civetweb.c 278 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324
  1. /* Copyright (c) 2013-2015 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #ifdef __linux__
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int clock_gettime(int clk_id, struct timespec *t)
  123. {
  124. if (clk_id == CLOCK_REALTIME) {
  125. struct timeval now;
  126. int rv = gettimeofday(&now, NULL);
  127. if (rv) {
  128. return rv;
  129. }
  130. t->tv_sec = now.tv_sec;
  131. t->tv_nsec = now.tv_usec * 1000;
  132. return 0;
  133. } else if (clk_id == CLOCK_MONOTONIC) {
  134. static uint64_t start_time = 0;
  135. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  136. uint64_t now = mach_absolute_time();
  137. if (start_time == 0) {
  138. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  139. #if defined(DEBUG)
  140. assert(mach_status == KERN_SUCCESS);
  141. #else
  142. /* appease "unused variable" warning for release builds */
  143. (void)mach_status;
  144. #endif
  145. start_time = now;
  146. }
  147. now =
  148. (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer /
  149. (double)timebase_ifo.denom);
  150. t->tv_sec = now / 1000000000;
  151. t->tv_nsec = now % 1000000000;
  152. return 0;
  153. }
  154. return -1; /* EINVAL - Clock ID is unknown */
  155. }
  156. #endif
  157. #include <time.h>
  158. #include <stdlib.h>
  159. #include <stdarg.h>
  160. #include <assert.h>
  161. #include <string.h>
  162. #include <ctype.h>
  163. #include <limits.h>
  164. #include <stddef.h>
  165. #include <stdio.h>
  166. #ifndef MAX_WORKER_THREADS
  167. #define MAX_WORKER_THREADS (1024 * 64)
  168. #endif
  169. #ifndef SOCKET_TIMEOUT_QUANTUM
  170. #define SOCKET_TIMEOUT_QUANTUM (10000)
  171. #endif
  172. mg_static_assert(MAX_WORKER_THREADS >= 1,
  173. "worker threads must be a positive number");
  174. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  175. #include <windows.h>
  176. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  177. #include <ws2tcpip.h>
  178. typedef const char *SOCK_OPT_TYPE;
  179. #if !defined(PATH_MAX)
  180. #define PATH_MAX (MAX_PATH)
  181. #endif
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (4096)
  184. #endif
  185. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  186. #ifndef _IN_PORT_T
  187. #ifndef in_port_t
  188. #define in_port_t u_short
  189. #endif
  190. #endif
  191. #ifndef _WIN32_WCE
  192. #include <process.h>
  193. #include <direct.h>
  194. #include <io.h>
  195. #else /* _WIN32_WCE */
  196. #define NO_CGI /* WinCE has no pipes */
  197. typedef long off_t;
  198. #define errno ((int)(GetLastError()))
  199. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  200. #endif /* _WIN32_WCE */
  201. #define MAKEUQUAD(lo, hi) \
  202. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  203. #define RATE_DIFF (10000000) /* 100 nsecs */
  204. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  205. #define SYS2UNIX_TIME(lo, hi) \
  206. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  207. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  208. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  209. * Also use _strtoui64 on modern M$ compilers */
  210. #if defined(_MSC_VER)
  211. #if (_MSC_VER < 1300)
  212. #define STRX(x) #x
  213. #define STR(x) STRX(x)
  214. #define __func__ __FILE__ ":" STR(__LINE__)
  215. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  216. #define strtoll(x, y, z) (_atoi64(x))
  217. #else
  218. #define __func__ __FUNCTION__
  219. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  220. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  221. #endif
  222. #endif /* _MSC_VER */
  223. #define ERRNO ((int)(GetLastError()))
  224. #define NO_SOCKLEN_T
  225. #define SSL_LIB "ssleay32.dll"
  226. #define CRYPTO_LIB "libeay32.dll"
  227. #define O_NONBLOCK (0)
  228. #ifndef W_OK
  229. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  230. #endif
  231. #if !defined(EWOULDBLOCK)
  232. #define EWOULDBLOCK WSAEWOULDBLOCK
  233. #endif /* !EWOULDBLOCK */
  234. #define _POSIX_
  235. #define INT64_FMT "I64d"
  236. #define WINCDECL __cdecl
  237. #define SHUT_RD (0)
  238. #define SHUT_WR (1)
  239. #define SHUT_BOTH (2)
  240. #define snprintf _snprintf
  241. #define vsnprintf _vsnprintf
  242. #define access _access
  243. #define mg_sleep(x) (Sleep(x))
  244. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  245. #ifndef popen
  246. #define popen(x, y) (_popen(x, y))
  247. #endif
  248. #ifndef pclose
  249. #define pclose(x) (_pclose(x))
  250. #endif
  251. #define close(x) (_close(x))
  252. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  253. #define RTLD_LAZY (0)
  254. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  255. #define fdopen(x, y) (_fdopen((x), (y)))
  256. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  257. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  258. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  259. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  260. #define sleep(x) (Sleep((x)*1000))
  261. #define rmdir(x) (_rmdir(x))
  262. #if !defined(fileno)
  263. #define fileno(x) (_fileno(x))
  264. #endif /* !fileno MINGW #defines fileno */
  265. typedef HANDLE pthread_mutex_t;
  266. typedef DWORD pthread_key_t;
  267. typedef HANDLE pthread_t;
  268. typedef struct {
  269. CRITICAL_SECTION threadIdSec;
  270. int waitingthreadcount; /* The number of threads queued. */
  271. pthread_t *waitingthreadhdls; /* The thread handles. */
  272. } pthread_cond_t;
  273. #ifndef __clockid_t_defined
  274. typedef DWORD clockid_t;
  275. #endif
  276. #ifndef CLOCK_MONOTONIC
  277. #define CLOCK_MONOTONIC (1)
  278. #endif
  279. #ifndef CLOCK_REALTIME
  280. #define CLOCK_REALTIME (2)
  281. #endif
  282. #ifndef _TIMESPEC_DEFINED
  283. struct timespec {
  284. time_t tv_sec; /* seconds */
  285. long tv_nsec; /* nanoseconds */
  286. };
  287. #endif
  288. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  289. static int pthread_mutex_lock(pthread_mutex_t *);
  290. static int pthread_mutex_unlock(pthread_mutex_t *);
  291. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  292. struct file;
  293. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  294. #if defined(HAVE_STDINT)
  295. #include <stdint.h>
  296. #else
  297. typedef unsigned int uint32_t;
  298. typedef unsigned short uint16_t;
  299. typedef unsigned __int64 uint64_t;
  300. typedef __int64 int64_t;
  301. #define INT64_MAX (9223372036854775807)
  302. #endif /* HAVE_STDINT */
  303. /* POSIX dirent interface */
  304. struct dirent {
  305. char d_name[PATH_MAX];
  306. };
  307. typedef struct DIR {
  308. HANDLE handle;
  309. WIN32_FIND_DATAW info;
  310. struct dirent result;
  311. } DIR;
  312. #if defined(_WIN32) && !defined(POLLIN)
  313. #ifndef HAVE_POLL
  314. struct pollfd {
  315. SOCKET fd;
  316. short events;
  317. short revents;
  318. };
  319. #define POLLIN (0x0300)
  320. #endif
  321. #endif
  322. /* Mark required libraries */
  323. #if defined(_MSC_VER)
  324. #pragma comment(lib, "Ws2_32.lib")
  325. #endif
  326. #else /* UNIX specific */
  327. #include <sys/wait.h>
  328. #include <sys/socket.h>
  329. #include <sys/poll.h>
  330. #include <netinet/in.h>
  331. #include <arpa/inet.h>
  332. #include <sys/time.h>
  333. #include <sys/utsname.h>
  334. #include <stdint.h>
  335. #include <inttypes.h>
  336. #include <netdb.h>
  337. typedef const void *SOCK_OPT_TYPE;
  338. #if defined(ANDROID)
  339. typedef unsigned short int in_port_t;
  340. #endif
  341. #include <pwd.h>
  342. #include <unistd.h>
  343. #include <grp.h>
  344. #include <dirent.h>
  345. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  346. #include <dlfcn.h>
  347. #endif
  348. #include <pthread.h>
  349. #if defined(__MACH__)
  350. #define SSL_LIB "libssl.dylib"
  351. #define CRYPTO_LIB "libcrypto.dylib"
  352. #else
  353. #if !defined(SSL_LIB)
  354. #define SSL_LIB "libssl.so"
  355. #endif
  356. #if !defined(CRYPTO_LIB)
  357. #define CRYPTO_LIB "libcrypto.so"
  358. #endif
  359. #endif
  360. #ifndef O_BINARY
  361. #define O_BINARY (0)
  362. #endif /* O_BINARY */
  363. #define closesocket(a) (close(a))
  364. #define mg_mkdir(x, y) (mkdir(x, y))
  365. #define mg_remove(x) (remove(x))
  366. #define mg_sleep(x) (usleep((x)*1000))
  367. #define ERRNO (errno)
  368. #define INVALID_SOCKET (-1)
  369. #define INT64_FMT PRId64
  370. typedef int SOCKET;
  371. #define WINCDECL
  372. #if defined(__hpux)
  373. /* HPUX 11 does not have monotonic, fall back to realtime */
  374. #ifndef CLOCK_MONOTONIC
  375. #define CLOCK_MONOTONIC CLOCK_REALTIME
  376. #endif
  377. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  378. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  379. * the prototypes use int* rather than socklen_t* which matches the
  380. * actual library expectation. When called with the wrong size arg
  381. * accept() returns a zero client inet addr and check_acl() always
  382. * fails. Since socklen_t is widely used below, just force replace
  383. * their typedef with int. - DTL
  384. */
  385. #define socklen_t int
  386. #endif /* hpux */
  387. #endif /* End of Windows and UNIX specific includes */
  388. /* va_copy should always be a macro, C99 and C++11 - DTL */
  389. #ifndef va_copy
  390. #define va_copy(x, y) ((x) = (y))
  391. #endif
  392. #ifdef _WIN32
  393. static CRITICAL_SECTION global_log_file_lock;
  394. static DWORD pthread_self(void) { return GetCurrentThreadId(); }
  395. static int pthread_key_create(
  396. pthread_key_t *key,
  397. void (*_must_be_zero)(
  398. void *) /* destructor function not supported for windows */)
  399. {
  400. assert(_must_be_zero == NULL);
  401. if ((key != 0) && (_must_be_zero == NULL)) {
  402. *key = TlsAlloc();
  403. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  404. }
  405. return -2;
  406. }
  407. static int pthread_key_delete(pthread_key_t key)
  408. {
  409. return TlsFree(key) ? 0 : 1;
  410. }
  411. static int pthread_setspecific(pthread_key_t key, void *value)
  412. {
  413. return TlsSetValue(key, value) ? 0 : 1;
  414. }
  415. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  416. static void *pthread_getspecific(pthread_key_t key) { return TlsGetValue(key); }
  417. #endif
  418. #endif /* _WIN32 */
  419. #include "civetweb.h"
  420. #define PASSWORDS_FILE_NAME ".htpasswd"
  421. #define CGI_ENVIRONMENT_SIZE (4096)
  422. #define MAX_CGI_ENVIR_VARS (64)
  423. #define MG_BUF_LEN (8192)
  424. #ifndef MAX_REQUEST_SIZE
  425. #define MAX_REQUEST_SIZE (16384)
  426. #endif
  427. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  428. "request size length must be a positive number");
  429. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  430. #if !defined(DEBUG_TRACE)
  431. #if defined(DEBUG)
  432. static void DEBUG_TRACE_FUNC(const char *func,
  433. unsigned line,
  434. PRINTF_FORMAT_STRING(const char *fmt),
  435. ...) PRINTF_ARGS(3, 4);
  436. static void
  437. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  438. {
  439. va_list args;
  440. flockfile(stdout);
  441. printf("*** %lu.%p.%s.%u: ",
  442. (unsigned long)time(NULL),
  443. (void *)pthread_self(),
  444. func,
  445. line);
  446. va_start(args, fmt);
  447. vprintf(fmt, args);
  448. va_end(args);
  449. putchar('\n');
  450. fflush(stdout);
  451. funlockfile(stdout);
  452. }
  453. #define DEBUG_TRACE(fmt, ...) \
  454. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  455. #else
  456. #define DEBUG_TRACE(fmt, ...) \
  457. do { \
  458. } while (0)
  459. #endif /* DEBUG */
  460. #endif /* DEBUG_TRACE */
  461. #if defined(MEMORY_DEBUGGING)
  462. unsigned long mg_memory_debug_blockCount = 0;
  463. unsigned long mg_memory_debug_totalMemUsed = 0;
  464. static void *mg_malloc_ex(size_t size, const char *file, unsigned line)
  465. {
  466. void *data = malloc(size + sizeof(size_t));
  467. void *memory = 0;
  468. char mallocStr[256];
  469. if (data) {
  470. *(size_t *)data = size;
  471. mg_memory_debug_totalMemUsed += size;
  472. mg_memory_debug_blockCount++;
  473. memory = (void *)(((char *)data) + sizeof(size_t));
  474. }
  475. sprintf(mallocStr,
  476. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  477. memory,
  478. (unsigned long)size,
  479. mg_memory_debug_totalMemUsed,
  480. mg_memory_debug_blockCount,
  481. file,
  482. line);
  483. #if defined(_WIN32)
  484. OutputDebugStringA(mallocStr);
  485. #else
  486. DEBUG_TRACE("%s", mallocStr);
  487. #endif
  488. return memory;
  489. }
  490. static void *
  491. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  492. {
  493. void *data = mg_malloc_ex(size * count, file, line);
  494. if (data) {
  495. memset(data, 0, size);
  496. }
  497. return data;
  498. }
  499. static void mg_free_ex(void *memory, const char *file, unsigned line)
  500. {
  501. char mallocStr[256];
  502. void *data = (void *)(((char *)memory) - sizeof(size_t));
  503. size_t size;
  504. if (memory) {
  505. size = *(size_t *)data;
  506. mg_memory_debug_totalMemUsed -= size;
  507. mg_memory_debug_blockCount--;
  508. sprintf(mallocStr,
  509. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  510. memory,
  511. (unsigned long)size,
  512. mg_memory_debug_totalMemUsed,
  513. mg_memory_debug_blockCount,
  514. file,
  515. line);
  516. #if defined(_WIN32)
  517. OutputDebugStringA(mallocStr);
  518. #else
  519. DEBUG_TRACE("%s", mallocStr);
  520. #endif
  521. free(data);
  522. }
  523. }
  524. static void *
  525. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  526. {
  527. char mallocStr[256];
  528. void *data;
  529. void *_realloc;
  530. size_t oldsize;
  531. if (newsize) {
  532. if (memory) {
  533. data = (void *)(((char *)memory) - sizeof(size_t));
  534. oldsize = *(size_t *)data;
  535. _realloc = realloc(data, newsize + sizeof(size_t));
  536. if (_realloc) {
  537. data = _realloc;
  538. mg_memory_debug_totalMemUsed -= oldsize;
  539. sprintf(mallocStr,
  540. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  541. memory,
  542. (unsigned long)oldsize,
  543. mg_memory_debug_totalMemUsed,
  544. mg_memory_debug_blockCount,
  545. file,
  546. line);
  547. #if defined(_WIN32)
  548. OutputDebugStringA(mallocStr);
  549. #else
  550. DEBUG_TRACE("%s", mallocStr);
  551. #endif
  552. mg_memory_debug_totalMemUsed += newsize;
  553. sprintf(mallocStr,
  554. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  555. memory,
  556. (unsigned long)newsize,
  557. mg_memory_debug_totalMemUsed,
  558. mg_memory_debug_blockCount,
  559. file,
  560. line);
  561. #if defined(_WIN32)
  562. OutputDebugStringA(mallocStr);
  563. #else
  564. DEBUG_TRACE("%s", mallocStr);
  565. #endif
  566. *(size_t *)data = newsize;
  567. data = (void *)(((char *)data) + sizeof(size_t));
  568. } else {
  569. #if defined(_WIN32)
  570. OutputDebugStringA("MEM: realloc failed\n");
  571. #else
  572. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  573. #endif
  574. return _realloc;
  575. }
  576. } else {
  577. data = mg_malloc_ex(newsize, file, line);
  578. }
  579. } else {
  580. data = 0;
  581. mg_free_ex(memory, file, line);
  582. }
  583. return data;
  584. }
  585. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  586. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  587. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  588. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  589. #else
  590. static __inline void *mg_malloc(size_t a) { return malloc(a); }
  591. static __inline void *mg_calloc(size_t a, size_t b) { return calloc(a, b); }
  592. static __inline void *mg_realloc(void *a, size_t b) { return realloc(a, b); }
  593. static __inline void mg_free(void *a) { free(a); }
  594. #endif
  595. /* This following lines are just meant as a reminder to use the mg-functions
  596. * for memory management */
  597. #ifdef malloc
  598. #undef malloc
  599. #endif
  600. #ifdef calloc
  601. #undef calloc
  602. #endif
  603. #ifdef realloc
  604. #undef realloc
  605. #endif
  606. #ifdef free
  607. #undef free
  608. #endif
  609. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  610. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  611. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  612. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  613. #define MD5_STATIC static
  614. #include "md5.inl"
  615. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  616. #ifdef NO_SOCKLEN_T
  617. typedef int socklen_t;
  618. #endif /* NO_SOCKLEN_T */
  619. #define _DARWIN_UNLIMITED_SELECT
  620. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  621. #if !defined(MSG_NOSIGNAL)
  622. #define MSG_NOSIGNAL (0)
  623. #endif
  624. #if !defined(SOMAXCONN)
  625. #define SOMAXCONN (100)
  626. #endif
  627. /* Size of the accepted socket queue */
  628. #if !defined(MGSQLEN)
  629. #define MGSQLEN (20)
  630. #endif
  631. #if defined(NO_SSL_DL)
  632. #include <openssl/ssl.h>
  633. #include <openssl/err.h>
  634. #else
  635. /* SSL loaded dynamically from DLL.
  636. * I put the prototypes here to be independent from OpenSSL source
  637. * installation. */
  638. typedef struct ssl_st SSL;
  639. typedef struct ssl_method_st SSL_METHOD;
  640. typedef struct ssl_ctx_st SSL_CTX;
  641. struct ssl_func {
  642. const char *name; /* SSL function name */
  643. void (*ptr)(void); /* Function pointer */
  644. };
  645. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  646. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  647. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  648. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  649. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  650. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  651. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  652. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  653. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  654. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  655. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  656. #define SSL_CTX_use_PrivateKey_file \
  657. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  658. #define SSL_CTX_use_certificate_file \
  659. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  660. #define SSL_CTX_set_default_passwd_cb \
  661. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  662. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  663. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  664. #define SSL_CTX_use_certificate_chain_file \
  665. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  666. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  667. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  668. #define SSL_CTX_set_verify (*(void (*)(SSL_CTX *, int, int))ssl_sw[19].ptr)
  669. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  670. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  671. #define CRYPTO_set_locking_callback \
  672. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  673. #define CRYPTO_set_id_callback \
  674. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  675. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  676. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  677. /* set_ssl_option() function updates this array.
  678. * It loads SSL library dynamically and changes NULLs to the actual addresses
  679. * of respective functions. The macros above (like SSL_connect()) are really
  680. * just calling these functions indirectly via the pointer. */
  681. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  682. {"SSL_accept", NULL},
  683. {"SSL_connect", NULL},
  684. {"SSL_read", NULL},
  685. {"SSL_write", NULL},
  686. {"SSL_get_error", NULL},
  687. {"SSL_set_fd", NULL},
  688. {"SSL_new", NULL},
  689. {"SSL_CTX_new", NULL},
  690. {"SSLv23_server_method", NULL},
  691. {"SSL_library_init", NULL},
  692. {"SSL_CTX_use_PrivateKey_file", NULL},
  693. {"SSL_CTX_use_certificate_file", NULL},
  694. {"SSL_CTX_set_default_passwd_cb", NULL},
  695. {"SSL_CTX_free", NULL},
  696. {"SSL_load_error_strings", NULL},
  697. {"SSL_CTX_use_certificate_chain_file", NULL},
  698. {"SSLv23_client_method", NULL},
  699. {"SSL_pending", NULL},
  700. {"SSL_CTX_set_verify", NULL},
  701. {"SSL_shutdown", NULL},
  702. {NULL, NULL}};
  703. /* Similar array as ssl_sw. These functions could be located in different
  704. * lib. */
  705. #if !defined(NO_SSL)
  706. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  707. {"CRYPTO_set_locking_callback", NULL},
  708. {"CRYPTO_set_id_callback", NULL},
  709. {"ERR_get_error", NULL},
  710. {"ERR_error_string", NULL},
  711. {NULL, NULL}};
  712. #endif /* NO_SSL */
  713. #endif /* NO_SSL_DL */
  714. static const char *month_names[] = {"Jan",
  715. "Feb",
  716. "Mar",
  717. "Apr",
  718. "May",
  719. "Jun",
  720. "Jul",
  721. "Aug",
  722. "Sep",
  723. "Oct",
  724. "Nov",
  725. "Dec"};
  726. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  727. * union u. */
  728. union usa {
  729. struct sockaddr sa;
  730. struct sockaddr_in sin;
  731. #if defined(USE_IPV6)
  732. struct sockaddr_in6 sin6;
  733. #endif
  734. };
  735. /* Describes a string (chunk of memory). */
  736. struct vec {
  737. const char *ptr;
  738. size_t len;
  739. };
  740. struct file {
  741. uint64_t size;
  742. time_t last_modified;
  743. FILE *fp;
  744. const char *membuf; /* Non-NULL if file data is in memory */
  745. int is_directory;
  746. int gzipped; /* set to 1 if the content is gzipped
  747. * in which case we need a content-encoding: gzip header */
  748. };
  749. #define STRUCT_FILE_INITIALIZER \
  750. { \
  751. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  752. }
  753. /* Describes listening socket, or socket which was accept()-ed by the master
  754. * thread and queued for future handling by the worker thread. */
  755. struct socket {
  756. SOCKET sock; /* Listening socket */
  757. union usa lsa; /* Local socket address */
  758. union usa rsa; /* Remote socket address */
  759. unsigned char is_ssl; /* Is port SSL-ed */
  760. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  761. * port */
  762. };
  763. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  764. enum {
  765. CGI_EXTENSIONS,
  766. CGI_ENVIRONMENT,
  767. PUT_DELETE_PASSWORDS_FILE,
  768. CGI_INTERPRETER,
  769. PROTECT_URI,
  770. AUTHENTICATION_DOMAIN,
  771. SSI_EXTENSIONS,
  772. THROTTLE,
  773. ACCESS_LOG_FILE,
  774. ENABLE_DIRECTORY_LISTING,
  775. ERROR_LOG_FILE,
  776. GLOBAL_PASSWORDS_FILE,
  777. INDEX_FILES,
  778. ENABLE_KEEP_ALIVE,
  779. ACCESS_CONTROL_LIST,
  780. EXTRA_MIME_TYPES,
  781. LISTENING_PORTS,
  782. DOCUMENT_ROOT,
  783. SSL_CERTIFICATE,
  784. NUM_THREADS,
  785. RUN_AS_USER,
  786. REWRITE,
  787. HIDE_FILES,
  788. REQUEST_TIMEOUT,
  789. #if defined(USE_WEBSOCKET)
  790. WEBSOCKET_TIMEOUT,
  791. #endif
  792. DECODE_URL,
  793. #if defined(USE_LUA)
  794. LUA_PRELOAD_FILE,
  795. LUA_SCRIPT_EXTENSIONS,
  796. LUA_SERVER_PAGE_EXTENSIONS,
  797. #endif
  798. #if defined(USE_WEBSOCKET)
  799. WEBSOCKET_ROOT,
  800. #endif
  801. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  802. LUA_WEBSOCKET_EXTENSIONS,
  803. #endif
  804. ACCESS_CONTROL_ALLOW_ORIGIN,
  805. ERROR_PAGES,
  806. NUM_OPTIONS
  807. };
  808. /* Config option name, config types, default value */
  809. static struct mg_option config_options[] = {
  810. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  811. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  812. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  813. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  814. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  815. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  816. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  817. {"throttle", CONFIG_TYPE_STRING, NULL},
  818. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  819. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  820. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  821. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  822. {"index_files",
  823. CONFIG_TYPE_STRING,
  824. #ifdef USE_LUA
  825. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  826. "index.shtml,index.php"},
  827. #else
  828. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  829. #endif
  830. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  831. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  832. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  833. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  834. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  835. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  836. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  837. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  838. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  839. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  840. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  841. #if defined(USE_WEBSOCKET)
  842. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  843. #endif
  844. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  845. #if defined(USE_LUA)
  846. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  847. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  848. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  849. #endif
  850. #if defined(USE_WEBSOCKET)
  851. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  852. #endif
  853. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  854. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  855. #endif
  856. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  857. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  858. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  859. /* Check if the config_options and the corresponding enum have compatible
  860. * sizes. */
  861. mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) ==
  862. (NUM_OPTIONS + 1),
  863. "config_options and enum not sync");
  864. struct mg_request_handler_info {
  865. /* Name/Pattern of the URI. */
  866. char *uri;
  867. size_t uri_len;
  868. /* URI type: ws/wss (websocket) or http/https (web page). */
  869. int is_websocket_handler;
  870. /* Handler for http/https requests. */
  871. mg_request_handler handler;
  872. /* Handler for ws/wss (websocket) requests. */
  873. mg_websocket_connect_handler connect_handler;
  874. mg_websocket_ready_handler ready_handler;
  875. mg_websocket_data_handler data_handler;
  876. mg_websocket_close_handler close_handler;
  877. /* User supplied argument for the handler function. */
  878. void *cbdata;
  879. /* next request handler in a linked list */
  880. struct mg_request_handler_info *next;
  881. };
  882. struct mg_context {
  883. volatile int stop_flag; /* Should we stop event loop */
  884. SSL_CTX *ssl_ctx; /* SSL context */
  885. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  886. struct mg_callbacks callbacks; /* User-defined callback function */
  887. void *user_data; /* User-defined data */
  888. int context_type; /* 1 = server context, 2 = client context */
  889. struct socket *listening_sockets;
  890. in_port_t *listening_ports;
  891. unsigned int num_listening_sockets;
  892. volatile int num_threads; /* Number of threads */
  893. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  894. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  895. struct socket queue[MGSQLEN]; /* Accepted sockets */
  896. volatile int sq_head; /* Head of the socket queue */
  897. volatile int sq_tail; /* Tail of the socket queue */
  898. pthread_cond_t sq_full; /* Signaled when socket is produced */
  899. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  900. pthread_t masterthreadid; /* The master thread ID */
  901. unsigned int workerthreadcount; /* The amount of worker threads. */
  902. pthread_t *workerthreadids; /* The worker thread IDs */
  903. unsigned long start_time; /* Server start time, used for authentication */
  904. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  905. unsigned long nonce_count; /* Used nonces, used for authentication */
  906. char *systemName; /* What operating system is running */
  907. /* linked list of uri handlers */
  908. struct mg_request_handler_info *request_handlers;
  909. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  910. /* linked list of shared lua websockets */
  911. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  912. #endif
  913. #ifdef USE_TIMERS
  914. struct ttimers *timers;
  915. #endif
  916. };
  917. struct mg_connection {
  918. struct mg_request_info request_info;
  919. struct mg_context *ctx;
  920. SSL *ssl; /* SSL descriptor */
  921. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  922. struct socket client; /* Connected client */
  923. time_t conn_birth_time; /* Time (wall clock) when connection was
  924. * established */
  925. struct timespec req_time; /* Time (since system start) when the request
  926. * was received */
  927. int64_t num_bytes_sent; /* Total bytes sent to client */
  928. int64_t content_len; /* Content-Length header value */
  929. int64_t consumed_content; /* How many bytes of content have been read */
  930. int is_chunked; /* Transfer-encoding is chunked: 0=no, 1=yes:
  931. * data available, 2: all data read */
  932. size_t chunk_remainder; /* Unread data from the last chunk */
  933. char *buf; /* Buffer for received data */
  934. char *path_info; /* PATH_INFO part of the URL */
  935. int must_close; /* 1 if connection must be closed */
  936. int in_error_handler; /* 1 if in handler for user defined error
  937. * pages */
  938. int buf_size; /* Buffer size */
  939. int request_len; /* Size of the request + headers in a buffer */
  940. int data_len; /* Total size of data in a buffer */
  941. int status_code; /* HTTP reply status code, e.g. 200 */
  942. int throttle; /* Throttling, bytes/sec. <= 0 means no
  943. * throttle */
  944. time_t last_throttle_time; /* Last time throttled data was sent */
  945. int64_t last_throttle_bytes; /* Bytes sent this second */
  946. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  947. * atomic transmissions for websockets */
  948. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  949. void *lua_websocket_state; /* Lua_State for a websocket connection */
  950. #endif
  951. };
  952. static pthread_key_t sTlsKey; /* Thread local storage index */
  953. static int sTlsInit = 0;
  954. struct mg_workerTLS {
  955. int is_master;
  956. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  957. HANDLE pthread_cond_helper_mutex;
  958. #endif
  959. };
  960. /* Directory entry */
  961. struct de {
  962. struct mg_connection *conn;
  963. char *file_name;
  964. struct file file;
  965. };
  966. #if defined(USE_WEBSOCKET)
  967. static int is_websocket_protocol(const struct mg_connection *conn);
  968. #else
  969. #define is_websocket_protocol(conn) (0)
  970. #endif
  971. static int mg_atomic_inc(volatile int *addr)
  972. {
  973. int ret;
  974. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  975. /* Depending on the SDK, this function uses either
  976. * (volatile unsigned int *) or (volatile LONG *),
  977. * so whatever you use, the other SDK is likely to raise a warning. */
  978. ret = InterlockedIncrement((volatile long *)addr);
  979. #elif defined(__GNUC__)
  980. ret = __sync_add_and_fetch(addr, 1);
  981. #else
  982. ret = (++(*addr));
  983. #endif
  984. return ret;
  985. }
  986. static int mg_atomic_dec(volatile int *addr)
  987. {
  988. int ret;
  989. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  990. /* Depending on the SDK, this function uses either
  991. * (volatile unsigned int *) or (volatile LONG *),
  992. * so whatever you use, the other SDK is likely to raise a warning. */
  993. ret = InterlockedDecrement((volatile long *)addr);
  994. #elif defined(__GNUC__)
  995. ret = __sync_sub_and_fetch(addr, 1);
  996. #else
  997. ret = (--(*addr));
  998. #endif
  999. return ret;
  1000. }
  1001. #if !defined(NO_THREAD_NAME)
  1002. #if defined(_WIN32) && defined(_MSC_VER)
  1003. /* Set the thread name for debugging purposes in Visual Studio
  1004. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1005. */
  1006. #pragma pack(push, 8)
  1007. typedef struct tagTHREADNAME_INFO {
  1008. DWORD dwType; /* Must be 0x1000. */
  1009. LPCSTR szName; /* Pointer to name (in user addr space). */
  1010. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1011. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1012. } THREADNAME_INFO;
  1013. #pragma pack(pop)
  1014. #elif defined(__linux__)
  1015. #include <sys/prctl.h>
  1016. #include <sys/sendfile.h>
  1017. #endif
  1018. static void mg_set_thread_name(const char *name)
  1019. {
  1020. char threadName[16]; /* Max. thread length in Linux/OSX/.. */
  1021. /* TODO (low): use strcpy and strcat instad of snprintf, use server name,
  1022. * don't
  1023. * return */
  1024. if (snprintf(threadName, sizeof(threadName), "civetweb-%s", name) < 0) {
  1025. return;
  1026. }
  1027. threadName[sizeof(threadName) - 1] = 0;
  1028. #if defined(_WIN32)
  1029. #if defined(_MSC_VER)
  1030. /* Windows and Visual Studio Compiler */
  1031. __try
  1032. {
  1033. THREADNAME_INFO info;
  1034. info.dwType = 0x1000;
  1035. info.szName = threadName;
  1036. info.dwThreadID = ~0U;
  1037. info.dwFlags = 0;
  1038. RaiseException(0x406D1388,
  1039. 0,
  1040. sizeof(info) / sizeof(ULONG_PTR),
  1041. (ULONG_PTR *)&info);
  1042. }
  1043. __except(EXCEPTION_EXECUTE_HANDLER) {}
  1044. #elif defined(__MINGW32__)
  1045. /* No option known to set thread name for MinGW */
  1046. #endif
  1047. #elif ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1048. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1049. (void)pthread_setname_np(pthread_self(), threadName);
  1050. #elif defined(__linux__)
  1051. /* on linux we can use the old prctl function */
  1052. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1053. #endif
  1054. }
  1055. #else /* !defined(NO_THREAD_NAME) */
  1056. void mg_set_thread_name(const char *threadName) {}
  1057. #endif
  1058. #if defined(MG_LEGACY_INTERFACE)
  1059. const char **mg_get_valid_option_names(void)
  1060. {
  1061. static const char *
  1062. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1063. int i;
  1064. for (i = 0; config_options[i].name != NULL; i++) {
  1065. data[i * 2] = config_options[i].name;
  1066. data[i * 2 + 1] = config_options[i].default_value;
  1067. }
  1068. return data;
  1069. }
  1070. #endif
  1071. const struct mg_option *mg_get_valid_options(void) { return config_options; }
  1072. static int is_file_in_memory(struct mg_connection *conn,
  1073. const char *path,
  1074. struct file *filep)
  1075. {
  1076. size_t size = 0;
  1077. if (!conn || !filep) {
  1078. return 0;
  1079. }
  1080. filep->last_modified = (time_t)0;
  1081. if ((filep->membuf =
  1082. conn->ctx->callbacks.open_file == NULL
  1083. ? NULL
  1084. : conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  1085. /* NOTE: override filep->size only on success. Otherwise, it might
  1086. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1087. filep->size = size;
  1088. }
  1089. return filep->membuf != NULL;
  1090. }
  1091. static int is_file_opened(const struct file *filep)
  1092. {
  1093. if (!filep) {
  1094. return 0;
  1095. }
  1096. return filep->membuf != NULL || filep->fp != NULL;
  1097. }
  1098. static int mg_fopen(struct mg_connection *conn,
  1099. const char *path,
  1100. const char *mode,
  1101. struct file *filep)
  1102. {
  1103. if (!filep) {
  1104. return 0;
  1105. }
  1106. if (!is_file_in_memory(conn, path, filep)) {
  1107. #ifdef _WIN32
  1108. wchar_t wbuf[PATH_MAX], wmode[20];
  1109. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1110. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1111. filep->fp = _wfopen(wbuf, wmode);
  1112. #else
  1113. filep->fp = fopen(path, mode);
  1114. #endif
  1115. }
  1116. return is_file_opened(filep);
  1117. }
  1118. static void mg_fclose(struct file *filep)
  1119. {
  1120. if (filep != NULL && filep->fp != NULL) {
  1121. fclose(filep->fp);
  1122. }
  1123. }
  1124. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  1125. {
  1126. for (; *src != '\0' && n > 1; n--) {
  1127. *dst++ = *src++;
  1128. }
  1129. *dst = '\0';
  1130. }
  1131. static int lowercase(const char *s)
  1132. {
  1133. return tolower(*(const unsigned char *)s);
  1134. }
  1135. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1136. {
  1137. int diff = 0;
  1138. if (len > 0) {
  1139. do {
  1140. diff = lowercase(s1++) - lowercase(s2++);
  1141. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1142. }
  1143. return diff;
  1144. }
  1145. static int mg_strcasecmp(const char *s1, const char *s2)
  1146. {
  1147. int diff;
  1148. do {
  1149. diff = lowercase(s1++) - lowercase(s2++);
  1150. } while (diff == 0 && s1[-1] != '\0');
  1151. return diff;
  1152. }
  1153. static char *mg_strndup(const char *ptr, size_t len)
  1154. {
  1155. char *p;
  1156. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1157. mg_strlcpy(p, ptr, len + 1);
  1158. }
  1159. return p;
  1160. }
  1161. static char *mg_strdup(const char *str) { return mg_strndup(str, strlen(str)); }
  1162. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  1163. {
  1164. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1165. if (big_len >= small_len) {
  1166. for (i = 0; i <= (big_len - small_len); i++) {
  1167. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1168. return big_str + i;
  1169. }
  1170. }
  1171. }
  1172. return NULL;
  1173. }
  1174. /* Like snprintf(), but never returns negative value, or a value
  1175. * that is larger than a supplied buffer.
  1176. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  1177. * in his audit report. */
  1178. static int mg_vsnprintf(struct mg_connection *conn,
  1179. char *buf,
  1180. size_t buflen,
  1181. const char *fmt,
  1182. va_list ap)
  1183. {
  1184. int n;
  1185. if (buflen == 0) {
  1186. return 0;
  1187. }
  1188. #ifdef __clang__
  1189. #pragma clang diagnostic push
  1190. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1191. /* Using fmt as a non-literal is intended here, since it is mostly called
  1192. * indirectly by mg_snprintf */
  1193. #endif
  1194. n = vsnprintf(buf, buflen, fmt, ap);
  1195. #ifdef __clang__
  1196. #pragma clang diagnostic pop
  1197. #endif
  1198. if (n < 0) {
  1199. mg_cry(conn, "vsnprintf error");
  1200. n = 0;
  1201. } else if (n >= (int)buflen) {
  1202. mg_cry(conn,
  1203. "truncating vsnprintf buffer: [%.*s]",
  1204. n > 200 ? 200 : n,
  1205. buf);
  1206. n = (int)buflen - 1;
  1207. }
  1208. buf[n] = '\0';
  1209. return n;
  1210. }
  1211. static int mg_snprintf(struct mg_connection *conn,
  1212. char *buf,
  1213. size_t buflen,
  1214. PRINTF_FORMAT_STRING(const char *fmt),
  1215. ...) PRINTF_ARGS(4, 5);
  1216. static int mg_snprintf(
  1217. struct mg_connection *conn, char *buf, size_t buflen, const char *fmt, ...)
  1218. {
  1219. va_list ap;
  1220. int n;
  1221. va_start(ap, fmt);
  1222. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  1223. va_end(ap);
  1224. return n;
  1225. }
  1226. static int get_option_index(const char *name)
  1227. {
  1228. int i;
  1229. for (i = 0; config_options[i].name != NULL; i++) {
  1230. if (strcmp(config_options[i].name, name) == 0) {
  1231. return i;
  1232. }
  1233. }
  1234. return -1;
  1235. }
  1236. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  1237. {
  1238. int i;
  1239. if ((i = get_option_index(name)) == -1) {
  1240. return NULL;
  1241. } else if (!ctx || ctx->config[i] == NULL) {
  1242. return "";
  1243. } else {
  1244. return ctx->config[i];
  1245. }
  1246. }
  1247. struct mg_context *mg_get_context(const struct mg_connection *conn)
  1248. {
  1249. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1250. }
  1251. void *mg_get_user_data(const struct mg_context *ctx)
  1252. {
  1253. return (ctx == NULL) ? NULL : ctx->user_data;
  1254. }
  1255. void mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1256. {
  1257. if (conn != NULL) {
  1258. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1259. }
  1260. }
  1261. void *mg_get_user_connection_data(const struct mg_connection *conn)
  1262. {
  1263. if (conn != NULL) {
  1264. return conn->request_info.conn_data;
  1265. }
  1266. return NULL;
  1267. }
  1268. size_t
  1269. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1270. {
  1271. size_t i;
  1272. if (!ctx) {
  1273. return 0;
  1274. }
  1275. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1276. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1277. ports[i] = ctx->listening_ports[i];
  1278. }
  1279. return i;
  1280. }
  1281. static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1282. {
  1283. buf[0] = '\0';
  1284. if (!usa) {
  1285. return;
  1286. }
  1287. if (usa->sa.sa_family == AF_INET) {
  1288. getnameinfo(&usa->sa,
  1289. sizeof(usa->sin),
  1290. buf,
  1291. (unsigned)len,
  1292. NULL,
  1293. 0,
  1294. NI_NUMERICHOST);
  1295. }
  1296. #if defined(USE_IPV6)
  1297. else if (usa->sa.sa_family == AF_INET6) {
  1298. getnameinfo(&usa->sa,
  1299. sizeof(usa->sin6),
  1300. buf,
  1301. (unsigned)len,
  1302. NULL,
  1303. 0,
  1304. NI_NUMERICHOST);
  1305. }
  1306. #endif
  1307. }
  1308. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1309. * included in all responses other than 100, 101, 5xx. */
  1310. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1311. {
  1312. struct tm *tm;
  1313. tm = gmtime(t);
  1314. if (tm != NULL) {
  1315. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1316. } else {
  1317. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1318. buf[buf_len - 1] = '\0';
  1319. }
  1320. }
  1321. /* difftime for struct timespec. Return value is in seconds. */
  1322. static double mg_difftimespec(const struct timespec *ts_now,
  1323. const struct timespec *ts_before)
  1324. {
  1325. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 +
  1326. (double)(ts_now->tv_sec - ts_before->tv_sec);
  1327. }
  1328. /* Print error message to the opened error log stream. */
  1329. void mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1330. {
  1331. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1332. va_list ap;
  1333. FILE *fp;
  1334. time_t timestamp;
  1335. va_start(ap, fmt);
  1336. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  1337. va_end(ap);
  1338. /* Do not lock when getting the callback value, here and below.
  1339. * I suppose this is fine, since function cannot disappear in the
  1340. * same way string option can. */
  1341. if (conn && (conn->ctx->callbacks.log_message == NULL ||
  1342. conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1343. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1344. ? NULL
  1345. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1346. if (fp != NULL) {
  1347. flockfile(fp);
  1348. timestamp = time(NULL);
  1349. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1350. fprintf(fp,
  1351. "[%010lu] [error] [client %s] ",
  1352. (unsigned long)timestamp,
  1353. src_addr);
  1354. if (conn->request_info.request_method != NULL) {
  1355. fprintf(fp,
  1356. "%s %s: ",
  1357. conn->request_info.request_method,
  1358. conn->request_info.uri);
  1359. }
  1360. fprintf(fp, "%s", buf);
  1361. fputc('\n', fp);
  1362. funlockfile(fp);
  1363. fclose(fp);
  1364. }
  1365. }
  1366. }
  1367. /* Return fake connection structure. Used for logging, if connection
  1368. * is not applicable at the moment of logging. */
  1369. static struct mg_connection *fc(struct mg_context *ctx)
  1370. {
  1371. static struct mg_connection fake_connection;
  1372. fake_connection.ctx = ctx;
  1373. return &fake_connection;
  1374. }
  1375. const char *mg_version(void) { return CIVETWEB_VERSION; }
  1376. const struct mg_request_info *
  1377. mg_get_request_info(const struct mg_connection *conn)
  1378. {
  1379. if (!conn) {
  1380. return NULL;
  1381. }
  1382. return &conn->request_info;
  1383. }
  1384. /* Skip the characters until one of the delimiters characters found.
  1385. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1386. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1387. * Delimiters can be quoted with quotechar. */
  1388. static char *skip_quoted(char **buf,
  1389. const char *delimiters,
  1390. const char *whitespace,
  1391. char quotechar)
  1392. {
  1393. char *p, *begin_word, *end_word, *end_whitespace;
  1394. begin_word = *buf;
  1395. end_word = begin_word + strcspn(begin_word, delimiters);
  1396. /* Check for quotechar */
  1397. if (end_word > begin_word) {
  1398. p = end_word - 1;
  1399. while (*p == quotechar) {
  1400. /* TODO (bel, low): it seems this code is never reached, so
  1401. * quotechar is actually not needed - check if this code may be
  1402. * droped */
  1403. /* If there is anything beyond end_word, copy it */
  1404. if (*end_word == '\0') {
  1405. *p = '\0';
  1406. break;
  1407. } else {
  1408. size_t end_off = strcspn(end_word + 1, delimiters);
  1409. memmove(p, end_word, end_off + 1);
  1410. p += end_off; /* p must correspond to end_word - 1 */
  1411. end_word += end_off + 1;
  1412. }
  1413. }
  1414. for (p++; p < end_word; p++) {
  1415. *p = '\0';
  1416. }
  1417. }
  1418. if (*end_word == '\0') {
  1419. *buf = end_word;
  1420. } else {
  1421. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1422. for (p = end_word; p < end_whitespace; p++) {
  1423. *p = '\0';
  1424. }
  1425. *buf = end_whitespace;
  1426. }
  1427. return begin_word;
  1428. }
  1429. /* Simplified version of skip_quoted without quote char
  1430. * and whitespace == delimiters */
  1431. static char *skip(char **buf, const char *delimiters)
  1432. {
  1433. return skip_quoted(buf, delimiters, delimiters, 0);
  1434. }
  1435. /* Return HTTP header value, or NULL if not found. */
  1436. static const char *get_header(const struct mg_request_info *ri,
  1437. const char *name)
  1438. {
  1439. int i;
  1440. if (ri) {
  1441. for (i = 0; i < ri->num_headers; i++) {
  1442. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1443. return ri->http_headers[i].value;
  1444. }
  1445. }
  1446. }
  1447. return NULL;
  1448. }
  1449. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  1450. {
  1451. if (!conn) {
  1452. return NULL;
  1453. }
  1454. return get_header(&conn->request_info, name);
  1455. }
  1456. /* A helper function for traversing a comma separated list of values.
  1457. * It returns a list pointer shifted to the next value, or NULL if the end
  1458. * of the list found.
  1459. * Value is stored in val vector. If value has form "x=y", then eq_val
  1460. * vector is initialized to point to the "y" part, and val vector length
  1461. * is adjusted to point only to "x". */
  1462. static const char *
  1463. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1464. {
  1465. if (val == NULL || list == NULL || *list == '\0') {
  1466. /* End of the list */
  1467. list = NULL;
  1468. } else {
  1469. val->ptr = list;
  1470. if ((list = strchr(val->ptr, ',')) != NULL) {
  1471. /* Comma found. Store length and shift the list ptr */
  1472. val->len = ((size_t)(list - val->ptr));
  1473. list++;
  1474. } else {
  1475. /* This value is the last one */
  1476. list = val->ptr + strlen(val->ptr);
  1477. val->len = ((size_t)(list - val->ptr));
  1478. }
  1479. if (eq_val != NULL) {
  1480. /* Value has form "x=y", adjust pointers and lengths
  1481. * so that val points to "x", and eq_val points to "y". */
  1482. eq_val->len = 0;
  1483. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1484. if (eq_val->ptr != NULL) {
  1485. eq_val->ptr++; /* Skip over '=' character */
  1486. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1487. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1488. }
  1489. }
  1490. }
  1491. return list;
  1492. }
  1493. /* Perform case-insensitive match of string against pattern */
  1494. static int
  1495. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1496. {
  1497. const char *or_str;
  1498. size_t i;
  1499. int j, len, res;
  1500. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1501. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1502. return res > 0 ? res : match_prefix(or_str + 1,
  1503. (size_t)((pattern + pattern_len) -
  1504. (or_str + 1)),
  1505. str);
  1506. }
  1507. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1508. if (pattern[i] == '?' && str[j] != '\0') {
  1509. continue;
  1510. } else if (pattern[i] == '$') {
  1511. return str[j] == '\0' ? j : -1;
  1512. } else if (pattern[i] == '*') {
  1513. i++;
  1514. if (pattern[i] == '*') {
  1515. i++;
  1516. len = (int)strlen(str + j);
  1517. } else {
  1518. len = (int)strcspn(str + j, "/");
  1519. }
  1520. if (i == pattern_len) {
  1521. return j + len;
  1522. }
  1523. do {
  1524. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1525. } while (res == -1 && len-- > 0);
  1526. return res == -1 ? -1 : j + res + len;
  1527. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1528. return -1;
  1529. }
  1530. }
  1531. return j;
  1532. }
  1533. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1534. * This function must tolerate situations when connection info is not
  1535. * set up, for example if request parsing failed. */
  1536. static int should_keep_alive(const struct mg_connection *conn)
  1537. {
  1538. if (conn != NULL) {
  1539. const char *http_version = conn->request_info.http_version;
  1540. const char *header = mg_get_header(conn, "Connection");
  1541. if (conn->must_close || conn->status_code == 401 ||
  1542. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1543. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1544. (header == NULL && http_version &&
  1545. 0 != strcmp(http_version, "1.1"))) {
  1546. return 0;
  1547. }
  1548. return 1;
  1549. }
  1550. return 0;
  1551. }
  1552. static int should_decode_url(const struct mg_connection *conn)
  1553. {
  1554. if (!conn || !conn->ctx) {
  1555. return 0;
  1556. }
  1557. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1558. }
  1559. static const char *suggest_connection_header(const struct mg_connection *conn)
  1560. {
  1561. return should_keep_alive(conn) ? "keep-alive" : "close";
  1562. }
  1563. static void handle_file_based_request(struct mg_connection *conn,
  1564. const char *path,
  1565. struct file *filep);
  1566. static int
  1567. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1568. static const char *mg_get_response_code_text(int response_code,
  1569. struct mg_connection *conn)
  1570. {
  1571. switch (response_code) {
  1572. /* RFC2616 Section 10.1 - Informational 1xx */
  1573. case 100:
  1574. return "Continue"; /* RFC2616 Section 10.1.1 */
  1575. case 101:
  1576. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1577. case 102:
  1578. return "Processing"; /* RFC2518 Section 10.1 */
  1579. /* RFC2616 Section 10.2 - Successful 2xx */
  1580. case 200:
  1581. return "OK"; /* RFC2616 Section 10.2.1 */
  1582. case 201:
  1583. return "Created"; /* RFC2616 Section 10.2.2 */
  1584. case 202:
  1585. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1586. case 203:
  1587. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1588. case 204:
  1589. return "No Content"; /* RFC2616 Section 10.2.5 */
  1590. case 205:
  1591. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1592. case 206:
  1593. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1594. case 207:
  1595. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1596. /* RFC2616 Section 10.3 - Redirection 3xx */
  1597. case 300:
  1598. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1599. case 301:
  1600. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1601. case 302:
  1602. return "Found"; /* RFC2616 Section 10.3.3 */
  1603. case 303:
  1604. return "See Other"; /* RFC2616 Section 10.3.4 */
  1605. case 304:
  1606. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1607. case 305:
  1608. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1609. case 307:
  1610. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1611. /* RFC2616 Section 10.4 - Client Error 4xx */
  1612. case 400:
  1613. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1614. case 401:
  1615. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1616. case 402:
  1617. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1618. case 403:
  1619. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1620. case 404:
  1621. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1622. case 405:
  1623. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1624. case 406:
  1625. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1626. case 407:
  1627. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1628. case 408:
  1629. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1630. case 409:
  1631. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1632. case 410:
  1633. return "Gone"; /* RFC2616 Section 10.4.11 */
  1634. case 411:
  1635. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1636. case 412:
  1637. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1638. case 413:
  1639. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1640. case 414:
  1641. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1642. case 415:
  1643. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1644. case 416:
  1645. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1646. case 417:
  1647. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1648. case 422:
  1649. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1650. * Section 11.2 */
  1651. case 423:
  1652. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1653. case 424:
  1654. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1655. * Section 11.4 */
  1656. case 428:
  1657. return "Precondition Required"; /* RFC 6585, Section 3 */
  1658. case 429:
  1659. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1660. case 431:
  1661. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1662. /* RFC2616 Section 10.5 - Server Error 5xx */
  1663. case 500:
  1664. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1665. case 501:
  1666. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1667. case 502:
  1668. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1669. case 503:
  1670. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1671. case 504:
  1672. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1673. case 505:
  1674. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1675. case 507:
  1676. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1677. * Section 11.5 */
  1678. case 511:
  1679. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1680. /* Other RFCs */
  1681. case 426:
  1682. return "Upgrade Required"; /* RFC 2817 */
  1683. /* Return codes from non normative RFCs: */
  1684. /* Informative and experimental RFCs, "de facto" standards due to common
  1685. * use, ... */
  1686. case 208:
  1687. return "Already Reported"; /* RFC5842 Section 7.1 */
  1688. case 226:
  1689. return "IM used"; /* RFC3229 Section 10.4.1 */
  1690. case 308:
  1691. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1692. case 418:
  1693. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1694. case 419:
  1695. return "Authentication Timeout"; /* common use */
  1696. case 451:
  1697. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1698. * Section 3 */
  1699. case 506:
  1700. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1701. case 508:
  1702. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1703. case 510:
  1704. return "Not Extended"; /* RFC 2774, Section 7 */
  1705. default:
  1706. /* This error code is unknown. This should not happen. */
  1707. if (conn) {
  1708. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1709. }
  1710. /* Return at least a category according to RFC 2616 Section 10. */
  1711. if (response_code >= 100 && response_code < 200) {
  1712. /* Unknown informational status code */
  1713. return "Information";
  1714. }
  1715. if (response_code >= 200 && response_code < 300) {
  1716. /* Unknown success code */
  1717. return "Success";
  1718. }
  1719. if (response_code >= 300 && response_code < 400) {
  1720. /* Unknown redirection code */
  1721. return "Redirection";
  1722. }
  1723. if (response_code >= 400 && response_code < 500) {
  1724. /* Unknown request error code */
  1725. return "Client Error";
  1726. }
  1727. if (response_code >= 500 && response_code < 600) {
  1728. /* Unknown server error code */
  1729. return "Server Error";
  1730. }
  1731. /* Response code not even within reasonable range */
  1732. return "";
  1733. }
  1734. }
  1735. static void send_http_error(struct mg_connection *,
  1736. int,
  1737. PRINTF_FORMAT_STRING(const char *fmt),
  1738. ...) PRINTF_ARGS(3, 4);
  1739. static void
  1740. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1741. {
  1742. char buf[MG_BUF_LEN];
  1743. va_list ap;
  1744. int len = 0, i, page_handler_found, scope;
  1745. char date[64];
  1746. time_t curtime = time(NULL);
  1747. const char *error_handler = NULL;
  1748. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1749. const char *error_page_file_ext, *tstr;
  1750. const char *status_text = mg_get_response_code_text(status, conn);
  1751. if (conn == NULL) {
  1752. return;
  1753. }
  1754. conn->status_code = status;
  1755. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL ||
  1756. conn->ctx->callbacks.http_error(conn, status)) {
  1757. if (!conn->in_error_handler) {
  1758. /* Send user defined error pages, if defined */
  1759. error_handler = conn->ctx->config[ERROR_PAGES];
  1760. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1761. page_handler_found = 0;
  1762. if (error_handler != NULL) {
  1763. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1764. switch (scope) {
  1765. case 1:
  1766. len = mg_snprintf(conn,
  1767. buf,
  1768. sizeof(buf) - 32,
  1769. "%serror%03u.",
  1770. error_handler,
  1771. status);
  1772. break;
  1773. case 2:
  1774. len = mg_snprintf(conn,
  1775. buf,
  1776. sizeof(buf) - 32,
  1777. "%serror%01uxx.",
  1778. error_handler,
  1779. status / 100);
  1780. break;
  1781. default:
  1782. len = mg_snprintf(conn,
  1783. buf,
  1784. sizeof(buf) - 32,
  1785. "%serror.",
  1786. error_handler);
  1787. break;
  1788. }
  1789. tstr = strchr(error_page_file_ext, '.');
  1790. while (tstr) {
  1791. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  1792. i++)
  1793. buf[len + i - 1] = tstr[i];
  1794. buf[len + i - 1] = 0;
  1795. if (mg_stat(conn, buf, &error_page_file)) {
  1796. page_handler_found = 1;
  1797. break;
  1798. }
  1799. tstr = strchr(tstr + i, '.');
  1800. }
  1801. }
  1802. }
  1803. if (page_handler_found) {
  1804. conn->in_error_handler = 1;
  1805. handle_file_based_request(conn, buf, &error_page_file);
  1806. conn->in_error_handler = 0;
  1807. return;
  1808. }
  1809. }
  1810. buf[0] = '\0';
  1811. gmt_time_string(date, sizeof(date), &curtime);
  1812. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1813. if (status > 199 && status != 204 && status != 304) {
  1814. len = mg_snprintf(conn,
  1815. buf,
  1816. sizeof(buf) - 1,
  1817. "Error %d: %s",
  1818. status,
  1819. status_text);
  1820. buf[len] = '\n';
  1821. len++;
  1822. buf[len] = 0;
  1823. va_start(ap, fmt);
  1824. len += mg_vsnprintf(
  1825. conn, buf + len, sizeof(buf) - (size_t)len, fmt, ap);
  1826. va_end(ap);
  1827. }
  1828. DEBUG_TRACE("[%s]", buf);
  1829. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  1830. if (len > 0) {
  1831. mg_printf(conn, "Content-Type: text/plain\r\n");
  1832. }
  1833. mg_printf(conn,
  1834. "Content-Length: %d\r\n"
  1835. "Date: %s\r\n"
  1836. "Connection: %s\r\n\r\n",
  1837. len,
  1838. date,
  1839. suggest_connection_header(conn));
  1840. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  1841. }
  1842. }
  1843. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1844. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  1845. {
  1846. (void)unused;
  1847. *mutex = CreateMutex(NULL, FALSE, NULL);
  1848. return *mutex == NULL ? -1 : 0;
  1849. }
  1850. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  1851. {
  1852. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1853. }
  1854. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  1855. {
  1856. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  1857. }
  1858. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  1859. static int pthread_mutex_trylock(pthread_mutex_t *mutex)
  1860. {
  1861. switch (WaitForSingleObject(*mutex, 0)) {
  1862. case WAIT_OBJECT_0:
  1863. return 0;
  1864. case WAIT_TIMEOUT:
  1865. return -2; /* EBUSY */
  1866. }
  1867. return -1;
  1868. }
  1869. #endif
  1870. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  1871. {
  1872. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1873. }
  1874. #ifndef WIN_PTHREADS_TIME_H
  1875. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  1876. {
  1877. FILETIME ft;
  1878. ULARGE_INTEGER li;
  1879. BOOL ok = FALSE;
  1880. double d;
  1881. static double perfcnt_per_sec = 0.0;
  1882. if (tp) {
  1883. if (clk_id == CLOCK_REALTIME) {
  1884. GetSystemTimeAsFileTime(&ft);
  1885. li.LowPart = ft.dwLowDateTime;
  1886. li.HighPart = ft.dwHighDateTime;
  1887. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1888. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1889. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1890. ok = TRUE;
  1891. } else if (clk_id == CLOCK_MONOTONIC) {
  1892. if (perfcnt_per_sec == 0.0) {
  1893. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  1894. perfcnt_per_sec = 1.0 / li.QuadPart;
  1895. }
  1896. if (perfcnt_per_sec != 0.0) {
  1897. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  1898. d = li.QuadPart * perfcnt_per_sec;
  1899. tp->tv_sec = (time_t)d;
  1900. d -= tp->tv_sec;
  1901. tp->tv_nsec = (long)(d * 1.0E9);
  1902. ok = TRUE;
  1903. }
  1904. }
  1905. }
  1906. return ok ? 0 : -1;
  1907. }
  1908. #endif
  1909. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1910. {
  1911. (void)unused;
  1912. InitializeCriticalSection(&cv->threadIdSec);
  1913. cv->waitingthreadcount = 0;
  1914. cv->waitingthreadhdls =
  1915. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1916. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  1917. }
  1918. static int pthread_cond_timedwait(pthread_cond_t *cv,
  1919. pthread_mutex_t *mutex,
  1920. const struct timespec *abstime)
  1921. {
  1922. struct mg_workerTLS *tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1923. int ok;
  1924. struct timespec tsnow;
  1925. int64_t nsnow, nswaitabs, nswaitrel;
  1926. DWORD mswaitrel;
  1927. EnterCriticalSection(&cv->threadIdSec);
  1928. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1929. cv->waitingthreadhdls[cv->waitingthreadcount] =
  1930. tls->pthread_cond_helper_mutex;
  1931. cv->waitingthreadcount++;
  1932. LeaveCriticalSection(&cv->threadIdSec);
  1933. if (abstime) {
  1934. clock_gettime(CLOCK_REALTIME, &tsnow);
  1935. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  1936. nswaitabs =
  1937. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  1938. nswaitrel = nswaitabs - nsnow;
  1939. if (nswaitrel < 0) {
  1940. nswaitrel = 0;
  1941. }
  1942. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1943. } else {
  1944. mswaitrel = INFINITE;
  1945. }
  1946. pthread_mutex_unlock(mutex);
  1947. ok = (WAIT_OBJECT_0 ==
  1948. WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1949. pthread_mutex_lock(mutex);
  1950. return ok ? 0 : -1;
  1951. }
  1952. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  1953. {
  1954. return pthread_cond_timedwait(cv, mutex, NULL);
  1955. }
  1956. static int pthread_cond_signal(pthread_cond_t *cv)
  1957. {
  1958. int i;
  1959. HANDLE wkup = NULL;
  1960. BOOL ok = FALSE;
  1961. EnterCriticalSection(&cv->threadIdSec);
  1962. if (cv->waitingthreadcount) {
  1963. wkup = cv->waitingthreadhdls[0];
  1964. ok = SetEvent(wkup);
  1965. for (i = 1; i < cv->waitingthreadcount; i++) {
  1966. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  1967. }
  1968. cv->waitingthreadcount--;
  1969. assert(ok);
  1970. }
  1971. LeaveCriticalSection(&cv->threadIdSec);
  1972. return ok ? 0 : 1;
  1973. }
  1974. static int pthread_cond_broadcast(pthread_cond_t *cv)
  1975. {
  1976. EnterCriticalSection(&cv->threadIdSec);
  1977. while (cv->waitingthreadcount) {
  1978. pthread_cond_signal(cv);
  1979. }
  1980. LeaveCriticalSection(&cv->threadIdSec);
  1981. return 0;
  1982. }
  1983. static int pthread_cond_destroy(pthread_cond_t *cv)
  1984. {
  1985. EnterCriticalSection(&cv->threadIdSec);
  1986. assert(cv->waitingthreadcount == 0);
  1987. mg_free(cv->waitingthreadhdls);
  1988. cv->waitingthreadhdls = 0;
  1989. LeaveCriticalSection(&cv->threadIdSec);
  1990. DeleteCriticalSection(&cv->threadIdSec);
  1991. return 0;
  1992. }
  1993. /* For Windows, change all slashes to backslashes in path names. */
  1994. static void change_slashes_to_backslashes(char *path)
  1995. {
  1996. int i;
  1997. for (i = 0; path[i] != '\0'; i++) {
  1998. if (path[i] == '/') {
  1999. path[i] = '\\';
  2000. }
  2001. /* remove double backslash (check i > 0 to preserve UNC paths,
  2002. * like \\server\file.txt) */
  2003. if ((path[i] == '\\') && (i > 0)) {
  2004. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2005. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2006. }
  2007. }
  2008. }
  2009. }
  2010. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2011. * wbuf and wbuf_len is a target buffer and its length. */
  2012. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2013. {
  2014. char buf[PATH_MAX], buf2[PATH_MAX];
  2015. mg_strlcpy(buf, path, sizeof(buf));
  2016. change_slashes_to_backslashes(buf);
  2017. /* Convert to Unicode and back. If doubly-converted string does not
  2018. * match the original, something is fishy, reject. */
  2019. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2020. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2021. WideCharToMultiByte(
  2022. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2023. if (strcmp(buf, buf2) != 0) {
  2024. wbuf[0] = L'\0';
  2025. }
  2026. }
  2027. #if defined(_WIN32_WCE)
  2028. static time_t time(time_t *ptime)
  2029. {
  2030. time_t t;
  2031. SYSTEMTIME st;
  2032. FILETIME ft;
  2033. GetSystemTime(&st);
  2034. SystemTimeToFileTime(&st, &ft);
  2035. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2036. if (ptime != NULL) {
  2037. *ptime = t;
  2038. }
  2039. return t;
  2040. }
  2041. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  2042. {
  2043. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2044. FILETIME ft, lft;
  2045. SYSTEMTIME st;
  2046. TIME_ZONE_INFORMATION tzinfo;
  2047. if (ptm == NULL) {
  2048. return NULL;
  2049. }
  2050. *(int64_t *)&ft = t;
  2051. FileTimeToLocalFileTime(&ft, &lft);
  2052. FileTimeToSystemTime(&lft, &st);
  2053. ptm->tm_year = st.wYear - 1900;
  2054. ptm->tm_mon = st.wMonth - 1;
  2055. ptm->tm_wday = st.wDayOfWeek;
  2056. ptm->tm_mday = st.wDay;
  2057. ptm->tm_hour = st.wHour;
  2058. ptm->tm_min = st.wMinute;
  2059. ptm->tm_sec = st.wSecond;
  2060. ptm->tm_yday = 0; /* hope nobody uses this */
  2061. ptm->tm_isdst =
  2062. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2063. return ptm;
  2064. }
  2065. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  2066. {
  2067. /* FIXME(lsm): fix this. */
  2068. return localtime(ptime, ptm);
  2069. }
  2070. static size_t
  2071. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2072. {
  2073. (void)snprintf(dst, dst_size, "implement strftime() for WinCE");
  2074. return 0;
  2075. }
  2076. #endif
  2077. /* Windows happily opens files with some garbage at the end of file name.
  2078. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2079. * "a.cgi", despite one would expect an error back.
  2080. * This function returns non-0 if path ends with some garbage. */
  2081. static int path_cannot_disclose_cgi(const char *path)
  2082. {
  2083. static const char *allowed_last_characters = "_-";
  2084. int last = path[strlen(path) - 1];
  2085. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2086. }
  2087. static int
  2088. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2089. {
  2090. wchar_t wbuf[PATH_MAX];
  2091. WIN32_FILE_ATTRIBUTE_DATA info;
  2092. time_t creation_time;
  2093. if (!filep) {
  2094. return 0;
  2095. }
  2096. memset(filep, 0, sizeof(*filep));
  2097. if (conn && is_file_in_memory(conn, path, filep)) {
  2098. return 1;
  2099. }
  2100. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2101. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2102. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2103. filep->last_modified =
  2104. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2105. info.ftLastWriteTime.dwHighDateTime);
  2106. /* On Windows, the file creation time can be higher than the
  2107. * modification time, e.g. when a file is copied.
  2108. * Since the Last-Modified timestamp is used for caching
  2109. * it should be based on the most recent timestamp. */
  2110. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2111. info.ftCreationTime.dwHighDateTime);
  2112. if (creation_time > filep->last_modified) {
  2113. filep->last_modified = creation_time;
  2114. }
  2115. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2116. /* If file name is fishy, reset the file structure and return
  2117. * error.
  2118. * Note it is important to reset, not just return the error, cause
  2119. * functions like is_file_opened() check the struct. */
  2120. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2121. memset(filep, 0, sizeof(*filep));
  2122. return 0;
  2123. }
  2124. return 1;
  2125. }
  2126. return 0;
  2127. }
  2128. static int mg_remove(const char *path)
  2129. {
  2130. wchar_t wbuf[PATH_MAX];
  2131. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2132. return DeleteFileW(wbuf) ? 0 : -1;
  2133. }
  2134. static int mg_mkdir(const char *path, int mode)
  2135. {
  2136. char buf[PATH_MAX];
  2137. wchar_t wbuf[PATH_MAX];
  2138. (void)mode;
  2139. mg_strlcpy(buf, path, sizeof(buf));
  2140. change_slashes_to_backslashes(buf);
  2141. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2142. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2143. }
  2144. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2145. static DIR *opendir(const char *name)
  2146. {
  2147. DIR *dir = NULL;
  2148. wchar_t wpath[PATH_MAX];
  2149. DWORD attrs;
  2150. if (name == NULL) {
  2151. SetLastError(ERROR_BAD_ARGUMENTS);
  2152. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2153. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2154. } else {
  2155. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2156. attrs = GetFileAttributesW(wpath);
  2157. if (attrs != 0xFFFFFFFF &&
  2158. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2159. (void)wcscat(wpath, L"\\*");
  2160. dir->handle = FindFirstFileW(wpath, &dir->info);
  2161. dir->result.d_name[0] = '\0';
  2162. } else {
  2163. mg_free(dir);
  2164. dir = NULL;
  2165. }
  2166. }
  2167. return dir;
  2168. }
  2169. static int closedir(DIR *dir)
  2170. {
  2171. int result = 0;
  2172. if (dir != NULL) {
  2173. if (dir->handle != INVALID_HANDLE_VALUE)
  2174. result = FindClose(dir->handle) ? 0 : -1;
  2175. mg_free(dir);
  2176. } else {
  2177. result = -1;
  2178. SetLastError(ERROR_BAD_ARGUMENTS);
  2179. }
  2180. return result;
  2181. }
  2182. static struct dirent *readdir(DIR *dir)
  2183. {
  2184. struct dirent *result = 0;
  2185. if (dir) {
  2186. if (dir->handle != INVALID_HANDLE_VALUE) {
  2187. result = &dir->result;
  2188. (void)WideCharToMultiByte(CP_UTF8,
  2189. 0,
  2190. dir->info.cFileName,
  2191. -1,
  2192. result->d_name,
  2193. sizeof(result->d_name),
  2194. NULL,
  2195. NULL);
  2196. if (!FindNextFileW(dir->handle, &dir->info)) {
  2197. (void)FindClose(dir->handle);
  2198. dir->handle = INVALID_HANDLE_VALUE;
  2199. }
  2200. } else {
  2201. SetLastError(ERROR_FILE_NOT_FOUND);
  2202. }
  2203. } else {
  2204. SetLastError(ERROR_BAD_ARGUMENTS);
  2205. }
  2206. return result;
  2207. }
  2208. #ifndef HAVE_POLL
  2209. static int poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2210. {
  2211. struct timeval tv;
  2212. fd_set set;
  2213. unsigned int i;
  2214. int result;
  2215. SOCKET maxfd = 0;
  2216. tv.tv_sec = milliseconds / 1000;
  2217. tv.tv_usec = (milliseconds % 1000) * 1000;
  2218. FD_ZERO(&set);
  2219. for (i = 0; i < n; i++) {
  2220. FD_SET((SOCKET)pfd[i].fd, &set);
  2221. pfd[i].revents = 0;
  2222. if (pfd[i].fd > maxfd) {
  2223. maxfd = pfd[i].fd;
  2224. }
  2225. }
  2226. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2227. for (i = 0; i < n; i++) {
  2228. if (FD_ISSET(pfd[i].fd, &set)) {
  2229. pfd[i].revents = POLLIN;
  2230. }
  2231. }
  2232. }
  2233. return result;
  2234. }
  2235. #endif /* HAVE_POLL */
  2236. static void set_close_on_exec(SOCKET sock,
  2237. struct mg_connection *conn /* may be null */)
  2238. {
  2239. (void)conn; /* Unused. */
  2240. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2241. }
  2242. int mg_start_thread(mg_thread_func_t f, void *p)
  2243. {
  2244. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2245. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2246. */
  2247. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2248. ((uintptr_t)(-1L)))
  2249. ? -1
  2250. : 0);
  2251. #else
  2252. return (
  2253. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2254. ? -1
  2255. : 0);
  2256. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2257. }
  2258. /* Start a thread storing the thread context. */
  2259. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2260. void *p,
  2261. pthread_t *threadidptr)
  2262. {
  2263. uintptr_t uip;
  2264. HANDLE threadhandle;
  2265. int result = -1;
  2266. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2267. threadhandle = (HANDLE)uip;
  2268. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2269. *threadidptr = threadhandle;
  2270. result = 0;
  2271. }
  2272. return result;
  2273. }
  2274. /* Wait for a thread to finish. */
  2275. static int mg_join_thread(pthread_t threadid)
  2276. {
  2277. int result;
  2278. DWORD dwevent;
  2279. result = -1;
  2280. dwevent = WaitForSingleObject(threadid, INFINITE);
  2281. if (dwevent == WAIT_FAILED) {
  2282. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2283. } else {
  2284. if (dwevent == WAIT_OBJECT_0) {
  2285. CloseHandle(threadid);
  2286. result = 0;
  2287. }
  2288. }
  2289. return result;
  2290. }
  2291. static HANDLE dlopen(const char *dll_name, int flags)
  2292. {
  2293. wchar_t wbuf[PATH_MAX];
  2294. (void)flags;
  2295. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2296. return LoadLibraryW(wbuf);
  2297. }
  2298. static int dlclose(void *handle)
  2299. {
  2300. int result;
  2301. if (FreeLibrary((HMODULE)handle) != 0) {
  2302. result = 0;
  2303. } else {
  2304. result = -1;
  2305. }
  2306. return result;
  2307. }
  2308. #if !defined(NO_CGI)
  2309. #define SIGKILL (0)
  2310. static int kill(pid_t pid, int sig_num)
  2311. {
  2312. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2313. (void)CloseHandle((HANDLE)pid);
  2314. return 0;
  2315. }
  2316. static void trim_trailing_whitespaces(char *s)
  2317. {
  2318. char *e = s + strlen(s) - 1;
  2319. while (e > s && isspace(*(unsigned char *)e)) {
  2320. *e-- = '\0';
  2321. }
  2322. }
  2323. static pid_t spawn_process(struct mg_connection *conn,
  2324. const char *prog,
  2325. char *envblk,
  2326. char *envp[],
  2327. int fdin,
  2328. int fdout,
  2329. const char *dir)
  2330. {
  2331. HANDLE me;
  2332. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2333. cmdline[PATH_MAX], buf[PATH_MAX];
  2334. struct file file = STRUCT_FILE_INITIALIZER;
  2335. STARTUPINFOA si;
  2336. PROCESS_INFORMATION pi = {0};
  2337. (void)envp;
  2338. memset(&si, 0, sizeof(si));
  2339. si.cb = sizeof(si);
  2340. /* TODO(lsm, mid): redirect CGI errors to the error log file */
  2341. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2342. si.wShowWindow = SW_HIDE;
  2343. me = GetCurrentProcess();
  2344. DuplicateHandle(me,
  2345. (HANDLE)_get_osfhandle(fdin),
  2346. me,
  2347. &si.hStdInput,
  2348. 0,
  2349. TRUE,
  2350. DUPLICATE_SAME_ACCESS);
  2351. DuplicateHandle(me,
  2352. (HANDLE)_get_osfhandle(fdout),
  2353. me,
  2354. &si.hStdOutput,
  2355. 0,
  2356. TRUE,
  2357. DUPLICATE_SAME_ACCESS);
  2358. /* If CGI file is a script, try to read the interpreter line */
  2359. interp = conn->ctx->config[CGI_INTERPRETER];
  2360. if (interp == NULL) {
  2361. buf[0] = buf[1] = '\0';
  2362. /* Read the first line of the script into the buffer */
  2363. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  2364. if (mg_fopen(conn, cmdline, "r", &file)) {
  2365. p = (char *)file.membuf;
  2366. mg_fgets(buf, sizeof(buf), &file, &p);
  2367. mg_fclose(&file);
  2368. buf[sizeof(buf) - 1] = '\0';
  2369. }
  2370. if (buf[0] == '#' && buf[1] == '!') {
  2371. trim_trailing_whitespaces(buf + 2);
  2372. } else {
  2373. buf[2] = '\0';
  2374. }
  2375. interp = buf + 2;
  2376. }
  2377. if (interp[0] != '\0') {
  2378. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2379. interp = full_interp;
  2380. }
  2381. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2382. if (interp[0] != '\0') {
  2383. mg_snprintf(conn,
  2384. cmdline,
  2385. sizeof(cmdline),
  2386. "\"%s\" \"%s\\%s\"",
  2387. interp,
  2388. full_dir,
  2389. prog);
  2390. } else {
  2391. mg_snprintf(
  2392. conn, cmdline, sizeof(cmdline), "\"%s\\%s\"", full_dir, prog);
  2393. }
  2394. DEBUG_TRACE("Running [%s]", cmdline);
  2395. if (CreateProcessA(NULL,
  2396. cmdline,
  2397. NULL,
  2398. NULL,
  2399. TRUE,
  2400. CREATE_NEW_PROCESS_GROUP,
  2401. envblk,
  2402. NULL,
  2403. &si,
  2404. &pi) == 0) {
  2405. mg_cry(
  2406. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2407. pi.hProcess = (pid_t)-1;
  2408. }
  2409. (void)CloseHandle(si.hStdOutput);
  2410. (void)CloseHandle(si.hStdInput);
  2411. if (pi.hThread != NULL) {
  2412. (void)CloseHandle(pi.hThread);
  2413. }
  2414. return (pid_t)pi.hProcess;
  2415. }
  2416. #endif /* !NO_CGI */
  2417. static int set_non_blocking_mode(SOCKET sock)
  2418. {
  2419. unsigned long on = 1;
  2420. return ioctlsocket(sock, (long)FIONBIO, &on);
  2421. }
  2422. #else
  2423. static int
  2424. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2425. {
  2426. struct stat st;
  2427. if (!filep) {
  2428. return 0;
  2429. }
  2430. memset(filep, 0, sizeof(*filep));
  2431. if (conn && is_file_in_memory(conn, path, filep)) {
  2432. return 1;
  2433. }
  2434. if (0 == stat(path, &st)) {
  2435. filep->size = (uint64_t)(st.st_size);
  2436. filep->last_modified = st.st_mtime;
  2437. filep->is_directory = S_ISDIR(st.st_mode);
  2438. return 1;
  2439. }
  2440. return 0;
  2441. }
  2442. static void set_close_on_exec(SOCKET fd,
  2443. struct mg_connection *conn /* may be null */)
  2444. {
  2445. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2446. if (conn) {
  2447. mg_cry(conn,
  2448. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2449. __func__,
  2450. strerror(ERRNO));
  2451. }
  2452. }
  2453. }
  2454. int mg_start_thread(mg_thread_func_t func, void *param)
  2455. {
  2456. pthread_t thread_id;
  2457. pthread_attr_t attr;
  2458. int result;
  2459. (void)pthread_attr_init(&attr);
  2460. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2461. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2462. /* Compile-time option to control stack size,
  2463. * e.g. -DUSE_STACK_SIZE=16384 */
  2464. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2465. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2466. result = pthread_create(&thread_id, &attr, func, param);
  2467. pthread_attr_destroy(&attr);
  2468. return result;
  2469. }
  2470. /* Start a thread storing the thread context. */
  2471. static int mg_start_thread_with_id(mg_thread_func_t func,
  2472. void *param,
  2473. pthread_t *threadidptr)
  2474. {
  2475. pthread_t thread_id;
  2476. pthread_attr_t attr;
  2477. int result;
  2478. (void)pthread_attr_init(&attr);
  2479. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2480. /* Compile-time option to control stack size,
  2481. * e.g. -DUSE_STACK_SIZE=16384 */
  2482. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2483. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2484. result = pthread_create(&thread_id, &attr, func, param);
  2485. pthread_attr_destroy(&attr);
  2486. if ((result == 0) && (threadidptr != NULL)) {
  2487. *threadidptr = thread_id;
  2488. }
  2489. return result;
  2490. }
  2491. /* Wait for a thread to finish. */
  2492. static int mg_join_thread(pthread_t threadid)
  2493. {
  2494. int result;
  2495. result = pthread_join(threadid, NULL);
  2496. return result;
  2497. }
  2498. #ifndef NO_CGI
  2499. static pid_t spawn_process(struct mg_connection *conn,
  2500. const char *prog,
  2501. char *envblk,
  2502. char *envp[],
  2503. int fdin,
  2504. int fdout,
  2505. const char *dir)
  2506. {
  2507. pid_t pid;
  2508. const char *interp;
  2509. (void)envblk;
  2510. if (conn == NULL) {
  2511. return 0;
  2512. }
  2513. if ((pid = fork()) == -1) {
  2514. /* Parent */
  2515. send_http_error(conn,
  2516. 500,
  2517. "Error: Creating CGI process\nfork(): %s",
  2518. strerror(ERRNO));
  2519. } else if (pid == 0) {
  2520. /* Child */
  2521. if (chdir(dir) != 0) {
  2522. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2523. } else if (dup2(fdin, 0) == -1) {
  2524. mg_cry(
  2525. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2526. } else if (dup2(fdout, 1) == -1) {
  2527. mg_cry(
  2528. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2529. } else {
  2530. /* Not redirecting stderr to stdout, to avoid output being littered
  2531. * with the error messages. */
  2532. (void)close(fdin);
  2533. (void)close(fdout);
  2534. /* After exec, all signal handlers are restored to their default
  2535. * values, with one exception of SIGCHLD. According to
  2536. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2537. * leave unchanged after exec if it was set to be ignored. Restore
  2538. * it to default action. */
  2539. signal(SIGCHLD, SIG_DFL);
  2540. interp = conn->ctx->config[CGI_INTERPRETER];
  2541. if (interp == NULL) {
  2542. (void)execle(prog, prog, NULL, envp);
  2543. mg_cry(conn,
  2544. "%s: execle(%s): %s",
  2545. __func__,
  2546. prog,
  2547. strerror(ERRNO));
  2548. } else {
  2549. (void)execle(interp, interp, prog, NULL, envp);
  2550. mg_cry(conn,
  2551. "%s: execle(%s %s): %s",
  2552. __func__,
  2553. interp,
  2554. prog,
  2555. strerror(ERRNO));
  2556. }
  2557. }
  2558. exit(EXIT_FAILURE);
  2559. }
  2560. return pid;
  2561. }
  2562. #endif /* !NO_CGI */
  2563. static int set_non_blocking_mode(SOCKET sock)
  2564. {
  2565. int flags;
  2566. flags = fcntl(sock, F_GETFL, 0);
  2567. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2568. return 0;
  2569. }
  2570. #endif /* _WIN32 */
  2571. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2572. * descriptor. Return number of bytes written. */
  2573. static int push(struct mg_context *ctx,
  2574. FILE *fp,
  2575. SOCKET sock,
  2576. SSL *ssl,
  2577. const char *buf,
  2578. int len,
  2579. double timeout)
  2580. {
  2581. struct timespec start, now;
  2582. int n;
  2583. #ifdef _WIN32
  2584. typedef int len_t;
  2585. #else
  2586. typedef size_t len_t;
  2587. #endif
  2588. if (timeout > 0) {
  2589. memset(&start, 0, sizeof(start));
  2590. memset(&now, 0, sizeof(now));
  2591. clock_gettime(CLOCK_MONOTONIC, &start);
  2592. }
  2593. if (ctx == NULL) {
  2594. return -1;
  2595. }
  2596. do {
  2597. #ifndef NO_SSL
  2598. if (ssl != NULL) {
  2599. n = SSL_write(ssl, buf, len);
  2600. } else
  2601. #endif
  2602. if (fp != NULL) {
  2603. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2604. if (ferror(fp)) {
  2605. n = -1;
  2606. }
  2607. } else {
  2608. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2609. }
  2610. if (ctx->stop_flag) {
  2611. return -1;
  2612. }
  2613. if ((n > 0) || (n == 0 && len == 0)) {
  2614. /* some data has been read, or no data was requested */
  2615. return n;
  2616. }
  2617. if (n == 0) {
  2618. /* shutdown of the socket at client side */
  2619. return -1;
  2620. }
  2621. if (n < 0) {
  2622. /* socket error - check errno */
  2623. int err = ERRNO;
  2624. DEBUG_TRACE("send() failed, error %d", err);
  2625. (void)err; /* TODO: error handling depending on the error code.
  2626. * These codes are different between Windows and Linux.
  2627. */
  2628. return -1;
  2629. }
  2630. if (timeout > 0) {
  2631. clock_gettime(CLOCK_MONOTONIC, &now);
  2632. }
  2633. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2634. return -1;
  2635. }
  2636. static int64_t push_all(struct mg_context *ctx,
  2637. FILE *fp,
  2638. SOCKET sock,
  2639. SSL *ssl,
  2640. const char *buf,
  2641. int64_t len)
  2642. {
  2643. double timeout = -1.0;
  2644. int64_t n, nwritten = 0;
  2645. if (ctx == NULL) {
  2646. return -1;
  2647. }
  2648. if (ctx->config[REQUEST_TIMEOUT]) {
  2649. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2650. }
  2651. while (len > 0 && ctx->stop_flag == 0) {
  2652. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2653. if (n < 0) {
  2654. nwritten = n; /* Propagate the error */
  2655. break;
  2656. } else if (n == 0) {
  2657. break; /* No more data to write */
  2658. } else {
  2659. nwritten += n;
  2660. len -= n;
  2661. }
  2662. }
  2663. return nwritten;
  2664. }
  2665. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2666. * Return negative value on error, or number of bytes read on success. */
  2667. static int
  2668. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  2669. {
  2670. int nread;
  2671. struct timespec start, now;
  2672. #ifdef _WIN32
  2673. typedef int len_t;
  2674. #else
  2675. typedef size_t len_t;
  2676. #endif
  2677. if (timeout > 0) {
  2678. memset(&start, 0, sizeof(start));
  2679. memset(&now, 0, sizeof(now));
  2680. clock_gettime(CLOCK_MONOTONIC, &start);
  2681. }
  2682. do {
  2683. if (fp != NULL) {
  2684. /* Use read() instead of fread(), because if we're reading from the
  2685. * CGI pipe, fread() may block until IO buffer is filled up. We
  2686. * cannot afford to block and must pass all read bytes immediately
  2687. * to the client. */
  2688. nread = (int)read(fileno(fp), buf, (size_t)len);
  2689. #ifndef NO_SSL
  2690. } else if (conn->ssl != NULL) {
  2691. nread = SSL_read(conn->ssl, buf, len);
  2692. #endif
  2693. } else {
  2694. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  2695. }
  2696. if (conn->ctx->stop_flag) {
  2697. return -1;
  2698. }
  2699. if ((nread > 0) || (nread == 0 && len == 0)) {
  2700. /* some data has been read, or no data was requested */
  2701. return nread;
  2702. }
  2703. if (nread == 0) {
  2704. /* shutdown of the socket at client side */
  2705. return -1;
  2706. }
  2707. if (nread < 0) {
  2708. /* socket error - check errno */
  2709. int err = ERRNO;
  2710. #ifdef _WIN32
  2711. if (err == WSAEWOULDBLOCK) {
  2712. /* standard case if called from close_socket_gracefully */
  2713. return -1;
  2714. } else if (err == WSAETIMEDOUT) {
  2715. /* timeout is handled by the while loop */
  2716. } else {
  2717. DEBUG_TRACE("recv() failed, error %d", err);
  2718. return -1;
  2719. }
  2720. #else
  2721. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  2722. * if the timeout is reached and if the socket was set to non-
  2723. * blocking in close_socket_gracefully, so we can not distinguish
  2724. * here. We have to wait for the timeout in both cases for now.
  2725. */
  2726. if (err == EAGAIN || err == EWOULDBLOCK) {
  2727. /* standard case if called from close_socket_gracefully
  2728. * => should return -1 */
  2729. /* or timeout occured
  2730. * => the code must stay in the while loop */
  2731. } else {
  2732. DEBUG_TRACE("recv() failed, error %d", err);
  2733. return -1;
  2734. }
  2735. #endif
  2736. }
  2737. if (timeout > 0) {
  2738. clock_gettime(CLOCK_MONOTONIC, &now);
  2739. }
  2740. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2741. /* Timeout occured, but no data available. */
  2742. return -1;
  2743. }
  2744. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  2745. {
  2746. int n, nread = 0;
  2747. double timeout = -1.0;
  2748. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2749. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2750. }
  2751. while (len > 0 && conn->ctx->stop_flag == 0) {
  2752. n = pull(fp, conn, buf + nread, len, timeout);
  2753. if (n < 0) {
  2754. nread = n; /* Propagate the error */
  2755. break;
  2756. } else if (n == 0) {
  2757. break; /* No more data to read */
  2758. } else {
  2759. conn->consumed_content += n;
  2760. nread += n;
  2761. len -= n;
  2762. }
  2763. }
  2764. return nread;
  2765. }
  2766. static void discard_unread_request_data(struct mg_connection *conn)
  2767. {
  2768. char buf[MG_BUF_LEN];
  2769. size_t to_read;
  2770. int nread;
  2771. if (conn == NULL) {
  2772. return;
  2773. }
  2774. to_read = sizeof(buf);
  2775. if (conn->is_chunked) {
  2776. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2777. * completely */
  2778. while (conn->is_chunked == 1) {
  2779. nread = mg_read(conn, buf, to_read);
  2780. if (nread <= 0) {
  2781. break;
  2782. }
  2783. }
  2784. } else {
  2785. /* Not chunked: content length is known */
  2786. while (conn->consumed_content < conn->content_len) {
  2787. if (to_read >
  2788. (size_t)(conn->content_len - conn->consumed_content)) {
  2789. to_read = (size_t)(conn->content_len - conn->consumed_content);
  2790. }
  2791. nread = mg_read(conn, buf, to_read);
  2792. if (nread <= 0) {
  2793. break;
  2794. }
  2795. }
  2796. }
  2797. }
  2798. static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  2799. {
  2800. int64_t n, buffered_len, nread;
  2801. int64_t len64 =
  2802. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2803. * int, we may not read more
  2804. * bytes */
  2805. const char *body;
  2806. if (conn == NULL) {
  2807. return 0;
  2808. }
  2809. /* If Content-Length is not set for a PUT or POST request, read until
  2810. * socket is closed */
  2811. if (conn->consumed_content == 0 && conn->content_len == -1) {
  2812. conn->content_len = INT64_MAX;
  2813. conn->must_close = 1;
  2814. }
  2815. nread = 0;
  2816. if (conn->consumed_content < conn->content_len) {
  2817. /* Adjust number of bytes to read. */
  2818. int64_t left_to_read = conn->content_len - conn->consumed_content;
  2819. if (left_to_read < len64) {
  2820. /* Do not reade more than the total content length of the request.
  2821. */
  2822. len64 = left_to_read;
  2823. }
  2824. /* Return buffered data */
  2825. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  2826. conn->consumed_content;
  2827. if (buffered_len > 0) {
  2828. if (len64 < buffered_len) {
  2829. buffered_len = len64;
  2830. }
  2831. body = conn->buf + conn->request_len + conn->consumed_content;
  2832. memcpy(buf, body, (size_t)buffered_len);
  2833. len64 -= buffered_len;
  2834. conn->consumed_content += buffered_len;
  2835. nread += buffered_len;
  2836. buf = (char *)buf + buffered_len;
  2837. }
  2838. /* We have returned all buffered data. Read new data from the remote
  2839. * socket.
  2840. */
  2841. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  2842. nread += n;
  2843. } else {
  2844. nread = (nread > 0 ? nread : n);
  2845. }
  2846. }
  2847. return (int)nread;
  2848. }
  2849. static char mg_getc(struct mg_connection *conn)
  2850. {
  2851. char c;
  2852. if (conn == NULL) {
  2853. return 0;
  2854. }
  2855. conn->content_len++;
  2856. if (mg_read_inner(conn, &c, 1) <= 0) {
  2857. return (char)0;
  2858. }
  2859. return c;
  2860. }
  2861. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  2862. {
  2863. if (len > INT_MAX) {
  2864. len = INT_MAX;
  2865. }
  2866. if (conn == NULL) {
  2867. return 0;
  2868. }
  2869. if (conn->is_chunked) {
  2870. size_t all_read = 0;
  2871. while (len > 0) {
  2872. if (conn->chunk_remainder) {
  2873. /* copy from the remainder of the last received chunk */
  2874. long read_ret;
  2875. size_t read_now =
  2876. ((conn->chunk_remainder > len) ? (len)
  2877. : (conn->chunk_remainder));
  2878. conn->content_len += (int)read_now;
  2879. read_ret =
  2880. mg_read_inner(conn, (char *)buf + all_read, read_now);
  2881. all_read += (size_t)read_ret;
  2882. conn->chunk_remainder -= read_now;
  2883. len -= read_now;
  2884. if (conn->chunk_remainder == 0) {
  2885. /* the rest of the data in the current chunk has been read
  2886. */
  2887. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  2888. /* Protocol violation */
  2889. return -1;
  2890. }
  2891. }
  2892. } else {
  2893. /* fetch a new chunk */
  2894. int i = 0;
  2895. char lenbuf[64];
  2896. char *end = 0;
  2897. unsigned long chunkSize = 0;
  2898. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  2899. lenbuf[i] = mg_getc(conn);
  2900. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  2901. continue;
  2902. }
  2903. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  2904. lenbuf[i + 1] = 0;
  2905. chunkSize = strtoul(lenbuf, &end, 16);
  2906. break;
  2907. }
  2908. if (!isalnum(lenbuf[i])) {
  2909. /* illegal character for chunk length */
  2910. return -1;
  2911. }
  2912. }
  2913. if ((end == NULL) || (*end != '\r')) {
  2914. /* chunksize not set correctly */
  2915. return -1;
  2916. }
  2917. conn->chunk_remainder = chunkSize;
  2918. if (chunkSize == 0) {
  2919. /* regular end of content */
  2920. conn->is_chunked = 2;
  2921. break;
  2922. }
  2923. }
  2924. }
  2925. return (int)all_read;
  2926. }
  2927. return mg_read_inner(conn, buf, len);
  2928. }
  2929. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  2930. {
  2931. time_t now;
  2932. int64_t n, total, allowed;
  2933. if (conn == NULL) {
  2934. return 0;
  2935. }
  2936. if (conn->throttle > 0) {
  2937. if ((now = time(NULL)) != conn->last_throttle_time) {
  2938. conn->last_throttle_time = now;
  2939. conn->last_throttle_bytes = 0;
  2940. }
  2941. allowed = conn->throttle - conn->last_throttle_bytes;
  2942. if (allowed > (int64_t)len) {
  2943. allowed = (int64_t)len;
  2944. }
  2945. if ((total = push_all(conn->ctx,
  2946. NULL,
  2947. conn->client.sock,
  2948. conn->ssl,
  2949. (const char *)buf,
  2950. (int64_t)allowed)) == allowed) {
  2951. buf = (char *)buf + total;
  2952. conn->last_throttle_bytes += total;
  2953. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  2954. allowed = conn->throttle > (int64_t)len - total
  2955. ? (int64_t)len - total
  2956. : conn->throttle;
  2957. if ((n = push_all(conn->ctx,
  2958. NULL,
  2959. conn->client.sock,
  2960. conn->ssl,
  2961. (const char *)buf,
  2962. (int64_t)allowed)) != allowed) {
  2963. break;
  2964. }
  2965. sleep(1);
  2966. conn->last_throttle_bytes = allowed;
  2967. conn->last_throttle_time = time(NULL);
  2968. buf = (char *)buf + n;
  2969. total += n;
  2970. }
  2971. }
  2972. } else {
  2973. total = push_all(conn->ctx,
  2974. NULL,
  2975. conn->client.sock,
  2976. conn->ssl,
  2977. (const char *)buf,
  2978. (int64_t)len);
  2979. }
  2980. return (int)total;
  2981. }
  2982. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  2983. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  2984. {
  2985. va_list ap_copy;
  2986. size_t size = MG_BUF_LEN;
  2987. int len = -1;
  2988. *buf = NULL;
  2989. while (len == -1) {
  2990. if (*buf) {
  2991. mg_free(*buf);
  2992. }
  2993. *buf = (char *)mg_malloc(size *= 4);
  2994. if (!*buf) {
  2995. break;
  2996. }
  2997. va_copy(ap_copy, ap);
  2998. len = vsnprintf(*buf, size, fmt, ap_copy);
  2999. va_end(ap_copy);
  3000. }
  3001. return len;
  3002. }
  3003. /* Print message to buffer. If buffer is large enough to hold the message,
  3004. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3005. * and return allocated buffer. */
  3006. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3007. {
  3008. va_list ap_copy;
  3009. int len;
  3010. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3011. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3012. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3013. * Therefore, we make two passes: on first pass, get required message
  3014. * length.
  3015. * On second pass, actually print the message. */
  3016. va_copy(ap_copy, ap);
  3017. len = vsnprintf(NULL, 0, fmt, ap_copy);
  3018. va_end(ap_copy);
  3019. if (len < 0) {
  3020. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3021. * Switch to alternative code path that uses incremental allocations.
  3022. */
  3023. va_copy(ap_copy, ap);
  3024. len = alloc_vprintf2(buf, fmt, ap);
  3025. va_end(ap_copy);
  3026. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0 &&
  3027. (*buf = (char *)mg_malloc(size)) == NULL) {
  3028. len = -1; /* Allocation failed, mark failure */
  3029. } else {
  3030. va_copy(ap_copy, ap);
  3031. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  3032. va_end(ap_copy);
  3033. }
  3034. return len;
  3035. }
  3036. static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3037. {
  3038. char mem[MG_BUF_LEN], *buf = mem;
  3039. int len;
  3040. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3041. len = mg_write(conn, buf, (size_t)len);
  3042. }
  3043. if (buf != mem && buf != NULL) {
  3044. mg_free(buf);
  3045. }
  3046. return len;
  3047. }
  3048. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3049. {
  3050. va_list ap;
  3051. int result;
  3052. va_start(ap, fmt);
  3053. result = mg_vprintf(conn, fmt, ap);
  3054. va_end(ap);
  3055. return result;
  3056. }
  3057. int mg_url_decode(const char *src,
  3058. int src_len,
  3059. char *dst,
  3060. int dst_len,
  3061. int is_form_url_encoded)
  3062. {
  3063. int i, j, a, b;
  3064. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3065. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3066. if (i < src_len - 2 && src[i] == '%' &&
  3067. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  3068. isxdigit(*(const unsigned char *)(src + i + 2))) {
  3069. a = tolower(*(const unsigned char *)(src + i + 1));
  3070. b = tolower(*(const unsigned char *)(src + i + 2));
  3071. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3072. i += 2;
  3073. } else if (is_form_url_encoded && src[i] == '+') {
  3074. dst[j] = ' ';
  3075. } else {
  3076. dst[j] = src[i];
  3077. }
  3078. }
  3079. dst[j] = '\0'; /* Null-terminate the destination */
  3080. return i >= src_len ? j : -1;
  3081. }
  3082. int mg_get_var(const char *data,
  3083. size_t data_len,
  3084. const char *name,
  3085. char *dst,
  3086. size_t dst_len)
  3087. {
  3088. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3089. }
  3090. int mg_get_var2(const char *data,
  3091. size_t data_len,
  3092. const char *name,
  3093. char *dst,
  3094. size_t dst_len,
  3095. size_t occurrence)
  3096. {
  3097. const char *p, *e, *s;
  3098. size_t name_len;
  3099. int len;
  3100. if (dst == NULL || dst_len == 0) {
  3101. len = -2;
  3102. } else if (data == NULL || name == NULL || data_len == 0) {
  3103. len = -1;
  3104. dst[0] = '\0';
  3105. } else {
  3106. name_len = strlen(name);
  3107. e = data + data_len;
  3108. len = -1;
  3109. dst[0] = '\0';
  3110. /* data is "var1=val1&var2=val2...". Find variable first */
  3111. for (p = data; p + name_len < e; p++) {
  3112. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3113. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3114. /* Point p to variable value */
  3115. p += name_len + 1;
  3116. /* Point s to the end of the value */
  3117. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3118. if (s == NULL) {
  3119. s = e;
  3120. }
  3121. /* assert(s >= p); */
  3122. if (s < p) {
  3123. return -3;
  3124. }
  3125. /* Decode variable into destination buffer */
  3126. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3127. /* Redirect error code from -1 to -2 (destination buffer too
  3128. * small). */
  3129. if (len == -1) {
  3130. len = -2;
  3131. }
  3132. break;
  3133. }
  3134. }
  3135. }
  3136. return len;
  3137. }
  3138. int mg_get_cookie(const char *cookie_header,
  3139. const char *var_name,
  3140. char *dst,
  3141. size_t dst_size)
  3142. {
  3143. const char *s, *p, *end;
  3144. int name_len, len = -1;
  3145. if (dst == NULL || dst_size == 0) {
  3146. len = -2;
  3147. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3148. len = -1;
  3149. dst[0] = '\0';
  3150. } else {
  3151. name_len = (int)strlen(var_name);
  3152. end = s + strlen(s);
  3153. dst[0] = '\0';
  3154. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3155. if (s[name_len] == '=') {
  3156. s += name_len + 1;
  3157. if ((p = strchr(s, ' ')) == NULL) {
  3158. p = end;
  3159. }
  3160. if (p[-1] == ';') {
  3161. p--;
  3162. }
  3163. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3164. s++;
  3165. p--;
  3166. }
  3167. if ((size_t)(p - s) < dst_size) {
  3168. len = (int)(p - s);
  3169. mg_strlcpy(dst, s, (size_t)len + 1);
  3170. } else {
  3171. len = -3;
  3172. }
  3173. break;
  3174. }
  3175. }
  3176. }
  3177. return len;
  3178. }
  3179. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3180. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3181. {
  3182. static const char *b64 =
  3183. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3184. int i, j, a, b, c;
  3185. for (i = j = 0; i < src_len; i += 3) {
  3186. a = src[i];
  3187. b = i + 1 >= src_len ? 0 : src[i + 1];
  3188. c = i + 2 >= src_len ? 0 : src[i + 2];
  3189. dst[j++] = b64[a >> 2];
  3190. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3191. if (i + 1 < src_len) {
  3192. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3193. }
  3194. if (i + 2 < src_len) {
  3195. dst[j++] = b64[c & 63];
  3196. }
  3197. }
  3198. while (j % 4 != 0) {
  3199. dst[j++] = '=';
  3200. }
  3201. dst[j++] = '\0';
  3202. }
  3203. #endif
  3204. #if defined(USE_LUA)
  3205. static unsigned char b64reverse(char letter)
  3206. {
  3207. if (letter >= 'A' && letter <= 'Z') {
  3208. return letter - 'A';
  3209. }
  3210. if (letter >= 'a' && letter <= 'z') {
  3211. return letter - 'a' + 26;
  3212. }
  3213. if (letter >= '0' && letter <= '9') {
  3214. return letter - '0' + 52;
  3215. }
  3216. if (letter == '+') {
  3217. return 62;
  3218. }
  3219. if (letter == '/') {
  3220. return 63;
  3221. }
  3222. if (letter == '=') {
  3223. return 255; /* normal end */
  3224. }
  3225. return 254; /* error */
  3226. }
  3227. static int
  3228. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3229. {
  3230. int i;
  3231. unsigned char a, b, c, d;
  3232. *dst_len = 0;
  3233. for (i = 0; i < src_len; i += 4) {
  3234. a = b64reverse(src[i]);
  3235. if (a >= 254) {
  3236. return i;
  3237. }
  3238. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3239. if (b >= 254) {
  3240. return i + 1;
  3241. }
  3242. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3243. if (c == 254) {
  3244. return i + 2;
  3245. }
  3246. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3247. if (c == 254) {
  3248. return i + 3;
  3249. }
  3250. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3251. if (c != 255) {
  3252. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3253. if (d != 255) {
  3254. dst[(*dst_len)++] = (c << 6) + d;
  3255. }
  3256. }
  3257. }
  3258. return -1;
  3259. }
  3260. #endif
  3261. static int is_put_or_delete_method(const struct mg_connection *conn)
  3262. {
  3263. if (conn) {
  3264. const char *s = conn->request_info.request_method;
  3265. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  3266. !strcmp(s, "MKCOL"));
  3267. }
  3268. return 0;
  3269. }
  3270. static void
  3271. interpret_uri(struct mg_connection *conn, /* in: request */
  3272. char *filename, /* out: filename */
  3273. size_t filename_buf_len, /* in: size of filename buffer */
  3274. struct file *filep, /* out: file structure */
  3275. int *is_found, /* out: file is found (directly) */
  3276. int *is_script_ressource, /* out: handled by a script? */
  3277. int *is_websocket_request, /* out: websocket connetion? */
  3278. int *is_put_or_delete_request /* out: put/delete a file? */
  3279. )
  3280. {
  3281. if (conn && conn->ctx) {
  3282. const char *uri = conn->request_info.uri;
  3283. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3284. #if !defined(NO_FILES)
  3285. const char *rewrite;
  3286. struct vec a, b;
  3287. char *p;
  3288. int match_len;
  3289. char gz_path[PATH_MAX];
  3290. char const *accept_encoding;
  3291. #endif
  3292. memset(filep, 0, sizeof(*filep));
  3293. *filename = 0;
  3294. *is_found = 0;
  3295. *is_script_ressource = 0;
  3296. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3297. #if defined(USE_WEBSOCKET)
  3298. *is_websocket_request = is_websocket_protocol(conn);
  3299. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3300. root = conn->ctx->config[WEBSOCKET_ROOT];
  3301. }
  3302. #else
  3303. *is_websocket_request = 0;
  3304. #endif
  3305. #if !defined(NO_FILES)
  3306. /* Note that root == NULL is a regular use case here. This occurs,
  3307. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3308. * config is not required. */
  3309. if (root == NULL) {
  3310. /* all file related outputs have already been set to 0, just return
  3311. */
  3312. return;
  3313. }
  3314. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3315. * of the path one byte on the right.
  3316. * If document_root is NULL, leave the file empty. */
  3317. mg_snprintf(conn, filename, filename_buf_len - 1, "%s%s", root, uri);
  3318. rewrite = conn->ctx->config[REWRITE];
  3319. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3320. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3321. mg_snprintf(conn,
  3322. filename,
  3323. filename_buf_len - 1,
  3324. "%.*s%s",
  3325. (int)b.len,
  3326. b.ptr,
  3327. uri + match_len);
  3328. break;
  3329. }
  3330. }
  3331. /* Local file path and name, corresponding to requested URI
  3332. * is now stored in "filename" variable. */
  3333. if (mg_stat(conn, filename, filep)) {
  3334. /* File exists. Check if it is a script type. */
  3335. if (0
  3336. #if !defined(NO_CGI)
  3337. ||
  3338. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3339. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3340. filename) > 0
  3341. #endif
  3342. #if defined(USE_LUA)
  3343. ||
  3344. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3345. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3346. filename) > 0
  3347. #endif
  3348. ) {
  3349. /* The request addresses a CGI script or a Lua script. The URI
  3350. * corresponds to the script itself (like /path/script.cgi),
  3351. * and there is no additional resource path
  3352. * (like /path/script.cgi/something).
  3353. * Requests that modify (replace or delete) a resource, like
  3354. * PUT and DELETE requests, should replace/delete the script
  3355. * file.
  3356. * Requests that read or write from/to a resource, like GET and
  3357. * POST requests, should call the script and return the
  3358. * generated response. */
  3359. *is_script_ressource = !*is_put_or_delete_request;
  3360. }
  3361. *is_found = 1;
  3362. return;
  3363. }
  3364. /* If we can't find the actual file, look for the file
  3365. * with the same name but a .gz extension. If we find it,
  3366. * use that and set the gzipped flag in the file struct
  3367. * to indicate that the response need to have the content-
  3368. * encoding: gzip header.
  3369. * We can only do this if the browser declares support. */
  3370. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  3371. NULL) {
  3372. if (strstr(accept_encoding, "gzip") != NULL) {
  3373. snprintf(gz_path, sizeof(gz_path), "%s.gz", filename);
  3374. if (mg_stat(conn, gz_path, filep)) {
  3375. if (filep) {
  3376. filep->gzipped = 1;
  3377. }
  3378. /* Currently gz files can not be scripts. */
  3379. return;
  3380. }
  3381. }
  3382. }
  3383. /* Support PATH_INFO for CGI scripts. */
  3384. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3385. if (*p == '/') {
  3386. *p = '\0';
  3387. if ((0
  3388. #if !defined(NO_CGI)
  3389. ||
  3390. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3391. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3392. filename) > 0
  3393. #endif
  3394. #if defined(USE_LUA)
  3395. ||
  3396. match_prefix(
  3397. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3398. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3399. filename) > 0
  3400. #endif
  3401. ) &&
  3402. mg_stat(conn, filename, filep)) {
  3403. /* Shift PATH_INFO block one character right, e.g.
  3404. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3405. * conn->path_info is pointing to the local variable "path"
  3406. * declared in handle_request(), so PATH_INFO is not valid
  3407. * after handle_request returns. */
  3408. conn->path_info = p + 1;
  3409. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3410. * trailing \0 */
  3411. p[1] = '/';
  3412. *is_script_ressource = 1;
  3413. break;
  3414. } else {
  3415. *p = '/';
  3416. }
  3417. }
  3418. }
  3419. #endif
  3420. }
  3421. }
  3422. /* Check whether full request is buffered. Return:
  3423. * -1 if request is malformed
  3424. * 0 if request is not yet fully buffered
  3425. * >0 actual request length, including last \r\n\r\n */
  3426. static int get_request_len(const char *buf, int buflen)
  3427. {
  3428. const char *s, *e;
  3429. int len = 0;
  3430. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3431. /* Control characters are not allowed but >=128 is. */
  3432. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  3433. *(const unsigned char *)s < 128) {
  3434. len = -1;
  3435. break; /* [i_a] abort scan as soon as one malformed character is
  3436. * found; */
  3437. /* don't let subsequent \r\n\r\n win us over anyhow */
  3438. } else if (s[0] == '\n' && s[1] == '\n') {
  3439. len = (int)(s - buf) + 2;
  3440. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3441. len = (int)(s - buf) + 3;
  3442. }
  3443. return len;
  3444. }
  3445. /* Convert month to the month number. Return -1 on error, or month number */
  3446. static int get_month_index(const char *s)
  3447. {
  3448. size_t i;
  3449. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3450. if (!strcmp(s, month_names[i])) {
  3451. return (int)i;
  3452. }
  3453. }
  3454. return -1;
  3455. }
  3456. static int num_leap_years(int year)
  3457. {
  3458. return year / 4 - year / 100 + year / 400;
  3459. }
  3460. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3461. static time_t parse_date_string(const char *datetime)
  3462. {
  3463. static const unsigned short days_before_month[] = {
  3464. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3465. char month_str[32] = {0};
  3466. int second, minute, hour, day, month, year, leap_days, days;
  3467. time_t result = (time_t)0;
  3468. if ((sscanf(datetime,
  3469. "%d/%3s/%d %d:%d:%d",
  3470. &day,
  3471. month_str,
  3472. &year,
  3473. &hour,
  3474. &minute,
  3475. &second) == 6) ||
  3476. (sscanf(datetime,
  3477. "%d %3s %d %d:%d:%d",
  3478. &day,
  3479. month_str,
  3480. &year,
  3481. &hour,
  3482. &minute,
  3483. &second) == 6) ||
  3484. (sscanf(datetime,
  3485. "%*3s, %d %3s %d %d:%d:%d",
  3486. &day,
  3487. month_str,
  3488. &year,
  3489. &hour,
  3490. &minute,
  3491. &second) == 6) ||
  3492. (sscanf(datetime,
  3493. "%d-%3s-%d %d:%d:%d",
  3494. &day,
  3495. month_str,
  3496. &year,
  3497. &hour,
  3498. &minute,
  3499. &second) == 6)) {
  3500. month = get_month_index(month_str);
  3501. if ((month >= 0) && (year > 1970)) {
  3502. leap_days = num_leap_years(year) - num_leap_years(1970);
  3503. year -= 1970;
  3504. days =
  3505. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3506. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3507. minute * 60 + second;
  3508. }
  3509. }
  3510. return result;
  3511. }
  3512. /* Protect against directory disclosure attack by removing '..',
  3513. * excessive '/' and '\' characters */
  3514. static void remove_double_dots_and_double_slashes(char *s)
  3515. {
  3516. char *p = s;
  3517. while (*s != '\0') {
  3518. *p++ = *s++;
  3519. if (s[-1] == '/' || s[-1] == '\\') {
  3520. /* Skip all following slashes, backslashes and double-dots */
  3521. while (s[0] != '\0') {
  3522. if (s[0] == '/' || s[0] == '\\') {
  3523. s++;
  3524. } else if (s[0] == '.' && s[1] == '.') {
  3525. s += 2;
  3526. } else {
  3527. break;
  3528. }
  3529. }
  3530. }
  3531. }
  3532. *p = '\0';
  3533. }
  3534. static const struct {
  3535. const char *extension;
  3536. size_t ext_len;
  3537. const char *mime_type;
  3538. } builtin_mime_types[] = {
  3539. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3540. * application types */
  3541. {".doc", 4, "application/msword"},
  3542. {".eps", 4, "application/postscript"},
  3543. {".exe", 4, "application/octet-stream"},
  3544. {".js", 3, "application/javascript"},
  3545. {".json", 5, "application/json"},
  3546. {".pdf", 4, "application/pdf"},
  3547. {".ps", 3, "application/postscript"},
  3548. {".rtf", 4, "application/rtf"},
  3549. {".xhtml", 6, "application/xhtml+xml"},
  3550. {".xsl", 4, "application/xml"},
  3551. {".xslt", 5, "application/xml"},
  3552. /* audio */
  3553. {".mp3", 4, "audio/mpeg"},
  3554. {".oga", 4, "audio/ogg"},
  3555. {".ogg", 4, "audio/ogg"},
  3556. /* image */
  3557. {".gif", 4, "image/gif"},
  3558. {".ief", 4, "image/ief"},
  3559. {".jpeg", 5, "image/jpeg"},
  3560. {".jpg", 4, "image/jpeg"},
  3561. {".jpm", 4, "image/jpm"},
  3562. {".jpx", 4, "image/jpx"},
  3563. {".png", 4, "image/png"},
  3564. {".svg", 4, "image/svg+xml"},
  3565. {".tif", 4, "image/tiff"},
  3566. {".tiff", 5, "image/tiff"},
  3567. /* model */
  3568. {".wrl", 4, "model/vrml"},
  3569. /* text */
  3570. {".css", 4, "text/css"},
  3571. {".csv", 4, "text/csv"},
  3572. {".htm", 4, "text/html"},
  3573. {".html", 5, "text/html"},
  3574. {".sgm", 4, "text/sgml"},
  3575. {".shtm", 5, "text/html"},
  3576. {".shtml", 6, "text/html"},
  3577. {".txt", 4, "text/plain"},
  3578. {".xml", 4, "text/xml"},
  3579. /* video */
  3580. {".mov", 4, "video/quicktime"},
  3581. {".mp4", 4, "video/mp4"},
  3582. {".mpeg", 5, "video/mpeg"},
  3583. {".mpg", 4, "video/mpeg"},
  3584. {".ogv", 4, "video/ogg"},
  3585. {".qt", 3, "video/quicktime"},
  3586. /* not registered types
  3587. * (http://reference.sitepoint.com/html/mime-types-full,
  3588. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3589. {".arj", 4, "application/x-arj-compressed"},
  3590. {".gz", 3, "application/x-gunzip"},
  3591. {".rar", 4, "application/x-arj-compressed"},
  3592. {".swf", 4, "application/x-shockwave-flash"},
  3593. {".tar", 4, "application/x-tar"},
  3594. {".tgz", 4, "application/x-tar-gz"},
  3595. {".torrent", 8, "application/x-bittorrent"},
  3596. {".ppt", 4, "application/x-mspowerpoint"},
  3597. {".xls", 4, "application/x-msexcel"},
  3598. {".zip", 4, "application/x-zip-compressed"},
  3599. {".aac",
  3600. 4,
  3601. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3602. {".aif", 4, "audio/x-aif"},
  3603. {".m3u", 4, "audio/x-mpegurl"},
  3604. {".mid", 4, "audio/x-midi"},
  3605. {".ra", 3, "audio/x-pn-realaudio"},
  3606. {".ram", 4, "audio/x-pn-realaudio"},
  3607. {".wav", 4, "audio/x-wav"},
  3608. {".bmp", 4, "image/bmp"},
  3609. {".ico", 4, "image/x-icon"},
  3610. {".pct", 4, "image/x-pct"},
  3611. {".pict", 5, "image/pict"},
  3612. {".rgb", 4, "image/x-rgb"},
  3613. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3614. {".asf", 4, "video/x-ms-asf"},
  3615. {".avi", 4, "video/x-msvideo"},
  3616. {".m4v", 4, "video/x-m4v"},
  3617. {NULL, 0, NULL}};
  3618. const char *mg_get_builtin_mime_type(const char *path)
  3619. {
  3620. const char *ext;
  3621. size_t i, path_len;
  3622. path_len = strlen(path);
  3623. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3624. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3625. if (path_len > builtin_mime_types[i].ext_len &&
  3626. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3627. return builtin_mime_types[i].mime_type;
  3628. }
  3629. }
  3630. return "text/plain";
  3631. }
  3632. /* Look at the "path" extension and figure what mime type it has.
  3633. * Store mime type in the vector. */
  3634. static void
  3635. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  3636. {
  3637. struct vec ext_vec, mime_vec;
  3638. const char *list, *ext;
  3639. size_t path_len;
  3640. path_len = strlen(path);
  3641. if (ctx == NULL || vec == NULL) {
  3642. return;
  3643. }
  3644. /* Scan user-defined mime types first, in case user wants to
  3645. * override default mime types. */
  3646. list = ctx->config[EXTRA_MIME_TYPES];
  3647. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3648. /* ext now points to the path suffix */
  3649. ext = path + path_len - ext_vec.len;
  3650. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3651. *vec = mime_vec;
  3652. return;
  3653. }
  3654. }
  3655. vec->ptr = mg_get_builtin_mime_type(path);
  3656. vec->len = strlen(vec->ptr);
  3657. }
  3658. /* Stringify binary data. Output buffer must be twice as big as input,
  3659. * because each byte takes 2 bytes in string representation */
  3660. static void bin2str(char *to, const unsigned char *p, size_t len)
  3661. {
  3662. static const char *hex = "0123456789abcdef";
  3663. for (; len--; p++) {
  3664. *to++ = hex[p[0] >> 4];
  3665. *to++ = hex[p[0] & 0x0f];
  3666. }
  3667. *to = '\0';
  3668. }
  3669. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3670. char *mg_md5(char buf[33], ...)
  3671. {
  3672. md5_byte_t hash[16];
  3673. const char *p;
  3674. va_list ap;
  3675. md5_state_t ctx;
  3676. md5_init(&ctx);
  3677. va_start(ap, buf);
  3678. while ((p = va_arg(ap, const char *)) != NULL) {
  3679. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  3680. }
  3681. va_end(ap);
  3682. md5_finish(&ctx, hash);
  3683. bin2str(buf, hash, sizeof(hash));
  3684. return buf;
  3685. }
  3686. /* Check the user's password, return 1 if OK */
  3687. static int check_password(const char *method,
  3688. const char *ha1,
  3689. const char *uri,
  3690. const char *nonce,
  3691. const char *nc,
  3692. const char *cnonce,
  3693. const char *qop,
  3694. const char *response)
  3695. {
  3696. char ha2[32 + 1], expected_response[32 + 1];
  3697. /* Some of the parameters may be NULL */
  3698. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3699. qop == NULL || response == NULL) {
  3700. return 0;
  3701. }
  3702. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3703. /* TODO(lsm): check for authentication timeout */
  3704. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3705. strlen(response) != 32
  3706. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3707. ) {
  3708. return 0;
  3709. }
  3710. mg_md5(ha2, method, ":", uri, NULL);
  3711. mg_md5(expected_response,
  3712. ha1,
  3713. ":",
  3714. nonce,
  3715. ":",
  3716. nc,
  3717. ":",
  3718. cnonce,
  3719. ":",
  3720. qop,
  3721. ":",
  3722. ha2,
  3723. NULL);
  3724. return mg_strcasecmp(response, expected_response) == 0;
  3725. }
  3726. /* Use the global passwords file, if specified by auth_gpass option,
  3727. * or search for .htpasswd in the requested directory. */
  3728. static void
  3729. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  3730. {
  3731. if (conn != NULL && conn->ctx != NULL) {
  3732. char name[PATH_MAX];
  3733. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3734. struct file file = STRUCT_FILE_INITIALIZER;
  3735. if (gpass != NULL) {
  3736. /* Use global passwords file */
  3737. if (!mg_fopen(conn, gpass, "r", filep)) {
  3738. #ifdef DEBUG
  3739. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3740. #endif
  3741. }
  3742. /* Important: using local struct file to test path for is_directory
  3743. * flag.
  3744. * If filep is used, mg_stat() makes it appear as if auth file was
  3745. * opened. */
  3746. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3747. mg_snprintf(conn,
  3748. name,
  3749. sizeof(name),
  3750. "%s%c%s",
  3751. path,
  3752. '/',
  3753. PASSWORDS_FILE_NAME);
  3754. if (!mg_fopen(conn, name, "r", filep)) {
  3755. #ifdef DEBUG
  3756. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3757. #endif
  3758. }
  3759. } else {
  3760. /* Try to find .htpasswd in requested directory. */
  3761. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  3762. if (e[0] == '/') {
  3763. break;
  3764. }
  3765. }
  3766. mg_snprintf(conn,
  3767. name,
  3768. sizeof(name),
  3769. "%.*s%c%s",
  3770. (int)(e - p),
  3771. p,
  3772. '/',
  3773. PASSWORDS_FILE_NAME);
  3774. if (!mg_fopen(conn, name, "r", filep)) {
  3775. #ifdef DEBUG
  3776. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3777. #endif
  3778. }
  3779. }
  3780. }
  3781. }
  3782. /* Parsed Authorization header */
  3783. struct ah {
  3784. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  3785. };
  3786. /* Return 1 on success. Always initializes the ah structure. */
  3787. static int parse_auth_header(struct mg_connection *conn,
  3788. char *buf,
  3789. size_t buf_size,
  3790. struct ah *ah)
  3791. {
  3792. char *name, *value, *s;
  3793. const char *auth_header;
  3794. unsigned long nonce;
  3795. if (!ah || !conn) {
  3796. return 0;
  3797. }
  3798. (void)memset(ah, 0, sizeof(*ah));
  3799. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  3800. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  3801. return 0;
  3802. }
  3803. /* Make modifiable copy of the auth header */
  3804. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  3805. s = buf;
  3806. /* Parse authorization header */
  3807. for (;;) {
  3808. /* Gobble initial spaces */
  3809. while (isspace(*(unsigned char *)s)) {
  3810. s++;
  3811. }
  3812. name = skip_quoted(&s, "=", " ", 0);
  3813. /* Value is either quote-delimited, or ends at first comma or space. */
  3814. if (s[0] == '\"') {
  3815. s++;
  3816. value = skip_quoted(&s, "\"", " ", '\\');
  3817. if (s[0] == ',') {
  3818. s++;
  3819. }
  3820. } else {
  3821. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  3822. * spaces */
  3823. }
  3824. if (*name == '\0') {
  3825. break;
  3826. }
  3827. if (!strcmp(name, "username")) {
  3828. ah->user = value;
  3829. } else if (!strcmp(name, "cnonce")) {
  3830. ah->cnonce = value;
  3831. } else if (!strcmp(name, "response")) {
  3832. ah->response = value;
  3833. } else if (!strcmp(name, "uri")) {
  3834. ah->uri = value;
  3835. } else if (!strcmp(name, "qop")) {
  3836. ah->qop = value;
  3837. } else if (!strcmp(name, "nc")) {
  3838. ah->nc = value;
  3839. } else if (!strcmp(name, "nonce")) {
  3840. ah->nonce = value;
  3841. }
  3842. }
  3843. #ifndef NO_NONCE_CHECK
  3844. /* Convert the nonce from the client to a number and check it. */
  3845. /* Server side nonce check is valuable in all situations but one: if the
  3846. * server restarts frequently,
  3847. * but the client should not see that, so the server should accept nonces
  3848. * from
  3849. * previous starts. */
  3850. if (ah->nonce == NULL) {
  3851. return 0;
  3852. }
  3853. s = NULL;
  3854. nonce = strtoul(ah->nonce, &s, 10);
  3855. if ((s == NULL) || (*s != 0)) {
  3856. return 0;
  3857. }
  3858. nonce ^= (uintptr_t)(conn->ctx);
  3859. if (nonce < conn->ctx->start_time) {
  3860. /* nonce is from a previous start of the server and no longer valid
  3861. * (replay attack?) */
  3862. return 0;
  3863. }
  3864. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  3865. return 0;
  3866. }
  3867. #endif
  3868. /* CGI needs it as REMOTE_USER */
  3869. if (ah->user != NULL) {
  3870. conn->request_info.remote_user = mg_strdup(ah->user);
  3871. } else {
  3872. return 0;
  3873. }
  3874. return 1;
  3875. }
  3876. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  3877. {
  3878. char *eof;
  3879. size_t len;
  3880. char *memend;
  3881. if (!filep) {
  3882. return NULL;
  3883. }
  3884. if (filep->membuf != NULL && *p != NULL) {
  3885. memend = (char *)&filep->membuf[filep->size];
  3886. /* Search for \n from p till the end of stream */
  3887. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  3888. if (eof != NULL) {
  3889. eof += 1; /* Include \n */
  3890. } else {
  3891. eof = memend; /* Copy remaining data */
  3892. }
  3893. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  3894. memcpy(buf, *p, len);
  3895. buf[len] = '\0';
  3896. *p += len;
  3897. return len ? eof : NULL;
  3898. } else if (filep->fp != NULL) {
  3899. return fgets(buf, (int)size, filep->fp);
  3900. } else {
  3901. return NULL;
  3902. }
  3903. }
  3904. struct read_auth_file_struct {
  3905. struct mg_connection *conn;
  3906. struct ah ah;
  3907. char *domain;
  3908. char buf[256 + 256 + 40];
  3909. char *f_user;
  3910. char *f_domain;
  3911. char *f_ha1;
  3912. };
  3913. static int read_auth_file(struct file *filep,
  3914. struct read_auth_file_struct *workdata)
  3915. {
  3916. char *p;
  3917. int is_authorized = 0;
  3918. struct file fp;
  3919. size_t l;
  3920. if (!filep || !workdata) {
  3921. return 0;
  3922. }
  3923. /* Loop over passwords file */
  3924. p = (char *)filep->membuf;
  3925. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  3926. l = strlen(workdata->buf);
  3927. while (l > 0) {
  3928. if (isspace(workdata->buf[l - 1]) ||
  3929. iscntrl(workdata->buf[l - 1])) {
  3930. l--;
  3931. workdata->buf[l] = 0;
  3932. } else
  3933. break;
  3934. }
  3935. if (l < 1) {
  3936. continue;
  3937. }
  3938. workdata->f_user = workdata->buf;
  3939. if (workdata->f_user[0] == ':') {
  3940. /* user names may not contain a ':' and may not be empty,
  3941. * so lines starting with ':' may be used for a special purpose */
  3942. if (workdata->f_user[1] == '#') {
  3943. /* :# is a comment */
  3944. continue;
  3945. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  3946. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  3947. is_authorized = read_auth_file(&fp, workdata);
  3948. mg_fclose(&fp);
  3949. } else {
  3950. mg_cry(workdata->conn,
  3951. "%s: cannot open authorization file: %s",
  3952. __func__,
  3953. workdata->buf);
  3954. }
  3955. continue;
  3956. }
  3957. /* everything is invalid for the moment (might change in the
  3958. * future) */
  3959. mg_cry(workdata->conn,
  3960. "%s: syntax error in authorization file: %s",
  3961. __func__,
  3962. workdata->buf);
  3963. continue;
  3964. }
  3965. workdata->f_domain = strchr(workdata->f_user, ':');
  3966. if (workdata->f_domain == NULL) {
  3967. mg_cry(workdata->conn,
  3968. "%s: syntax error in authorization file: %s",
  3969. __func__,
  3970. workdata->buf);
  3971. continue;
  3972. }
  3973. *(workdata->f_domain) = 0;
  3974. (workdata->f_domain)++;
  3975. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  3976. if (workdata->f_ha1 == NULL) {
  3977. mg_cry(workdata->conn,
  3978. "%s: syntax error in authorization file: %s",
  3979. __func__,
  3980. workdata->buf);
  3981. continue;
  3982. }
  3983. *(workdata->f_ha1) = 0;
  3984. (workdata->f_ha1)++;
  3985. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  3986. !strcmp(workdata->domain, workdata->f_domain)) {
  3987. return check_password(workdata->conn->request_info.request_method,
  3988. workdata->f_ha1,
  3989. workdata->ah.uri,
  3990. workdata->ah.nonce,
  3991. workdata->ah.nc,
  3992. workdata->ah.cnonce,
  3993. workdata->ah.qop,
  3994. workdata->ah.response);
  3995. }
  3996. }
  3997. return is_authorized;
  3998. }
  3999. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4000. static int authorize(struct mg_connection *conn, struct file *filep)
  4001. {
  4002. struct read_auth_file_struct workdata;
  4003. char buf[MG_BUF_LEN];
  4004. if (!conn || !conn->ctx) {
  4005. return 0;
  4006. }
  4007. memset(&workdata, 0, sizeof(workdata));
  4008. workdata.conn = conn;
  4009. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4010. return 0;
  4011. }
  4012. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4013. return read_auth_file(filep, &workdata);
  4014. }
  4015. /* Return 1 if request is authorised, 0 otherwise. */
  4016. static int check_authorization(struct mg_connection *conn, const char *path)
  4017. {
  4018. char fname[PATH_MAX];
  4019. struct vec uri_vec, filename_vec;
  4020. const char *list;
  4021. struct file file = STRUCT_FILE_INITIALIZER;
  4022. int authorized = 1;
  4023. if (!conn || !conn->ctx) {
  4024. return 0;
  4025. }
  4026. list = conn->ctx->config[PROTECT_URI];
  4027. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4028. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  4029. mg_snprintf(conn,
  4030. fname,
  4031. sizeof(fname),
  4032. "%.*s",
  4033. (int)filename_vec.len,
  4034. filename_vec.ptr);
  4035. if (!mg_fopen(conn, fname, "r", &file)) {
  4036. mg_cry(conn,
  4037. "%s: cannot open %s: %s",
  4038. __func__,
  4039. fname,
  4040. strerror(errno));
  4041. }
  4042. break;
  4043. }
  4044. }
  4045. if (!is_file_opened(&file)) {
  4046. open_auth_file(conn, path, &file);
  4047. }
  4048. if (is_file_opened(&file)) {
  4049. authorized = authorize(conn, &file);
  4050. mg_fclose(&file);
  4051. }
  4052. return authorized;
  4053. }
  4054. static void send_authorization_request(struct mg_connection *conn)
  4055. {
  4056. char date[64];
  4057. time_t curtime = time(NULL);
  4058. if (conn && conn->ctx) {
  4059. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  4060. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4061. nonce += conn->ctx->nonce_count;
  4062. ++conn->ctx->nonce_count;
  4063. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4064. nonce ^= (uintptr_t)(conn->ctx);
  4065. conn->status_code = 401;
  4066. conn->must_close = 1;
  4067. gmt_time_string(date, sizeof(date), &curtime);
  4068. mg_printf(conn,
  4069. "HTTP/1.1 401 Unauthorized\r\n"
  4070. "Date: %s\r\n"
  4071. "Connection: %s\r\n"
  4072. "Content-Length: 0\r\n"
  4073. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4074. "nonce=\"%lu\"\r\n\r\n",
  4075. date,
  4076. suggest_connection_header(conn),
  4077. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4078. nonce);
  4079. }
  4080. }
  4081. static int is_authorized_for_put(struct mg_connection *conn)
  4082. {
  4083. if (conn) {
  4084. struct file file = STRUCT_FILE_INITIALIZER;
  4085. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4086. int ret = 0;
  4087. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4088. ret = authorize(conn, &file);
  4089. mg_fclose(&file);
  4090. }
  4091. return ret;
  4092. }
  4093. return 0;
  4094. }
  4095. int mg_modify_passwords_file(const char *fname,
  4096. const char *domain,
  4097. const char *user,
  4098. const char *pass)
  4099. {
  4100. int found, i;
  4101. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4102. FILE *fp, *fp2;
  4103. found = 0;
  4104. fp = fp2 = NULL;
  4105. /* Regard empty password as no password - remove user record. */
  4106. if (pass != NULL && pass[0] == '\0') {
  4107. pass = NULL;
  4108. }
  4109. /* Other arguments must not be empty */
  4110. if (fname == NULL || domain == NULL || user == NULL) {
  4111. return 0;
  4112. }
  4113. /* Using the given file format, user name and domain must not contain ':'
  4114. */
  4115. if (strchr(user, ':') != NULL) {
  4116. return 0;
  4117. }
  4118. if (strchr(domain, ':') != NULL) {
  4119. return 0;
  4120. }
  4121. /* Do not allow control characters like newline in user name and domain.
  4122. * Do not allow excessively long names either. */
  4123. for (i = 0; i < 255 && user[i] != 0; i++) {
  4124. if (iscntrl(user[i])) {
  4125. return 0;
  4126. }
  4127. }
  4128. if (user[i]) {
  4129. return 0;
  4130. }
  4131. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4132. if (iscntrl(domain[i])) {
  4133. return 0;
  4134. }
  4135. }
  4136. if (domain[i]) {
  4137. return 0;
  4138. }
  4139. /* Create a temporary file name */
  4140. (void)snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  4141. tmp[sizeof(tmp) - 1] = 0;
  4142. /* Create the file if does not exist */
  4143. if ((fp = fopen(fname, "a+")) != NULL) {
  4144. (void)fclose(fp);
  4145. }
  4146. /* Open the given file and temporary file */
  4147. if ((fp = fopen(fname, "r")) == NULL) {
  4148. return 0;
  4149. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4150. fclose(fp);
  4151. return 0;
  4152. }
  4153. /* Copy the stuff to temporary file */
  4154. while (fgets(line, sizeof(line), fp) != NULL) {
  4155. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4156. continue;
  4157. }
  4158. u[255] = 0;
  4159. d[255] = 0;
  4160. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4161. found++;
  4162. if (pass != NULL) {
  4163. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4164. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4165. }
  4166. } else {
  4167. fprintf(fp2, "%s", line);
  4168. }
  4169. }
  4170. /* If new user, just add it */
  4171. if (!found && pass != NULL) {
  4172. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4173. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4174. }
  4175. /* Close files */
  4176. fclose(fp);
  4177. fclose(fp2);
  4178. /* Put the temp file in place of real file */
  4179. IGNORE_UNUSED_RESULT(remove(fname));
  4180. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4181. return 1;
  4182. }
  4183. static int is_valid_port(unsigned int port) { return port < 0xffff; }
  4184. static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4185. {
  4186. struct addrinfo hints, *res, *ressave;
  4187. int ret = 0;
  4188. memset(&hints, 0, sizeof(struct addrinfo));
  4189. hints.ai_family = af;
  4190. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4191. /* bad src string or bad address family */
  4192. return 0;
  4193. }
  4194. ressave = res;
  4195. while (res) {
  4196. if (dstlen >= res->ai_addrlen) {
  4197. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4198. ret = 1;
  4199. }
  4200. res = res->ai_next;
  4201. }
  4202. freeaddrinfo(ressave);
  4203. return ret;
  4204. }
  4205. static SOCKET conn2(struct mg_context *ctx /* may be null */,
  4206. const char *host,
  4207. int port,
  4208. int use_ssl,
  4209. char *ebuf,
  4210. size_t ebuf_len)
  4211. {
  4212. union usa sa;
  4213. SOCKET sock = INVALID_SOCKET;
  4214. memset(&sa, 0, sizeof(sa));
  4215. if (ebuf_len > 0) {
  4216. *ebuf = 0;
  4217. }
  4218. if (host == NULL) {
  4219. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  4220. return INVALID_SOCKET;
  4221. }
  4222. if (port < 0 || !is_valid_port((unsigned)port)) {
  4223. snprintf(ebuf, ebuf_len, "%s", "invalid port");
  4224. return INVALID_SOCKET;
  4225. }
  4226. if (use_ssl && (SSLv23_client_method == NULL)) {
  4227. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  4228. return INVALID_SOCKET;
  4229. }
  4230. if (mg_inet_pton(AF_INET, host, &sa.sin, sizeof(sa.sin))) {
  4231. sa.sin.sin_port = htons((uint16_t)port);
  4232. #ifdef USE_IPV6
  4233. } else if (mg_inet_pton(AF_INET6, host, &sa.sin6, sizeof(sa.sin6))) {
  4234. sa.sin6.sin6_port = htons((uint16_t)port);
  4235. #endif
  4236. } else {
  4237. snprintf(ebuf, ebuf_len, "%s", "host not found");
  4238. return INVALID_SOCKET;
  4239. }
  4240. sock = socket(PF_INET, SOCK_STREAM, 0);
  4241. if (sock == INVALID_SOCKET) {
  4242. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  4243. return INVALID_SOCKET;
  4244. }
  4245. set_close_on_exec(sock, fc(ctx));
  4246. /* TODO(mid): IPV6 */
  4247. if (connect(sock, (struct sockaddr *)&sa.sin, sizeof(sa.sin)) != 0) {
  4248. snprintf(
  4249. ebuf, ebuf_len, "connect(%s:%d): %s", host, port, strerror(ERRNO));
  4250. closesocket(sock);
  4251. sock = INVALID_SOCKET;
  4252. }
  4253. return sock;
  4254. }
  4255. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  4256. {
  4257. static const char *dont_escape = "._-$,;~()";
  4258. static const char *hex = "0123456789abcdef";
  4259. char *pos = dst;
  4260. const char *end = dst + dst_len - 1;
  4261. for (; *src != '\0' && pos < end; src++, pos++) {
  4262. if (isalnum(*(const unsigned char *)src) ||
  4263. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4264. *pos = *src;
  4265. } else if (pos + 2 < end) {
  4266. pos[0] = '%';
  4267. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4268. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4269. pos += 2;
  4270. } else {
  4271. break;
  4272. }
  4273. }
  4274. *pos = '\0';
  4275. return (*src == '\0') ? (int)(pos - dst) : -1;
  4276. }
  4277. static void print_dir_entry(struct de *de)
  4278. {
  4279. char size[64], mod[64], href[PATH_MAX];
  4280. struct tm *tm;
  4281. if (de->file.is_directory) {
  4282. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  4283. } else {
  4284. /* We use (signed) cast below because MSVC 6 compiler cannot
  4285. * convert unsigned __int64 to double. Sigh. */
  4286. if (de->file.size < 1024) {
  4287. mg_snprintf(de->conn, size, sizeof(size), "%d", (int)de->file.size);
  4288. } else if (de->file.size < 0x100000) {
  4289. mg_snprintf(de->conn,
  4290. size,
  4291. sizeof(size),
  4292. "%.1fk",
  4293. (double)de->file.size / 1024.0);
  4294. } else if (de->file.size < 0x40000000) {
  4295. mg_snprintf(de->conn,
  4296. size,
  4297. sizeof(size),
  4298. "%.1fM",
  4299. (double)de->file.size / 1048576);
  4300. } else {
  4301. mg_snprintf(de->conn,
  4302. size,
  4303. sizeof(size),
  4304. "%.1fG",
  4305. (double)de->file.size / 1073741824);
  4306. }
  4307. }
  4308. tm = localtime(&de->file.last_modified);
  4309. if (tm != NULL) {
  4310. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4311. } else {
  4312. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4313. mod[sizeof(mod) - 1] = '\0';
  4314. }
  4315. mg_url_encode(de->file_name, href, sizeof(href));
  4316. de->conn->num_bytes_sent +=
  4317. mg_printf(de->conn,
  4318. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4319. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4320. de->conn->request_info.uri,
  4321. href,
  4322. de->file.is_directory ? "/" : "",
  4323. de->file_name,
  4324. de->file.is_directory ? "/" : "",
  4325. mod,
  4326. size);
  4327. }
  4328. /* This function is called from send_directory() and used for
  4329. * sorting directory entries by size, or name, or modification time.
  4330. * On windows, __cdecl specification is needed in case if project is built
  4331. * with __stdcall convention. qsort always requires __cdels callback. */
  4332. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  4333. {
  4334. if (p1 && p2) {
  4335. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4336. const char *query_string = a->conn->request_info.query_string;
  4337. int cmp_result = 0;
  4338. if (query_string == NULL) {
  4339. query_string = "na";
  4340. }
  4341. if (a->file.is_directory && !b->file.is_directory) {
  4342. return -1; /* Always put directories on top */
  4343. } else if (!a->file.is_directory && b->file.is_directory) {
  4344. return 1; /* Always put directories on top */
  4345. } else if (*query_string == 'n') {
  4346. cmp_result = strcmp(a->file_name, b->file_name);
  4347. } else if (*query_string == 's') {
  4348. cmp_result = a->file.size == b->file.size
  4349. ? 0
  4350. : a->file.size > b->file.size ? 1 : -1;
  4351. } else if (*query_string == 'd') {
  4352. cmp_result =
  4353. (a->file.last_modified == b->file.last_modified)
  4354. ? 0
  4355. : ((a->file.last_modified > b->file.last_modified) ? 1
  4356. : -1);
  4357. }
  4358. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4359. }
  4360. return 0;
  4361. }
  4362. static int must_hide_file(struct mg_connection *conn, const char *path)
  4363. {
  4364. if (conn && conn->ctx) {
  4365. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4366. const char *pattern = conn->ctx->config[HIDE_FILES];
  4367. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  4368. (pattern != NULL &&
  4369. match_prefix(pattern, strlen(pattern), path) > 0);
  4370. }
  4371. return 0;
  4372. }
  4373. static int scan_directory(struct mg_connection *conn,
  4374. const char *dir,
  4375. void *data,
  4376. void (*cb)(struct de *, void *))
  4377. {
  4378. char path[PATH_MAX];
  4379. struct dirent *dp;
  4380. DIR *dirp;
  4381. struct de de;
  4382. if ((dirp = opendir(dir)) == NULL) {
  4383. return 0;
  4384. } else {
  4385. de.conn = conn;
  4386. while ((dp = readdir(dirp)) != NULL) {
  4387. /* Do not show current dir and hidden files */
  4388. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  4389. must_hide_file(conn, dp->d_name)) {
  4390. continue;
  4391. }
  4392. mg_snprintf(
  4393. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4394. /* If we don't memset stat structure to zero, mtime will have
  4395. * garbage and strftime() will segfault later on in
  4396. * print_dir_entry(). memset is required only if mg_stat()
  4397. * fails. For more details, see
  4398. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4399. memset(&de.file, 0, sizeof(de.file));
  4400. if (!mg_stat(conn, path, &de.file)) {
  4401. mg_cry(conn,
  4402. "%s: mg_stat(%s) failed: %s",
  4403. __func__,
  4404. path,
  4405. strerror(ERRNO));
  4406. }
  4407. de.file_name = dp->d_name;
  4408. cb(&de, data);
  4409. }
  4410. (void)closedir(dirp);
  4411. }
  4412. return 1;
  4413. }
  4414. static int remove_directory(struct mg_connection *conn, const char *dir)
  4415. {
  4416. char path[PATH_MAX];
  4417. struct dirent *dp;
  4418. DIR *dirp;
  4419. struct de de;
  4420. if ((dirp = opendir(dir)) == NULL) {
  4421. return 0;
  4422. } else {
  4423. de.conn = conn;
  4424. while ((dp = readdir(dirp)) != NULL) {
  4425. /* Do not show current dir (but show hidden files as they will
  4426. * also be removed) */
  4427. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4428. continue;
  4429. }
  4430. mg_snprintf(
  4431. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4432. /* If we don't memset stat structure to zero, mtime will have
  4433. * garbage and strftime() will segfault later on in
  4434. * print_dir_entry(). memset is required only if mg_stat()
  4435. * fails. For more details, see
  4436. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4437. memset(&de.file, 0, sizeof(de.file));
  4438. if (!mg_stat(conn, path, &de.file)) {
  4439. mg_cry(conn,
  4440. "%s: mg_stat(%s) failed: %s",
  4441. __func__,
  4442. path,
  4443. strerror(ERRNO));
  4444. }
  4445. if (de.file.membuf == NULL) {
  4446. /* file is not in memory */
  4447. if (de.file.is_directory) {
  4448. remove_directory(conn, path);
  4449. } else {
  4450. mg_remove(path);
  4451. }
  4452. }
  4453. }
  4454. (void)closedir(dirp);
  4455. IGNORE_UNUSED_RESULT(rmdir(dir));
  4456. }
  4457. return 1;
  4458. }
  4459. struct dir_scan_data {
  4460. struct de *entries;
  4461. unsigned int num_entries;
  4462. unsigned int arr_size;
  4463. };
  4464. /* Behaves like realloc(), but frees original pointer on failure */
  4465. static void *realloc2(void *ptr, size_t size)
  4466. {
  4467. void *new_ptr = mg_realloc(ptr, size);
  4468. if (new_ptr == NULL) {
  4469. mg_free(ptr);
  4470. }
  4471. return new_ptr;
  4472. }
  4473. static void dir_scan_callback(struct de *de, void *data)
  4474. {
  4475. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  4476. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  4477. dsd->arr_size *= 2;
  4478. dsd->entries = (struct de *)realloc2(
  4479. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  4480. }
  4481. if (dsd->entries == NULL) {
  4482. /* TODO(lsm, low): propagate an error to the caller */
  4483. dsd->num_entries = 0;
  4484. } else {
  4485. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  4486. dsd->entries[dsd->num_entries].file = de->file;
  4487. dsd->entries[dsd->num_entries].conn = de->conn;
  4488. dsd->num_entries++;
  4489. }
  4490. }
  4491. static void handle_directory_request(struct mg_connection *conn,
  4492. const char *dir)
  4493. {
  4494. unsigned int i;
  4495. int sort_direction;
  4496. struct dir_scan_data data = {NULL, 0, 128};
  4497. char date[64];
  4498. time_t curtime = time(NULL);
  4499. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  4500. send_http_error(conn,
  4501. 500,
  4502. "Error: Cannot open directory\nopendir(%s): %s",
  4503. dir,
  4504. strerror(ERRNO));
  4505. return;
  4506. }
  4507. gmt_time_string(date, sizeof(date), &curtime);
  4508. if (!conn) {
  4509. return;
  4510. }
  4511. sort_direction = conn->request_info.query_string != NULL &&
  4512. conn->request_info.query_string[1] == 'd'
  4513. ? 'a'
  4514. : 'd';
  4515. conn->must_close = 1;
  4516. mg_printf(conn,
  4517. "HTTP/1.1 200 OK\r\n"
  4518. "Date: %s\r\n"
  4519. "Connection: close\r\n"
  4520. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  4521. date);
  4522. conn->num_bytes_sent +=
  4523. mg_printf(conn,
  4524. "<html><head><title>Index of %s</title>"
  4525. "<style>th {text-align: left;}</style></head>"
  4526. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  4527. "<tr><th><a href=\"?n%c\">Name</a></th>"
  4528. "<th><a href=\"?d%c\">Modified</a></th>"
  4529. "<th><a href=\"?s%c\">Size</a></th></tr>"
  4530. "<tr><td colspan=\"3\"><hr></td></tr>",
  4531. conn->request_info.uri,
  4532. conn->request_info.uri,
  4533. sort_direction,
  4534. sort_direction,
  4535. sort_direction);
  4536. /* Print first entry - link to a parent directory */
  4537. conn->num_bytes_sent +=
  4538. mg_printf(conn,
  4539. "<tr><td><a href=\"%s%s\">%s</a></td>"
  4540. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4541. conn->request_info.uri,
  4542. "..",
  4543. "Parent directory",
  4544. "-",
  4545. "-");
  4546. /* Sort and print directory entries */
  4547. if (data.entries != NULL) {
  4548. qsort(data.entries,
  4549. (size_t)data.num_entries,
  4550. sizeof(data.entries[0]),
  4551. compare_dir_entries);
  4552. for (i = 0; i < data.num_entries; i++) {
  4553. print_dir_entry(&data.entries[i]);
  4554. mg_free(data.entries[i].file_name);
  4555. }
  4556. mg_free(data.entries);
  4557. }
  4558. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  4559. conn->status_code = 200;
  4560. }
  4561. /* Send len bytes from the opened file to the client. */
  4562. static void send_file_data(struct mg_connection *conn,
  4563. struct file *filep,
  4564. int64_t offset,
  4565. int64_t len)
  4566. {
  4567. char buf[MG_BUF_LEN];
  4568. int to_read, num_read, num_written;
  4569. int64_t size;
  4570. if (!filep || !conn) {
  4571. return;
  4572. }
  4573. /* Sanity check the offset */
  4574. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  4575. offset = offset < 0 ? 0 : offset > size ? size : offset;
  4576. if (len > 0 && filep->membuf != NULL && size > 0) {
  4577. /* file stored in memory */
  4578. if (len > size - offset) {
  4579. len = size - offset;
  4580. }
  4581. mg_write(conn, filep->membuf + offset, (size_t)len);
  4582. } else if (len > 0 && filep->fp != NULL) {
  4583. /* file stored on disk */
  4584. #if defined(__linux__)
  4585. /* TODO (high): Test sendfile for Linux */
  4586. if (conn->throttle == 0 && conn->ssl == 0) {
  4587. off_t sf_offs = (off_t)offset;
  4588. ssize_t sf_sent;
  4589. int sf_file = fileno(filep->fp);
  4590. do {
  4591. /* 2147479552 (0x7FFFF000) is a limit found by experiment on 64
  4592. * bit Linux (2^31 minus one memory page of 4k?). */
  4593. ssize_t sf_tosend =
  4594. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  4595. sf_sent =
  4596. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  4597. if (sf_sent > 0) {
  4598. conn->num_bytes_sent += sf_sent;
  4599. len -= sf_sent;
  4600. offset += sf_sent;
  4601. }
  4602. } while ((len > 0) && (sf_sent >= 0));
  4603. if (sf_sent > 0) {
  4604. return; /* OK */
  4605. }
  4606. /* sf_sent<0 means error, thus fall back to the classic way */
  4607. mg_cry(conn,
  4608. "%s: sendfile() failed: %s (now trying read+write)",
  4609. __func__,
  4610. strerror(ERRNO));
  4611. offset = (int64_t)sf_offs;
  4612. }
  4613. #endif
  4614. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  4615. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  4616. send_http_error(
  4617. conn, 500, "%s", "Error: Unable to access file at requested position.");
  4618. } else {
  4619. while (len > 0) {
  4620. /* Calculate how much to read from the file in the buffer */
  4621. to_read = sizeof(buf);
  4622. if ((int64_t)to_read > len) {
  4623. to_read = (int)len;
  4624. }
  4625. /* Read from file, exit the loop on error */
  4626. if ((num_read =
  4627. (int)fread(buf, 1, (size_t)to_read, filep->fp)) <= 0) {
  4628. break;
  4629. }
  4630. /* Send read bytes to the client, exit the loop on error */
  4631. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  4632. num_read) {
  4633. break;
  4634. }
  4635. /* Both read and were successful, adjust counters */
  4636. conn->num_bytes_sent += num_written;
  4637. len -= num_written;
  4638. }
  4639. }
  4640. }
  4641. }
  4642. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  4643. {
  4644. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  4645. }
  4646. static void construct_etag(char *buf, size_t buf_len, const struct file *filep)
  4647. {
  4648. if (filep != NULL && buf != NULL) {
  4649. snprintf(buf,
  4650. buf_len,
  4651. "\"%lx.%" INT64_FMT "\"",
  4652. (unsigned long)filep->last_modified,
  4653. filep->size);
  4654. }
  4655. }
  4656. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  4657. {
  4658. if (filep != NULL && filep->fp != NULL) {
  4659. #ifdef _WIN32
  4660. (void)conn; /* Unused. */
  4661. #else
  4662. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  4663. mg_cry(conn,
  4664. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4665. __func__,
  4666. strerror(ERRNO));
  4667. }
  4668. #endif
  4669. }
  4670. }
  4671. static void handle_static_file_request(struct mg_connection *conn,
  4672. const char *path,
  4673. struct file *filep)
  4674. {
  4675. char date[64], lm[64], etag[64], range[64];
  4676. const char *msg = "OK", *hdr;
  4677. time_t curtime = time(NULL);
  4678. int64_t cl, r1, r2;
  4679. struct vec mime_vec;
  4680. int n;
  4681. char gz_path[PATH_MAX];
  4682. const char *encoding = "";
  4683. const char *cors1, *cors2, *cors3;
  4684. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  4685. return;
  4686. }
  4687. get_mime_type(conn->ctx, path, &mime_vec);
  4688. if (filep->size > INT64_MAX) {
  4689. send_http_error(conn,
  4690. 500,
  4691. "Error: File size is too large to send\n%" INT64_FMT,
  4692. filep->size);
  4693. }
  4694. cl = (int64_t)filep->size;
  4695. conn->status_code = 200;
  4696. range[0] = '\0';
  4697. /* if this file is in fact a pre-gzipped file, rewrite its filename
  4698. * it's important to rewrite the filename after resolving
  4699. * the mime type from it, to preserve the actual file's type */
  4700. if (filep->gzipped) {
  4701. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  4702. path = gz_path;
  4703. encoding = "Content-Encoding: gzip\r\n";
  4704. }
  4705. if (!mg_fopen(conn, path, "rb", filep)) {
  4706. send_http_error(conn,
  4707. 500,
  4708. "Error: Cannot open file\nfopen(%s): %s",
  4709. path,
  4710. strerror(ERRNO));
  4711. return;
  4712. }
  4713. fclose_on_exec(filep, conn);
  4714. /* If Range: header specified, act accordingly */
  4715. r1 = r2 = 0;
  4716. hdr = mg_get_header(conn, "Range");
  4717. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  4718. r2 >= 0) {
  4719. /* actually, range requests don't play well with a pre-gzipped
  4720. * file (since the range is specified in the uncompressed space) */
  4721. if (filep->gzipped) {
  4722. send_http_error(
  4723. conn,
  4724. 501,
  4725. "%s",
  4726. "Error: Range requests in gzipped files are not supported");
  4727. mg_fclose(filep);
  4728. return;
  4729. }
  4730. conn->status_code = 206;
  4731. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  4732. mg_snprintf(conn,
  4733. range,
  4734. sizeof(range),
  4735. "Content-Range: bytes "
  4736. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  4737. r1,
  4738. r1 + cl - 1,
  4739. filep->size);
  4740. msg = "Partial Content";
  4741. }
  4742. hdr = mg_get_header(conn, "Origin");
  4743. if (hdr) {
  4744. /* Cross-origin resource sharing (CORS), see
  4745. * http://www.html5rocks.com/en/tutorials/cors/,
  4746. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  4747. * preflight is not supported for files. */
  4748. cors1 = "Access-Control-Allow-Origin: ";
  4749. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4750. cors3 = "\r\n";
  4751. } else {
  4752. cors1 = cors2 = cors3 = "";
  4753. }
  4754. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  4755. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  4756. gmt_time_string(date, sizeof(date), &curtime);
  4757. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  4758. construct_etag(etag, sizeof(etag), filep);
  4759. (void)mg_printf(conn,
  4760. "HTTP/1.1 %d %s\r\n"
  4761. "%s%s%s"
  4762. "Date: %s\r\n"
  4763. "Last-Modified: %s\r\n"
  4764. "Etag: %s\r\n"
  4765. "Content-Type: %.*s\r\n"
  4766. "Content-Length: %" INT64_FMT "\r\n"
  4767. "Connection: %s\r\n"
  4768. "Accept-Ranges: bytes\r\n"
  4769. "%s%s\r\n",
  4770. conn->status_code,
  4771. msg,
  4772. cors1,
  4773. cors2,
  4774. cors3,
  4775. date,
  4776. lm,
  4777. etag,
  4778. (int)mime_vec.len,
  4779. mime_vec.ptr,
  4780. cl,
  4781. suggest_connection_header(conn),
  4782. range,
  4783. encoding);
  4784. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  4785. send_file_data(conn, filep, r1, cl);
  4786. }
  4787. mg_fclose(filep);
  4788. }
  4789. void mg_send_file(struct mg_connection *conn, const char *path)
  4790. {
  4791. struct file file = STRUCT_FILE_INITIALIZER;
  4792. if (mg_stat(conn, path, &file)) {
  4793. if (file.is_directory) {
  4794. if (!conn) {
  4795. return;
  4796. }
  4797. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  4798. "yes")) {
  4799. handle_directory_request(conn, path);
  4800. } else {
  4801. send_http_error(
  4802. conn, 403, "%s", "Error: Directory listing denied");
  4803. }
  4804. } else {
  4805. handle_static_file_request(conn, path, &file);
  4806. }
  4807. } else {
  4808. send_http_error(conn, 404, "%s", "Error: File not found");
  4809. }
  4810. }
  4811. /* Parse HTTP headers from the given buffer, advance buffer to the point
  4812. * where parsing stopped. */
  4813. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  4814. {
  4815. int i;
  4816. if (!ri) {
  4817. return;
  4818. }
  4819. ri->num_headers = 0;
  4820. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  4821. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  4822. ri->http_headers[i].value = skip(buf, "\r\n");
  4823. if (ri->http_headers[i].name[0] == '\0') {
  4824. break;
  4825. }
  4826. ri->num_headers = i + 1;
  4827. }
  4828. }
  4829. static int is_valid_http_method(const char *method)
  4830. {
  4831. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  4832. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  4833. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  4834. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  4835. !strcmp(method, "MKCOL");
  4836. /* TRACE method is not supported for security reasons */
  4837. }
  4838. /* Parse HTTP request, fill in mg_request_info structure.
  4839. * This function modifies the buffer by NUL-terminating
  4840. * HTTP request components, header names and header values. */
  4841. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  4842. {
  4843. int is_request, request_length;
  4844. if (!ri) {
  4845. return 0;
  4846. }
  4847. request_length = get_request_len(buf, len);
  4848. if (request_length > 0) {
  4849. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  4850. * remote_port */
  4851. ri->remote_user = ri->request_method = ri->uri = ri->http_version =
  4852. NULL;
  4853. ri->num_headers = 0;
  4854. buf[request_length - 1] = '\0';
  4855. /* RFC says that all initial whitespaces should be ingored */
  4856. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  4857. buf++;
  4858. }
  4859. ri->request_method = skip(&buf, " ");
  4860. ri->uri = skip(&buf, " ");
  4861. ri->http_version = skip(&buf, "\r\n");
  4862. /* HTTP message could be either HTTP request or HTTP response, e.g.
  4863. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  4864. is_request = is_valid_http_method(ri->request_method);
  4865. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  4866. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  4867. request_length = -1;
  4868. } else {
  4869. if (is_request) {
  4870. ri->http_version += 5;
  4871. }
  4872. parse_http_headers(&buf, ri);
  4873. }
  4874. }
  4875. return request_length;
  4876. }
  4877. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  4878. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  4879. * buffer (which marks the end of HTTP request). Buffer buf may already
  4880. * have some data. The length of the data is stored in nread.
  4881. * Upon every read operation, increase nread by the number of bytes read. */
  4882. static int read_request(
  4883. FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
  4884. {
  4885. int request_len, n = 0;
  4886. struct timespec last_action_time = {0, 0};
  4887. double request_timeout;
  4888. if (!conn) {
  4889. return 0;
  4890. }
  4891. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4892. /* value of request_timeout is in seconds, config in milliseconds */
  4893. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4894. } else {
  4895. request_timeout = -1.0;
  4896. }
  4897. request_len = get_request_len(buf, *nread);
  4898. while (
  4899. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  4900. (request_len == 0) &&
  4901. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  4902. request_timeout) ||
  4903. (request_timeout < 0)) &&
  4904. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout)) >
  4905. 0)) {
  4906. *nread += n;
  4907. /* assert(*nread <= bufsiz); */
  4908. if (*nread > bufsiz) {
  4909. return -2;
  4910. }
  4911. request_len = get_request_len(buf, *nread);
  4912. if (request_timeout > 0.0) {
  4913. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  4914. }
  4915. }
  4916. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  4917. }
  4918. /* For given directory path, substitute it to valid index file.
  4919. * Return 1 if index file has been found, 0 if not found.
  4920. * If the file is found, it's stats is returned in stp. */
  4921. static int substitute_index_file(struct mg_connection *conn,
  4922. char *path,
  4923. size_t path_len,
  4924. struct file *filep)
  4925. {
  4926. if (conn && conn->ctx) {
  4927. const char *list = conn->ctx->config[INDEX_FILES];
  4928. struct file file = STRUCT_FILE_INITIALIZER;
  4929. struct vec filename_vec;
  4930. size_t n = strlen(path);
  4931. int found = 0;
  4932. /* The 'path' given to us points to the directory. Remove all trailing
  4933. * directory separator characters from the end of the path, and
  4934. * then append single directory separator character. */
  4935. while (n > 0 && path[n - 1] == '/') {
  4936. n--;
  4937. }
  4938. path[n] = '/';
  4939. /* Traverse index files list. For each entry, append it to the given
  4940. * path and see if the file exists. If it exists, break the loop */
  4941. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  4942. /* Ignore too long entries that may overflow path buffer */
  4943. if (filename_vec.len > path_len - (n + 2)) {
  4944. continue;
  4945. }
  4946. /* Prepare full path to the index file */
  4947. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  4948. /* Does it exist? */
  4949. if (mg_stat(conn, path, &file)) {
  4950. /* Yes it does, break the loop */
  4951. *filep = file;
  4952. found = 1;
  4953. break;
  4954. }
  4955. }
  4956. /* If no index file exists, restore directory path */
  4957. if (!found) {
  4958. path[n] = '\0';
  4959. }
  4960. return found;
  4961. }
  4962. return 0;
  4963. }
  4964. /* Return True if we should reply 304 Not Modified. */
  4965. static int is_not_modified(const struct mg_connection *conn,
  4966. const struct file *filep)
  4967. {
  4968. char etag[64];
  4969. const char *ims = mg_get_header(conn, "If-Modified-Since");
  4970. const char *inm = mg_get_header(conn, "If-None-Match");
  4971. construct_etag(etag, sizeof(etag), filep);
  4972. if (!filep) {
  4973. return 0;
  4974. }
  4975. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  4976. (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  4977. }
  4978. static int
  4979. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  4980. {
  4981. const char *expect, *body;
  4982. char buf[MG_BUF_LEN];
  4983. int to_read, nread, success = 0;
  4984. int64_t buffered_len;
  4985. double timeout = -1.0;
  4986. if (!conn) {
  4987. return 0;
  4988. }
  4989. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4990. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4991. }
  4992. expect = mg_get_header(conn, "Expect");
  4993. /* assert(fp != NULL); */
  4994. if (!fp) {
  4995. send_http_error(conn, 500, "%s", "Error: NULL File");
  4996. return 0;
  4997. }
  4998. if (conn->content_len == -1 && !conn->is_chunked) {
  4999. /* Content length is not specified by the client. */
  5000. send_http_error(
  5001. conn, 411, "%s", "Error: Client did not specify content length");
  5002. } else if ((expect != NULL) &&
  5003. (mg_strcasecmp(expect, "100-continue") != 0)) {
  5004. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5005. send_http_error(
  5006. conn, 417, "Error: Can not fulfill expectation %s", expect);
  5007. } else {
  5008. if (expect != NULL) {
  5009. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5010. conn->status_code = 100;
  5011. } else {
  5012. conn->status_code = 200;
  5013. }
  5014. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  5015. conn->consumed_content;
  5016. /* assert(buffered_len >= 0); */
  5017. /* assert(conn->consumed_content == 0); */
  5018. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5019. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5020. return 0;
  5021. }
  5022. if (buffered_len > 0) {
  5023. if ((int64_t)buffered_len > conn->content_len) {
  5024. buffered_len = (int)conn->content_len;
  5025. }
  5026. body = conn->buf + conn->request_len + conn->consumed_content;
  5027. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5028. conn->consumed_content += buffered_len;
  5029. }
  5030. nread = 0;
  5031. while (conn->consumed_content < conn->content_len) {
  5032. to_read = sizeof(buf);
  5033. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5034. to_read = (int)(conn->content_len - conn->consumed_content);
  5035. }
  5036. nread = pull(NULL, conn, buf, to_read, timeout);
  5037. if (nread <= 0 ||
  5038. push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5039. break;
  5040. }
  5041. conn->consumed_content += nread;
  5042. }
  5043. if (conn->consumed_content == conn->content_len) {
  5044. success = nread >= 0;
  5045. }
  5046. /* Each error code path in this function must send an error */
  5047. if (!success) {
  5048. /* NOTE: Maybe some data has already been sent. */
  5049. /* TODO (low): If some data has been sent, a correct error
  5050. * reply can no longer be sent, so just close the connection */
  5051. send_http_error(conn, 500, "%s", "");
  5052. }
  5053. }
  5054. return success;
  5055. }
  5056. #if !defined(NO_CGI)
  5057. /* This structure helps to create an environment for the spawned CGI program.
  5058. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5059. * last element must be NULL.
  5060. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5061. * strings must reside in a contiguous buffer. The end of the buffer is
  5062. * marked by two '\0' characters.
  5063. * We satisfy both worlds: we create an envp array (which is vars), all
  5064. * entries are actually pointers inside buf. */
  5065. struct cgi_env_block {
  5066. struct mg_connection *conn;
  5067. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  5068. unsigned int len; /* Space taken */
  5069. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  5070. unsigned int nvars; /* Number of variables */
  5071. };
  5072. static char *addenv(struct cgi_env_block *block,
  5073. PRINTF_FORMAT_STRING(const char *fmt),
  5074. ...) PRINTF_ARGS(2, 3);
  5075. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5076. * pointer into the vars array. */
  5077. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  5078. {
  5079. int n, space;
  5080. char *added;
  5081. va_list ap;
  5082. if (block == NULL || fmt == NULL) {
  5083. return NULL;
  5084. }
  5085. /* Calculate how much space is left in the buffer */
  5086. space = (int)(sizeof(block->buf) - block->len) - 2;
  5087. /* assert(space >= 0); */
  5088. if (space < 0) {
  5089. return NULL;
  5090. }
  5091. /* Make a pointer to the free space int the buffer */
  5092. added = block->buf + block->len;
  5093. /* Copy VARIABLE=VALUE\0 string into the free space */
  5094. va_start(ap, fmt);
  5095. n = mg_vsnprintf(block->conn, added, (size_t)space, fmt, ap);
  5096. va_end(ap);
  5097. /* Make sure we do not overflow buffer and the envp array */
  5098. if (n > 0 && n + 1 < space && block->nvars + 2 < ARRAY_SIZE(block->vars)) {
  5099. /* Append a pointer to the added string into the envp array */
  5100. block->vars[block->nvars++] = added;
  5101. /* Bump up used length counter. Include \0 terminator */
  5102. block->len += (unsigned int)(n) + 1;
  5103. } else {
  5104. mg_cry(block->conn,
  5105. "%s: CGI env buffer truncated for [%s]",
  5106. __func__,
  5107. fmt);
  5108. }
  5109. return added;
  5110. }
  5111. static void prepare_cgi_environment(struct mg_connection *conn,
  5112. const char *prog,
  5113. struct cgi_env_block *blk)
  5114. {
  5115. const char *s;
  5116. struct vec var_vec;
  5117. char *p, src_addr[IP_ADDR_STR_LEN];
  5118. int i;
  5119. if (conn == NULL || prog == NULL || blk == NULL) {
  5120. return;
  5121. }
  5122. blk->len = blk->nvars = 0;
  5123. blk->conn = conn;
  5124. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5125. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5126. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5127. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5128. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5129. /* Prepare the environment block */
  5130. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5131. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5132. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5133. /* TODO(lsm, high): fix this for IPv6 case */
  5134. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5135. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5136. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  5137. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5138. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  5139. /* SCRIPT_NAME */
  5140. addenv(blk,
  5141. "SCRIPT_NAME=%.*s",
  5142. (int)strlen(conn->request_info.uri) -
  5143. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5144. conn->request_info.uri);
  5145. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  5146. if (conn->path_info == NULL) {
  5147. addenv(blk, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5148. } else {
  5149. addenv(blk,
  5150. "PATH_TRANSLATED=%s%s",
  5151. conn->ctx->config[DOCUMENT_ROOT],
  5152. conn->path_info);
  5153. }
  5154. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5155. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5156. addenv(blk, "CONTENT_TYPE=%s", s);
  5157. }
  5158. if (conn->request_info.query_string != NULL) {
  5159. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  5160. }
  5161. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5162. addenv(blk, "CONTENT_LENGTH=%s", s);
  5163. }
  5164. if ((s = getenv("PATH")) != NULL) {
  5165. addenv(blk, "PATH=%s", s);
  5166. }
  5167. if (conn->path_info != NULL) {
  5168. addenv(blk, "PATH_INFO=%s", conn->path_info);
  5169. }
  5170. if (conn->status_code > 0) {
  5171. /* CGI error handler should show the status code */
  5172. addenv(blk, "STATUS=%d", conn->status_code);
  5173. }
  5174. #if defined(_WIN32)
  5175. if ((s = getenv("COMSPEC")) != NULL) {
  5176. addenv(blk, "COMSPEC=%s", s);
  5177. }
  5178. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5179. addenv(blk, "SYSTEMROOT=%s", s);
  5180. }
  5181. if ((s = getenv("SystemDrive")) != NULL) {
  5182. addenv(blk, "SystemDrive=%s", s);
  5183. }
  5184. if ((s = getenv("ProgramFiles")) != NULL) {
  5185. addenv(blk, "ProgramFiles=%s", s);
  5186. }
  5187. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5188. addenv(blk, "ProgramFiles(x86)=%s", s);
  5189. }
  5190. #else
  5191. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5192. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  5193. }
  5194. #endif /* _WIN32 */
  5195. if ((s = getenv("PERLLIB")) != NULL) {
  5196. addenv(blk, "PERLLIB=%s", s);
  5197. }
  5198. if (conn->request_info.remote_user != NULL) {
  5199. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  5200. addenv(blk, "%s", "AUTH_TYPE=Digest");
  5201. }
  5202. /* Add all headers as HTTP_* variables */
  5203. for (i = 0; i < conn->request_info.num_headers; i++) {
  5204. p = addenv(blk,
  5205. "HTTP_%s=%s",
  5206. conn->request_info.http_headers[i].name,
  5207. conn->request_info.http_headers[i].value);
  5208. /* Convert variable name into uppercase, and change - to _ */
  5209. for (; *p != '=' && *p != '\0'; p++) {
  5210. if (*p == '-') {
  5211. *p = '_';
  5212. }
  5213. *p = (char)toupper(*(unsigned char *)p);
  5214. }
  5215. }
  5216. /* Add user-specified variables */
  5217. s = conn->ctx->config[CGI_ENVIRONMENT];
  5218. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5219. addenv(blk, "%.*s", (int)var_vec.len, var_vec.ptr);
  5220. }
  5221. blk->vars[blk->nvars++] = NULL;
  5222. blk->buf[blk->len++] = '\0';
  5223. /* assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); */
  5224. /* assert(blk->len > 0); */
  5225. /* assert(blk->len < (int) sizeof(blk->buf)); */
  5226. if ((blk->nvars >= (int)ARRAY_SIZE(blk->vars)) || (blk->len <= 0) ||
  5227. (blk->len >= (int)sizeof(blk->buf))) {
  5228. /* TODO (mid): this statement is useless. Check original intention and
  5229. * proper replacement. */
  5230. return;
  5231. }
  5232. }
  5233. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  5234. {
  5235. char *buf;
  5236. size_t buflen;
  5237. int headers_len, data_len, i, fdin[2] = {0, 0}, fdout[2] = {0, 0};
  5238. const char *status, *status_text, *connection_state;
  5239. char *pbuf, dir[PATH_MAX], *p;
  5240. struct mg_request_info ri;
  5241. struct cgi_env_block blk;
  5242. FILE *in = NULL, *out = NULL;
  5243. struct file fout = STRUCT_FILE_INITIALIZER;
  5244. pid_t pid = (pid_t)-1;
  5245. if (conn == NULL) {
  5246. return;
  5247. }
  5248. buf = NULL;
  5249. buflen = 16384;
  5250. prepare_cgi_environment(conn, prog, &blk);
  5251. /* CGI must be executed in its own directory. 'dir' must point to the
  5252. * directory containing executable program, 'p' must point to the
  5253. * executable program name relative to 'dir'. */
  5254. (void)mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  5255. if ((p = strrchr(dir, '/')) != NULL) {
  5256. *p++ = '\0';
  5257. } else {
  5258. dir[0] = '.', dir[1] = '\0';
  5259. p = (char *)prog;
  5260. }
  5261. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  5262. send_http_error(
  5263. conn, 500, "Error: Cannot create CGI pipe: %s", strerror(ERRNO));
  5264. goto done;
  5265. }
  5266. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  5267. if (pid == (pid_t)-1) {
  5268. send_http_error(conn,
  5269. 500,
  5270. "Error: Cannot spawn CGI process [%s]: %s",
  5271. prog,
  5272. strerror(ERRNO));
  5273. goto done;
  5274. }
  5275. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5276. set_close_on_exec((SOCKET)fdin[0], conn);
  5277. set_close_on_exec((SOCKET)fdin[1], conn);
  5278. set_close_on_exec((SOCKET)fdout[0], conn);
  5279. set_close_on_exec((SOCKET)fdout[1], conn);
  5280. /* Parent closes only one side of the pipes.
  5281. * If we don't mark them as closed, close() attempt before
  5282. * return from this function throws an exception on Windows.
  5283. * Windows does not like when closed descriptor is closed again. */
  5284. (void)close(fdin[0]);
  5285. (void)close(fdout[1]);
  5286. fdin[0] = fdout[1] = -1;
  5287. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5288. send_http_error(conn,
  5289. 500,
  5290. "Error: CGI can not open fdin\nfopen: %s",
  5291. strerror(ERRNO));
  5292. goto done;
  5293. }
  5294. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5295. send_http_error(conn,
  5296. 500,
  5297. "Error: CGI can not open fdout\nfopen: %s",
  5298. strerror(ERRNO));
  5299. goto done;
  5300. }
  5301. setbuf(in, NULL);
  5302. setbuf(out, NULL);
  5303. fout.fp = out;
  5304. /* Send POST or PUT data to the CGI process if needed */
  5305. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5306. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5307. /* This is a POST/PUT request */
  5308. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  5309. /* Error sending the body data */
  5310. goto done;
  5311. }
  5312. }
  5313. /* Close so child gets an EOF. */
  5314. fclose(in);
  5315. in = NULL;
  5316. fdin[1] = -1;
  5317. /* Now read CGI reply into a buffer. We need to set correct
  5318. * status code, thus we need to see all HTTP headers first.
  5319. * Do not send anything back to client, until we buffer in all
  5320. * HTTP headers. */
  5321. data_len = 0;
  5322. buf = (char *)mg_malloc(buflen);
  5323. if (buf == NULL) {
  5324. send_http_error(conn,
  5325. 500,
  5326. "Error: Not enough memory for CGI buffer (%u bytes)",
  5327. (unsigned int)buflen);
  5328. goto done;
  5329. }
  5330. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  5331. if (headers_len <= 0) {
  5332. send_http_error(conn,
  5333. 500,
  5334. "Error: CGI program sent malformed or too big "
  5335. "(>%u bytes) HTTP headers: [%.*s]",
  5336. (unsigned)buflen,
  5337. data_len,
  5338. buf);
  5339. goto done;
  5340. }
  5341. pbuf = buf;
  5342. buf[headers_len - 1] = '\0';
  5343. parse_http_headers(&pbuf, &ri);
  5344. /* Make up and send the status line */
  5345. status_text = "OK";
  5346. if ((status = get_header(&ri, "Status")) != NULL) {
  5347. conn->status_code = atoi(status);
  5348. status_text = status;
  5349. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  5350. status_text++;
  5351. }
  5352. } else if (get_header(&ri, "Location") != NULL) {
  5353. conn->status_code = 302;
  5354. } else {
  5355. conn->status_code = 200;
  5356. }
  5357. connection_state = get_header(&ri, "Connection");
  5358. if (connection_state == NULL ||
  5359. mg_strcasecmp(connection_state, "keep-alive")) {
  5360. conn->must_close = 1;
  5361. }
  5362. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  5363. /* Send headers */
  5364. for (i = 0; i < ri.num_headers; i++) {
  5365. mg_printf(conn,
  5366. "%s: %s\r\n",
  5367. ri.http_headers[i].name,
  5368. ri.http_headers[i].value);
  5369. }
  5370. mg_write(conn, "\r\n", 2);
  5371. /* Send chunk of data that may have been read after the headers */
  5372. conn->num_bytes_sent +=
  5373. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  5374. /* Read the rest of CGI output and send to the client */
  5375. send_file_data(conn, &fout, 0, INT64_MAX);
  5376. done:
  5377. if (pid != (pid_t)-1) {
  5378. kill(pid, SIGKILL);
  5379. #if !defined(_WIN32)
  5380. {
  5381. int st;
  5382. while (waitpid(pid, &st, 0) != -1)
  5383. ; /* clean zombies */
  5384. }
  5385. #endif
  5386. }
  5387. if (fdin[0] != -1) {
  5388. close(fdin[0]);
  5389. }
  5390. if (fdout[1] != -1) {
  5391. close(fdout[1]);
  5392. }
  5393. if (in != NULL) {
  5394. fclose(in);
  5395. } else if (fdin[1] != -1) {
  5396. close(fdin[1]);
  5397. }
  5398. if (out != NULL) {
  5399. fclose(out);
  5400. } else if (fdout[0] != -1) {
  5401. close(fdout[0]);
  5402. }
  5403. if (buf != NULL) {
  5404. mg_free(buf);
  5405. }
  5406. }
  5407. #endif /* !NO_CGI */
  5408. /* For a given PUT path, create all intermediate subdirectories.
  5409. * Return 0 if the path itself is a directory.
  5410. * Return 1 if the path leads to a file.
  5411. * Return -1 for if the path is too long.
  5412. * Return -2 if path can not be created.
  5413. */
  5414. static int put_dir(struct mg_connection *conn, const char *path)
  5415. {
  5416. char buf[PATH_MAX];
  5417. const char *s, *p;
  5418. struct file file = STRUCT_FILE_INITIALIZER;
  5419. size_t len;
  5420. int res = 1;
  5421. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5422. len = (size_t)(p - path);
  5423. if (len >= sizeof(buf)) {
  5424. /* path too long */
  5425. res = -1;
  5426. break;
  5427. }
  5428. memcpy(buf, path, len);
  5429. buf[len] = '\0';
  5430. /* Try to create intermediate directory */
  5431. DEBUG_TRACE("mkdir(%s)", buf);
  5432. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5433. /* path does not exixt and can not be created */
  5434. res = -2;
  5435. break;
  5436. }
  5437. /* Is path itself a directory? */
  5438. if (p[1] == '\0') {
  5439. res = 0;
  5440. }
  5441. }
  5442. return res;
  5443. }
  5444. static void mkcol(struct mg_connection *conn, const char *path)
  5445. {
  5446. int rc, body_len;
  5447. struct de de;
  5448. char date[64];
  5449. time_t curtime = time(NULL);
  5450. if (conn == NULL) {
  5451. return;
  5452. }
  5453. /* TODO (mid): Check the send_http_error situations in this function */
  5454. memset(&de.file, 0, sizeof(de.file));
  5455. if (!mg_stat(conn, path, &de.file)) {
  5456. mg_cry(conn,
  5457. "%s: mg_stat(%s) failed: %s",
  5458. __func__,
  5459. path,
  5460. strerror(ERRNO));
  5461. }
  5462. if (de.file.last_modified) {
  5463. /* TODO (high): This check does not seem to make any sense ! */
  5464. send_http_error(
  5465. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5466. return;
  5467. }
  5468. body_len = conn->data_len - conn->request_len;
  5469. if (body_len > 0) {
  5470. send_http_error(
  5471. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5472. return;
  5473. }
  5474. rc = mg_mkdir(path, 0755);
  5475. if (rc == 0) {
  5476. conn->status_code = 201;
  5477. gmt_time_string(date, sizeof(date), &curtime);
  5478. mg_printf(conn,
  5479. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  5480. "0\r\nConnection: %s\r\n\r\n",
  5481. conn->status_code,
  5482. date,
  5483. suggest_connection_header(conn));
  5484. } else if (rc == -1) {
  5485. if (errno == EEXIST) {
  5486. send_http_error(
  5487. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  5488. } else if (errno == EACCES) {
  5489. send_http_error(
  5490. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5491. } else if (errno == ENOENT) {
  5492. send_http_error(
  5493. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5494. } else {
  5495. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  5496. }
  5497. }
  5498. }
  5499. static void put_file(struct mg_connection *conn, const char *path)
  5500. {
  5501. struct file file = STRUCT_FILE_INITIALIZER;
  5502. const char *range;
  5503. int64_t r1, r2;
  5504. int rc;
  5505. char date[64];
  5506. time_t curtime = time(NULL);
  5507. if (conn == NULL) {
  5508. return;
  5509. }
  5510. if (mg_stat(conn, path, &file)) {
  5511. /* File already exists */
  5512. conn->status_code = 200;
  5513. if (file.is_directory) {
  5514. /* This is an already existing directory,
  5515. * so there is nothing to do for the server. */
  5516. rc = 0;
  5517. } else {
  5518. /* File exists and is not a directory. */
  5519. /* Can it be replaced? */
  5520. if (file.membuf != NULL) {
  5521. /* This is an "in-memory" file, that can not be replaced */
  5522. send_http_error(
  5523. conn,
  5524. 405,
  5525. "Error: Put not possible\nReplacing %s is not supported",
  5526. path);
  5527. return;
  5528. }
  5529. /* Check if the server may write this file */
  5530. if (access(path, W_OK) == 0) {
  5531. /* Access granted */
  5532. conn->status_code = 200;
  5533. rc = 1;
  5534. } else {
  5535. send_http_error(
  5536. conn,
  5537. 403,
  5538. "Error: Put not possible\nReplacing %s is not allowed",
  5539. path);
  5540. return;
  5541. }
  5542. }
  5543. } else {
  5544. /* File should be created */
  5545. conn->status_code = 201;
  5546. rc = put_dir(conn, path);
  5547. }
  5548. if (rc == 0) {
  5549. /* put_dir returns 0 if path is a directory */
  5550. gmt_time_string(date, sizeof(date), &curtime);
  5551. mg_printf(conn,
  5552. "HTTP/1.1 %d %s\r\n"
  5553. "Date: %s\r\n"
  5554. "Content-Length: 0\r\n"
  5555. "Connection: %s\r\n\r\n",
  5556. conn->status_code,
  5557. mg_get_response_code_text(conn->status_code, NULL),
  5558. date,
  5559. suggest_connection_header(conn));
  5560. /* Request to create a directory has been fulfilled successfully.
  5561. * No need to put a file. */
  5562. return;
  5563. }
  5564. if (rc == -1) {
  5565. /* put_dir returns -1 if the path is too long */
  5566. send_http_error(conn,
  5567. 414,
  5568. "Error: Path too long\nput_dir(%s): %s",
  5569. path,
  5570. strerror(ERRNO));
  5571. return;
  5572. }
  5573. if (rc == -2) {
  5574. /* put_dir returns -2 if the directory can not be created */
  5575. send_http_error(conn,
  5576. 500,
  5577. "Error: Can not create directory\nput_dir(%s): %s",
  5578. path,
  5579. strerror(ERRNO));
  5580. return;
  5581. }
  5582. /* A file should be created or overwritten. */
  5583. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  5584. mg_fclose(&file);
  5585. send_http_error(conn,
  5586. 500,
  5587. "Error: Can not create file\nfopen(%s): %s",
  5588. path,
  5589. strerror(ERRNO));
  5590. return;
  5591. }
  5592. fclose_on_exec(&file, conn);
  5593. range = mg_get_header(conn, "Content-Range");
  5594. r1 = r2 = 0;
  5595. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  5596. conn->status_code = 206; /* Partial content */
  5597. fseeko(file.fp, r1, SEEK_SET);
  5598. }
  5599. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  5600. /* forward_body_data failed.
  5601. * The error code has already been sent to the client,
  5602. * and conn->status_code is already set. */
  5603. return;
  5604. }
  5605. gmt_time_string(date, sizeof(date), &curtime);
  5606. mg_printf(conn,
  5607. "HTTP/1.1 %d %s\r\n"
  5608. "Date: %s\r\n"
  5609. "Content-Length: 0\r\n"
  5610. "Connection: %s\r\n\r\n",
  5611. conn->status_code,
  5612. mg_get_response_code_text(conn->status_code, NULL),
  5613. date,
  5614. suggest_connection_header(conn));
  5615. mg_fclose(&file);
  5616. }
  5617. static void delete_file(struct mg_connection *conn, const char *path)
  5618. {
  5619. struct de de;
  5620. memset(&de.file, 0, sizeof(de.file));
  5621. if (!mg_stat(conn, path, &de.file)) {
  5622. /* mg_stat returns 0 if the file does not exist */
  5623. send_http_error(
  5624. conn, 404, "Error: Cannot delete file\nFile %s not found", path);
  5625. return;
  5626. }
  5627. if (de.file.membuf != NULL) {
  5628. /* the file is cached in memory */
  5629. send_http_error(
  5630. conn,
  5631. 405,
  5632. "Error: Delete not possible\nDeleting %s is not supported",
  5633. path);
  5634. return;
  5635. }
  5636. if (de.file.is_directory) {
  5637. remove_directory(conn, path);
  5638. /* TODO (mid): remove_dir does not return success of the operation */
  5639. /* Assume delete is successful: Return 204 without content. */
  5640. send_http_error(conn, 204, "%s", "");
  5641. return;
  5642. }
  5643. /* This is an existing file (not a directory).
  5644. * Check if write permission is granted. */
  5645. if (access(path, W_OK) != 0) {
  5646. /* File is read only */
  5647. send_http_error(
  5648. conn,
  5649. 403,
  5650. "Error: Delete not possible\nDeleting %s is not allowed",
  5651. path);
  5652. return;
  5653. }
  5654. /* Try to delete it. */
  5655. if (mg_remove(path) == 0) {
  5656. /* Delete was successful: Return 204 without content. */
  5657. send_http_error(conn, 204, "%s", "");
  5658. } else {
  5659. /* Delete not successful (file locked). */
  5660. send_http_error(conn,
  5661. 423,
  5662. "Error: Cannot delete file\nremove(%s): %s",
  5663. path,
  5664. strerror(ERRNO));
  5665. }
  5666. }
  5667. static void
  5668. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  5669. static void do_ssi_include(struct mg_connection *conn,
  5670. const char *ssi,
  5671. char *tag,
  5672. int include_level)
  5673. {
  5674. char file_name[MG_BUF_LEN], path[512], *p;
  5675. struct file file = STRUCT_FILE_INITIALIZER;
  5676. size_t len;
  5677. if (conn == NULL) {
  5678. return;
  5679. }
  5680. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  5681. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  5682. * always < MG_BUF_LEN. */
  5683. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  5684. /* File name is relative to the webserver root */
  5685. file_name[511] = 0;
  5686. (void)mg_snprintf(conn,
  5687. path,
  5688. sizeof(path),
  5689. "%s%c%s",
  5690. conn->ctx->config[DOCUMENT_ROOT],
  5691. '/',
  5692. file_name);
  5693. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  5694. /* File name is relative to the webserver working directory
  5695. * or it is absolute system path */
  5696. file_name[511] = 0;
  5697. (void)mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  5698. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  5699. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  5700. /* File name is relative to the currect document */
  5701. file_name[511] = 0;
  5702. (void)mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  5703. if ((p = strrchr(path, '/')) != NULL) {
  5704. p[1] = '\0';
  5705. }
  5706. len = strlen(path);
  5707. (void)mg_snprintf(
  5708. conn, path + len, sizeof(path) - len, "%s", file_name);
  5709. } else {
  5710. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  5711. return;
  5712. }
  5713. if (!mg_fopen(conn, path, "rb", &file)) {
  5714. mg_cry(conn,
  5715. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  5716. tag,
  5717. path,
  5718. strerror(ERRNO));
  5719. } else {
  5720. fclose_on_exec(&file, conn);
  5721. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  5722. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  5723. path) > 0) {
  5724. send_ssi_file(conn, path, &file, include_level + 1);
  5725. } else {
  5726. send_file_data(conn, &file, 0, INT64_MAX);
  5727. }
  5728. mg_fclose(&file);
  5729. }
  5730. }
  5731. #if !defined(NO_POPEN)
  5732. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  5733. {
  5734. char cmd[1024] = "";
  5735. struct file file = STRUCT_FILE_INITIALIZER;
  5736. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  5737. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  5738. } else {
  5739. cmd[1023] = 0;
  5740. if ((file.fp = popen(cmd, "r")) == NULL) {
  5741. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  5742. } else {
  5743. send_file_data(conn, &file, 0, INT64_MAX);
  5744. pclose(file.fp);
  5745. }
  5746. }
  5747. }
  5748. #endif /* !NO_POPEN */
  5749. static int mg_fgetc(struct file *filep, int offset)
  5750. {
  5751. if (filep == NULL) {
  5752. return EOF;
  5753. }
  5754. if (filep->membuf != NULL && offset >= 0 &&
  5755. ((unsigned int)(offset)) < filep->size) {
  5756. return ((unsigned char *)filep->membuf)[offset];
  5757. } else if (filep->fp != NULL) {
  5758. return fgetc(filep->fp);
  5759. } else {
  5760. return EOF;
  5761. }
  5762. }
  5763. static void send_ssi_file(struct mg_connection *conn,
  5764. const char *path,
  5765. struct file *filep,
  5766. int include_level)
  5767. {
  5768. char buf[MG_BUF_LEN];
  5769. int ch, offset, len, in_ssi_tag;
  5770. if (include_level > 10) {
  5771. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  5772. return;
  5773. }
  5774. in_ssi_tag = len = offset = 0;
  5775. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  5776. if (in_ssi_tag && ch == '>') {
  5777. in_ssi_tag = 0;
  5778. buf[len++] = (char)ch;
  5779. buf[len] = '\0';
  5780. /* assert(len <= (int) sizeof(buf)); */
  5781. if (len > (int)sizeof(buf)) {
  5782. break;
  5783. }
  5784. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  5785. /* Not an SSI tag, pass it */
  5786. (void)mg_write(conn, buf, (size_t)len);
  5787. } else {
  5788. if (!memcmp(buf + 5, "include", 7)) {
  5789. do_ssi_include(conn, path, buf + 12, include_level);
  5790. #if !defined(NO_POPEN)
  5791. } else if (!memcmp(buf + 5, "exec", 4)) {
  5792. do_ssi_exec(conn, buf + 9);
  5793. #endif /* !NO_POPEN */
  5794. } else {
  5795. mg_cry(conn,
  5796. "%s: unknown SSI "
  5797. "command: \"%s\"",
  5798. path,
  5799. buf);
  5800. }
  5801. }
  5802. len = 0;
  5803. } else if (in_ssi_tag) {
  5804. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  5805. /* Not an SSI tag */
  5806. in_ssi_tag = 0;
  5807. } else if (len == (int)sizeof(buf) - 2) {
  5808. mg_cry(conn, "%s: SSI tag is too large", path);
  5809. len = 0;
  5810. }
  5811. buf[len++] = (char)(ch & 0xff);
  5812. } else if (ch == '<') {
  5813. in_ssi_tag = 1;
  5814. if (len > 0) {
  5815. mg_write(conn, buf, (size_t)len);
  5816. }
  5817. len = 0;
  5818. buf[len++] = (char)(ch & 0xff);
  5819. } else {
  5820. buf[len++] = (char)(ch & 0xff);
  5821. if (len == (int)sizeof(buf)) {
  5822. mg_write(conn, buf, (size_t)len);
  5823. len = 0;
  5824. }
  5825. }
  5826. }
  5827. /* Send the rest of buffered data */
  5828. if (len > 0) {
  5829. mg_write(conn, buf, (size_t)len);
  5830. }
  5831. }
  5832. static void handle_ssi_file_request(struct mg_connection *conn,
  5833. const char *path,
  5834. struct file *filep)
  5835. {
  5836. char date[64];
  5837. time_t curtime = time(NULL);
  5838. const char *cors1, *cors2, *cors3;
  5839. if (conn == NULL || path == NULL || filep == NULL) {
  5840. return;
  5841. }
  5842. if (mg_get_header(conn, "Origin")) {
  5843. /* Cross-origin resource sharing (CORS). */
  5844. cors1 = "Access-Control-Allow-Origin: ";
  5845. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5846. cors3 = "\r\n";
  5847. } else {
  5848. cors1 = cors2 = cors3 = "";
  5849. }
  5850. if (!mg_fopen(conn, path, "rb", filep)) {
  5851. /* File exists (precondition for calling this function),
  5852. * but can not be opened by the server. */
  5853. send_http_error(conn,
  5854. 500,
  5855. "Error: Cannot read file\nfopen(%s): %s",
  5856. path,
  5857. strerror(ERRNO));
  5858. } else {
  5859. conn->must_close = 1;
  5860. gmt_time_string(date, sizeof(date), &curtime);
  5861. fclose_on_exec(filep, conn);
  5862. mg_printf(conn,
  5863. "HTTP/1.1 200 OK\r\n"
  5864. "%s%s%s"
  5865. "Date: %s\r\n"
  5866. "Content-Type: text/html\r\n"
  5867. "Connection: %s\r\n\r\n",
  5868. cors1,
  5869. cors2,
  5870. cors3,
  5871. date,
  5872. suggest_connection_header(conn));
  5873. send_ssi_file(conn, path, filep, 0);
  5874. mg_fclose(filep);
  5875. }
  5876. }
  5877. static void send_options(struct mg_connection *conn)
  5878. {
  5879. char date[64];
  5880. time_t curtime = time(NULL);
  5881. if (!conn) {
  5882. return;
  5883. }
  5884. conn->status_code = 200;
  5885. conn->must_close = 1;
  5886. gmt_time_string(date, sizeof(date), &curtime);
  5887. mg_printf(conn,
  5888. "HTTP/1.1 200 OK\r\n"
  5889. "Date: %s\r\n"
  5890. "Connection: %s\r\n"
  5891. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  5892. "PROPFIND, MKCOL\r\n"
  5893. "DAV: 1\r\n\r\n",
  5894. date,
  5895. suggest_connection_header(conn));
  5896. }
  5897. /* Writes PROPFIND properties for a collection element */
  5898. static void
  5899. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  5900. {
  5901. char mtime[64];
  5902. if (conn == NULL || uri == NULL || filep == NULL) {
  5903. return;
  5904. }
  5905. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  5906. conn->num_bytes_sent +=
  5907. mg_printf(conn,
  5908. "<d:response>"
  5909. "<d:href>%s</d:href>"
  5910. "<d:propstat>"
  5911. "<d:prop>"
  5912. "<d:resourcetype>%s</d:resourcetype>"
  5913. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  5914. "<d:getlastmodified>%s</d:getlastmodified>"
  5915. "</d:prop>"
  5916. "<d:status>HTTP/1.1 200 OK</d:status>"
  5917. "</d:propstat>"
  5918. "</d:response>\n",
  5919. uri,
  5920. filep->is_directory ? "<d:collection/>" : "",
  5921. filep->size,
  5922. mtime);
  5923. }
  5924. static void print_dav_dir_entry(struct de *de, void *data)
  5925. {
  5926. char href[PATH_MAX];
  5927. char href_encoded[PATH_MAX];
  5928. struct mg_connection *conn = (struct mg_connection *)data;
  5929. if (!de || !conn) {
  5930. return;
  5931. }
  5932. mg_snprintf(conn,
  5933. href,
  5934. sizeof(href),
  5935. "%s%s",
  5936. conn->request_info.uri,
  5937. de->file_name);
  5938. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  5939. print_props(conn, href_encoded, &de->file);
  5940. }
  5941. static void handle_propfind(struct mg_connection *conn,
  5942. const char *path,
  5943. struct file *filep)
  5944. {
  5945. const char *depth = mg_get_header(conn, "Depth");
  5946. char date[64];
  5947. time_t curtime = time(NULL);
  5948. gmt_time_string(date, sizeof(date), &curtime);
  5949. if (!conn || !path || !filep) {
  5950. return;
  5951. }
  5952. conn->must_close = 1;
  5953. conn->status_code = 207;
  5954. mg_printf(conn,
  5955. "HTTP/1.1 207 Multi-Status\r\n"
  5956. "Date: %s\r\n"
  5957. "Connection: %s\r\n"
  5958. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  5959. date,
  5960. suggest_connection_header(conn));
  5961. conn->num_bytes_sent +=
  5962. mg_printf(conn,
  5963. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  5964. "<d:multistatus xmlns:d='DAV:'>\n");
  5965. /* Print properties for the requested resource itself */
  5966. print_props(conn, conn->request_info.uri, filep);
  5967. /* If it is a directory, print directory entries too if Depth is not 0 */
  5968. if (filep && conn->ctx && filep->is_directory &&
  5969. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  5970. (depth == NULL || strcmp(depth, "0") != 0)) {
  5971. scan_directory(conn, path, conn, &print_dav_dir_entry);
  5972. }
  5973. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  5974. }
  5975. void mg_lock_connection(struct mg_connection *conn)
  5976. {
  5977. if (conn) {
  5978. (void)pthread_mutex_lock(&conn->mutex);
  5979. }
  5980. }
  5981. void mg_unlock_connection(struct mg_connection *conn)
  5982. {
  5983. if (conn) {
  5984. (void)pthread_mutex_unlock(&conn->mutex);
  5985. }
  5986. }
  5987. void mg_lock_context(struct mg_context *ctx)
  5988. {
  5989. if (ctx) {
  5990. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  5991. }
  5992. }
  5993. void mg_unlock_context(struct mg_context *ctx)
  5994. {
  5995. if (ctx) {
  5996. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  5997. }
  5998. }
  5999. #if defined(USE_TIMERS)
  6000. #include "timer.inl"
  6001. #endif /* USE_TIMERS */
  6002. #ifdef USE_LUA
  6003. #include "mod_lua.inl"
  6004. #endif /* USE_LUA */
  6005. #if defined(USE_WEBSOCKET)
  6006. /* START OF SHA-1 code
  6007. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6008. #define SHA1HANDSOFF
  6009. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6010. *
  6011. * #if defined(__sun)
  6012. * #include "solarisfixes.h"
  6013. * #endif
  6014. */
  6015. static int is_big_endian(void)
  6016. {
  6017. static const int n = 1;
  6018. return ((char *)&n)[0] == 0;
  6019. }
  6020. union char64long16 {
  6021. unsigned char c[64];
  6022. uint32_t l[16];
  6023. };
  6024. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6025. static uint32_t blk0(union char64long16 *block, int i)
  6026. {
  6027. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6028. if (!is_big_endian()) {
  6029. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6030. (rol(block->l[i], 8) & 0x00FF00FF);
  6031. }
  6032. return block->l[i];
  6033. }
  6034. #define blk(i) \
  6035. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6036. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6037. 1))
  6038. #define R0(v, w, x, y, z, i) \
  6039. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6040. w = rol(w, 30);
  6041. #define R1(v, w, x, y, z, i) \
  6042. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6043. w = rol(w, 30);
  6044. #define R2(v, w, x, y, z, i) \
  6045. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6046. w = rol(w, 30);
  6047. #define R3(v, w, x, y, z, i) \
  6048. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6049. w = rol(w, 30);
  6050. #define R4(v, w, x, y, z, i) \
  6051. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6052. w = rol(w, 30);
  6053. typedef struct {
  6054. uint32_t state[5];
  6055. uint32_t count[2];
  6056. unsigned char buffer[64];
  6057. } SHA1_CTX;
  6058. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6059. {
  6060. uint32_t a, b, c, d, e;
  6061. union char64long16 block[1];
  6062. memcpy(block, buffer, 64);
  6063. a = state[0];
  6064. b = state[1];
  6065. c = state[2];
  6066. d = state[3];
  6067. e = state[4];
  6068. R0(a, b, c, d, e, 0);
  6069. R0(e, a, b, c, d, 1);
  6070. R0(d, e, a, b, c, 2);
  6071. R0(c, d, e, a, b, 3);
  6072. R0(b, c, d, e, a, 4);
  6073. R0(a, b, c, d, e, 5);
  6074. R0(e, a, b, c, d, 6);
  6075. R0(d, e, a, b, c, 7);
  6076. R0(c, d, e, a, b, 8);
  6077. R0(b, c, d, e, a, 9);
  6078. R0(a, b, c, d, e, 10);
  6079. R0(e, a, b, c, d, 11);
  6080. R0(d, e, a, b, c, 12);
  6081. R0(c, d, e, a, b, 13);
  6082. R0(b, c, d, e, a, 14);
  6083. R0(a, b, c, d, e, 15);
  6084. R1(e, a, b, c, d, 16);
  6085. R1(d, e, a, b, c, 17);
  6086. R1(c, d, e, a, b, 18);
  6087. R1(b, c, d, e, a, 19);
  6088. R2(a, b, c, d, e, 20);
  6089. R2(e, a, b, c, d, 21);
  6090. R2(d, e, a, b, c, 22);
  6091. R2(c, d, e, a, b, 23);
  6092. R2(b, c, d, e, a, 24);
  6093. R2(a, b, c, d, e, 25);
  6094. R2(e, a, b, c, d, 26);
  6095. R2(d, e, a, b, c, 27);
  6096. R2(c, d, e, a, b, 28);
  6097. R2(b, c, d, e, a, 29);
  6098. R2(a, b, c, d, e, 30);
  6099. R2(e, a, b, c, d, 31);
  6100. R2(d, e, a, b, c, 32);
  6101. R2(c, d, e, a, b, 33);
  6102. R2(b, c, d, e, a, 34);
  6103. R2(a, b, c, d, e, 35);
  6104. R2(e, a, b, c, d, 36);
  6105. R2(d, e, a, b, c, 37);
  6106. R2(c, d, e, a, b, 38);
  6107. R2(b, c, d, e, a, 39);
  6108. R3(a, b, c, d, e, 40);
  6109. R3(e, a, b, c, d, 41);
  6110. R3(d, e, a, b, c, 42);
  6111. R3(c, d, e, a, b, 43);
  6112. R3(b, c, d, e, a, 44);
  6113. R3(a, b, c, d, e, 45);
  6114. R3(e, a, b, c, d, 46);
  6115. R3(d, e, a, b, c, 47);
  6116. R3(c, d, e, a, b, 48);
  6117. R3(b, c, d, e, a, 49);
  6118. R3(a, b, c, d, e, 50);
  6119. R3(e, a, b, c, d, 51);
  6120. R3(d, e, a, b, c, 52);
  6121. R3(c, d, e, a, b, 53);
  6122. R3(b, c, d, e, a, 54);
  6123. R3(a, b, c, d, e, 55);
  6124. R3(e, a, b, c, d, 56);
  6125. R3(d, e, a, b, c, 57);
  6126. R3(c, d, e, a, b, 58);
  6127. R3(b, c, d, e, a, 59);
  6128. R4(a, b, c, d, e, 60);
  6129. R4(e, a, b, c, d, 61);
  6130. R4(d, e, a, b, c, 62);
  6131. R4(c, d, e, a, b, 63);
  6132. R4(b, c, d, e, a, 64);
  6133. R4(a, b, c, d, e, 65);
  6134. R4(e, a, b, c, d, 66);
  6135. R4(d, e, a, b, c, 67);
  6136. R4(c, d, e, a, b, 68);
  6137. R4(b, c, d, e, a, 69);
  6138. R4(a, b, c, d, e, 70);
  6139. R4(e, a, b, c, d, 71);
  6140. R4(d, e, a, b, c, 72);
  6141. R4(c, d, e, a, b, 73);
  6142. R4(b, c, d, e, a, 74);
  6143. R4(a, b, c, d, e, 75);
  6144. R4(e, a, b, c, d, 76);
  6145. R4(d, e, a, b, c, 77);
  6146. R4(c, d, e, a, b, 78);
  6147. R4(b, c, d, e, a, 79);
  6148. state[0] += a;
  6149. state[1] += b;
  6150. state[2] += c;
  6151. state[3] += d;
  6152. state[4] += e;
  6153. a = b = c = d = e = 0;
  6154. memset(block, '\0', sizeof(block));
  6155. }
  6156. static void SHA1Init(SHA1_CTX *context)
  6157. {
  6158. context->state[0] = 0x67452301;
  6159. context->state[1] = 0xEFCDAB89;
  6160. context->state[2] = 0x98BADCFE;
  6161. context->state[3] = 0x10325476;
  6162. context->state[4] = 0xC3D2E1F0;
  6163. context->count[0] = context->count[1] = 0;
  6164. }
  6165. static void
  6166. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6167. {
  6168. uint32_t i, j;
  6169. j = context->count[0];
  6170. if ((context->count[0] += len << 3) < j) {
  6171. context->count[1]++;
  6172. }
  6173. context->count[1] += (len >> 29);
  6174. j = (j >> 3) & 63;
  6175. if ((j + len) > 63) {
  6176. memcpy(&context->buffer[j], data, (i = 64 - j));
  6177. SHA1Transform(context->state, context->buffer);
  6178. for (; i + 63 < len; i += 64) {
  6179. SHA1Transform(context->state, &data[i]);
  6180. }
  6181. j = 0;
  6182. } else
  6183. i = 0;
  6184. memcpy(&context->buffer[j], &data[i], len - i);
  6185. }
  6186. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6187. {
  6188. unsigned i;
  6189. unsigned char finalcount[8], c;
  6190. for (i = 0; i < 8; i++) {
  6191. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  6192. ((3 - (i & 3)) * 8)) &
  6193. 255);
  6194. }
  6195. c = 0200;
  6196. SHA1Update(context, &c, 1);
  6197. while ((context->count[0] & 504) != 448) {
  6198. c = 0000;
  6199. SHA1Update(context, &c, 1);
  6200. }
  6201. SHA1Update(context, finalcount, 8);
  6202. for (i = 0; i < 20; i++) {
  6203. digest[i] =
  6204. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  6205. 255);
  6206. }
  6207. memset(context, '\0', sizeof(*context));
  6208. memset(&finalcount, '\0', sizeof(finalcount));
  6209. }
  6210. /* END OF SHA1 CODE */
  6211. static void send_websocket_handshake(struct mg_connection *conn)
  6212. {
  6213. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  6214. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  6215. SHA1_CTX sha_ctx;
  6216. mg_snprintf(conn,
  6217. buf,
  6218. sizeof(buf),
  6219. "%s%s",
  6220. mg_get_header(conn, "Sec-WebSocket-Key"),
  6221. magic);
  6222. SHA1Init(&sha_ctx);
  6223. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  6224. SHA1Final((unsigned char *)sha, &sha_ctx);
  6225. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  6226. mg_printf(conn,
  6227. "%s%s%s",
  6228. "HTTP/1.1 101 Switching Protocols\r\n"
  6229. "Upgrade: websocket\r\n"
  6230. "Connection: Upgrade\r\n"
  6231. "Sec-WebSocket-Accept: ",
  6232. b64_sha,
  6233. "\r\n\r\n");
  6234. }
  6235. static void read_websocket(struct mg_connection *conn,
  6236. mg_websocket_data_handler ws_data_handler,
  6237. void *callback_data)
  6238. {
  6239. /* Pointer to the beginning of the portion of the incoming websocket
  6240. * message queue.
  6241. * The original websocket upgrade request is never removed, so the queue
  6242. * begins after it. */
  6243. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  6244. int n, error, exit_by_callback;
  6245. /* body_len is the length of the entire queue in bytes
  6246. * len is the length of the current message
  6247. * data_len is the length of the current message's data payload
  6248. * header_len is the length of the current message's header */
  6249. size_t i, len, mask_len, data_len, header_len, body_len;
  6250. /* "The masking key is a 32-bit value chosen at random by the client."
  6251. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  6252. */
  6253. unsigned char mask[4];
  6254. /* data points to the place where the message is stored when passed to the
  6255. * websocket_data callback. This is either mem on the stack, or a
  6256. * dynamically allocated buffer if it is too large. */
  6257. char mem[4096];
  6258. char *data = mem;
  6259. unsigned char mop; /* mask flag and opcode */
  6260. double timeout = -1.0;
  6261. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  6262. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  6263. }
  6264. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  6265. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6266. }
  6267. mg_set_thread_name("wsock");
  6268. /* Loop continuously, reading messages from the socket, invoking the
  6269. * callback, and waiting repeatedly until an error occurs. */
  6270. while (!conn->ctx->stop_flag) {
  6271. header_len = 0;
  6272. assert(conn->data_len >= conn->request_len);
  6273. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  6274. len = buf[1] & 127;
  6275. mask_len = buf[1] & 128 ? 4 : 0;
  6276. if (len < 126 && body_len >= mask_len) {
  6277. data_len = len;
  6278. header_len = 2 + mask_len;
  6279. } else if (len == 126 && body_len >= 4 + mask_len) {
  6280. header_len = 4 + mask_len;
  6281. data_len = ((((int)buf[2]) << 8) + buf[3]);
  6282. } else if (body_len >= 10 + mask_len) {
  6283. header_len = 10 + mask_len;
  6284. data_len = (((uint64_t)ntohl(*(uint32_t *)&buf[2])) << 32) +
  6285. ntohl(*(uint32_t *)&buf[6]);
  6286. }
  6287. }
  6288. if (header_len > 0 && body_len >= header_len) {
  6289. /* Allocate space to hold websocket payload */
  6290. data = mem;
  6291. if (data_len > sizeof(mem)) {
  6292. data = (char *)mg_malloc(data_len);
  6293. if (data == NULL) {
  6294. /* Allocation failed, exit the loop and then close the
  6295. * connection */
  6296. mg_cry(conn, "websocket out of memory; closing connection");
  6297. break;
  6298. }
  6299. }
  6300. /* Copy the mask before we shift the queue and destroy it */
  6301. if (mask_len > 0) {
  6302. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  6303. } else {
  6304. memset(mask, 0, sizeof(mask));
  6305. }
  6306. /* Read frame payload from the first message in the queue into
  6307. * data and advance the queue by moving the memory in place. */
  6308. assert(body_len >= header_len);
  6309. if (data_len + header_len > body_len) {
  6310. mop = buf[0]; /* current mask and opcode */
  6311. /* Overflow case */
  6312. len = body_len - header_len;
  6313. memcpy(data, buf + header_len, len);
  6314. error = 0;
  6315. while (len < data_len) {
  6316. n = pull(
  6317. NULL, conn, data + len, (int)(data_len - len), timeout);
  6318. if (n <= 0) {
  6319. error = 1;
  6320. break;
  6321. }
  6322. len += n;
  6323. }
  6324. if (error) {
  6325. mg_cry(conn, "Websocket pull failed; closing connection");
  6326. break;
  6327. }
  6328. conn->data_len = conn->request_len;
  6329. } else {
  6330. mop = buf[0]; /* current mask and opcode, overwritten by
  6331. * memmove() */
  6332. /* Length of the message being read at the front of the
  6333. * queue */
  6334. len = data_len + header_len;
  6335. /* Copy the data payload into the data pointer for the
  6336. * callback */
  6337. memcpy(data, buf + header_len, data_len);
  6338. /* Move the queue forward len bytes */
  6339. memmove(buf, buf + len, body_len - len);
  6340. /* Mark the queue as advanced */
  6341. conn->data_len -= (int)len;
  6342. }
  6343. /* Apply mask if necessary */
  6344. if (mask_len > 0) {
  6345. for (i = 0; i < data_len; ++i) {
  6346. data[i] ^= mask[i & 3];
  6347. }
  6348. }
  6349. /* Exit the loop if callback signals to exit (server side),
  6350. * or "connection close" opcode received (client side). */
  6351. exit_by_callback = 0;
  6352. if ((ws_data_handler != NULL) &&
  6353. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  6354. exit_by_callback = 1;
  6355. }
  6356. if (data != mem) {
  6357. mg_free(data);
  6358. }
  6359. if (exit_by_callback ||
  6360. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  6361. /* Opcode == 8, connection close */
  6362. break;
  6363. }
  6364. /* Not breaking the loop, process next websocket frame. */
  6365. } else {
  6366. /* Read from the socket into the next available location in the
  6367. * message queue. */
  6368. if ((n = pull(NULL,
  6369. conn,
  6370. conn->buf + conn->data_len,
  6371. conn->buf_size - conn->data_len,
  6372. timeout)) <= 0) {
  6373. /* Error, no bytes read */
  6374. break;
  6375. }
  6376. conn->data_len += n;
  6377. }
  6378. }
  6379. mg_set_thread_name("worker");
  6380. }
  6381. int mg_websocket_write(struct mg_connection *conn,
  6382. int opcode,
  6383. const char *data,
  6384. size_t dataLen)
  6385. {
  6386. unsigned char header[10];
  6387. size_t headerLen = 1;
  6388. int retval = -1;
  6389. header[0] = 0x80 + (opcode & 0xF);
  6390. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  6391. if (dataLen < 126) {
  6392. /* inline 7-bit length field */
  6393. header[1] = (unsigned char)dataLen;
  6394. headerLen = 2;
  6395. } else if (dataLen <= 0xFFFF) {
  6396. /* 16-bit length field */
  6397. header[1] = 126;
  6398. *(uint16_t *)(header + 2) = htons((uint16_t)dataLen);
  6399. headerLen = 4;
  6400. } else {
  6401. /* 64-bit length field */
  6402. header[1] = 127;
  6403. *(uint32_t *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  6404. *(uint32_t *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  6405. headerLen = 10;
  6406. }
  6407. /* Note that POSIX/Winsock's send() is threadsafe
  6408. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  6409. * but mongoose's mg_printf/mg_write is not (because of the loop in
  6410. * push(), although that is only a problem if the packet is large or
  6411. * outgoing buffer is full). */
  6412. (void)mg_lock_connection(conn);
  6413. retval = mg_write(conn, header, headerLen);
  6414. retval = mg_write(conn, data, dataLen);
  6415. mg_unlock_connection(conn);
  6416. return retval;
  6417. }
  6418. static void
  6419. handle_websocket_request(struct mg_connection *conn,
  6420. const char *path,
  6421. int is_callback_resource,
  6422. mg_websocket_connect_handler ws_connect_handler,
  6423. mg_websocket_ready_handler ws_ready_handler,
  6424. mg_websocket_data_handler ws_data_handler,
  6425. mg_websocket_close_handler ws_close_handler,
  6426. void *cbData)
  6427. {
  6428. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  6429. int lua_websock = 0;
  6430. #if !defined(USE_LUA)
  6431. (void)path;
  6432. #endif
  6433. /* Step 1: Check websocket protocol version. */
  6434. if (version == NULL || strcmp(version, "13") != 0) {
  6435. /* Reject wrong versions */
  6436. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  6437. return;
  6438. }
  6439. /* Step 2: If a callback is responsible, call it. */
  6440. if (is_callback_resource) {
  6441. if (ws_connect_handler != NULL &&
  6442. ws_connect_handler(conn, cbData) != 0) {
  6443. /* C callback has returned non-zero, do not proceed with handshake.
  6444. */
  6445. /* Note that C callbacks are no longer called when Lua is
  6446. * responsible, so C can no longer filter callbacks for Lua. */
  6447. return;
  6448. }
  6449. }
  6450. #if defined(USE_LUA)
  6451. /* Step 3: No callback. Check if Lua is responsible. */
  6452. else {
  6453. /* Step 3.1: Check if Lua is responsible. */
  6454. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  6455. lua_websock = match_prefix(
  6456. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  6457. strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  6458. path);
  6459. }
  6460. if (lua_websock) {
  6461. /* Step 3.2: Lua is responsible: call it. */
  6462. conn->lua_websocket_state = lua_websocket_new(path, conn);
  6463. if (!conn->lua_websocket_state) {
  6464. /* Lua rejected the new client */
  6465. return;
  6466. }
  6467. }
  6468. }
  6469. #endif
  6470. /* Step 4: Check if there is a responsible websocket handler. */
  6471. if (!is_callback_resource && !lua_websock) {
  6472. /* There is no callback, an Lua is not responsible either. */
  6473. /* Reply with a 404 Not Found or with nothing at all?
  6474. * TODO (mid): check the websocket standards, how to reply to
  6475. * requests to invalid websocket addresses. */
  6476. send_http_error(conn, 404, "%s", "Not found");
  6477. return;
  6478. }
  6479. /* Step 5: The websocket connection has been accepted */
  6480. send_websocket_handshake(conn);
  6481. /* Step 6: Call the ready handler */
  6482. if (is_callback_resource) {
  6483. if (ws_ready_handler != NULL) {
  6484. ws_ready_handler(conn, cbData);
  6485. }
  6486. #if defined(USE_LUA)
  6487. } else if (lua_websock) {
  6488. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  6489. /* the ready handler returned false */
  6490. return;
  6491. }
  6492. #endif
  6493. }
  6494. /* Step 7: Enter the read loop */
  6495. if (is_callback_resource) {
  6496. read_websocket(conn, ws_data_handler, cbData);
  6497. #if defined(USE_LUA)
  6498. } else if (lua_websock) {
  6499. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  6500. #endif
  6501. }
  6502. /* Step 8: Call the close handler */
  6503. if (ws_close_handler) {
  6504. ws_close_handler(conn, cbData);
  6505. }
  6506. }
  6507. static int is_websocket_protocol(const struct mg_connection *conn)
  6508. {
  6509. const char *host, *upgrade, *connection, *version, *key;
  6510. upgrade = mg_get_header(conn, "Upgrade");
  6511. if (upgrade == NULL) {
  6512. return 0; /* fail early, don't waste time checking other header fields
  6513. */
  6514. }
  6515. if (!mg_strcasestr(upgrade, "websocket")) {
  6516. return 0;
  6517. }
  6518. connection = mg_get_header(conn, "Connection");
  6519. if (connection == NULL) {
  6520. return 0;
  6521. }
  6522. if (!mg_strcasestr(connection, "upgrade")) {
  6523. return 0;
  6524. }
  6525. host = mg_get_header(conn, "Host");
  6526. key = mg_get_header(conn, "Sec-WebSocket-Key");
  6527. version = mg_get_header(conn, "Sec-WebSocket-Version");
  6528. return (host != NULL && key != NULL && version != NULL);
  6529. }
  6530. #endif /* !USE_WEBSOCKET */
  6531. static int isbyte(int n) { return n >= 0 && n <= 255; }
  6532. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  6533. {
  6534. int n, a, b, c, d, slash = 32, len = 0;
  6535. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  6536. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  6537. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  6538. slash < 33) {
  6539. len = n;
  6540. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) |
  6541. (uint32_t)d;
  6542. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  6543. }
  6544. return len;
  6545. }
  6546. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  6547. {
  6548. int throttle = 0;
  6549. struct vec vec, val;
  6550. uint32_t net, mask;
  6551. char mult;
  6552. double v;
  6553. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  6554. mult = ',';
  6555. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  6556. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  6557. mult != ',')) {
  6558. continue;
  6559. }
  6560. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  6561. : 1;
  6562. if (vec.len == 1 && vec.ptr[0] == '*') {
  6563. throttle = (int)v;
  6564. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  6565. if ((remote_ip & mask) == net) {
  6566. throttle = (int)v;
  6567. }
  6568. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  6569. throttle = (int)v;
  6570. }
  6571. }
  6572. return throttle;
  6573. }
  6574. static uint32_t get_remote_ip(const struct mg_connection *conn)
  6575. {
  6576. if (!conn) {
  6577. return 0;
  6578. }
  6579. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  6580. }
  6581. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  6582. {
  6583. /* TODO (mid): set a timeout */
  6584. const char *content_type_header, *boundary_start, *sc;
  6585. char *s;
  6586. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX], fname[1024],
  6587. boundary[100];
  6588. FILE *fp;
  6589. int bl, n, i, headers_len, boundary_len, eof, len = 0,
  6590. num_uploaded_files = 0;
  6591. struct mg_request_info part_request_info;
  6592. /* Request looks like this:
  6593. *
  6594. * POST /upload HTTP/1.1
  6595. * Host: 127.0.0.1:8080
  6596. * Content-Length: 244894
  6597. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  6598. *
  6599. * ------WebKitFormBoundaryRVr
  6600. * Content-Disposition: form-data; name="file"; filename="accum.png"
  6601. * Content-Type: image/png
  6602. *
  6603. * <89>PNG
  6604. * <PNG DATA>
  6605. * ------WebKitFormBoundaryRVr */
  6606. /* Extract boundary string from the Content-Type header */
  6607. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  6608. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  6609. NULL ||
  6610. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  6611. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  6612. boundary[0] == '\0') {
  6613. return num_uploaded_files;
  6614. }
  6615. boundary[99] = 0;
  6616. boundary_len = (int)strlen(boundary);
  6617. bl = boundary_len + 4; /* \r\n--<boundary> */
  6618. for (;;) {
  6619. /* Pull in headers */
  6620. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  6621. if (len < 0 || len > (int)sizeof(buf)) {
  6622. break;
  6623. }
  6624. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  6625. len += n;
  6626. /* assert(len <= (int) sizeof(buf)); */
  6627. if (len > (int)sizeof(buf)) {
  6628. break;
  6629. }
  6630. }
  6631. if ((headers_len = get_request_len(buf, len)) <= 0) {
  6632. break;
  6633. }
  6634. /* terminate header */
  6635. buf[headers_len - 1] = 0;
  6636. /* Scan for the boundary string and skip it */
  6637. if (buf[0] == '-' && buf[1] == '-' &&
  6638. !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  6639. s = &buf[bl];
  6640. } else {
  6641. s = &buf[2];
  6642. }
  6643. /* Get headers for this part of the multipart message */
  6644. memset(&part_request_info, 0, sizeof(part_request_info));
  6645. parse_http_headers(&s, &part_request_info);
  6646. /* assert(&buf[headers_len-1] == s); */
  6647. if (&buf[headers_len - 1] != s) {
  6648. break;
  6649. }
  6650. /* Fetch file name. */
  6651. sc = get_header(&part_request_info, "Content-Disposition");
  6652. if (!sc) {
  6653. /* invalid part of a multipart message */
  6654. break;
  6655. }
  6656. sc = strstr(sc, "filename");
  6657. if (!sc) {
  6658. /* no filename set */
  6659. break;
  6660. }
  6661. sc += 8; /* skip "filename" */
  6662. fname[0] = '\0';
  6663. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  6664. fname[1023] = 0;
  6665. /* Give up if the headers are not what we expect */
  6666. if (fname[0] == '\0') {
  6667. break;
  6668. }
  6669. /* Construct destination file name. Do not allow paths to have
  6670. * slashes. */
  6671. if ((s = strrchr(fname, '/')) == NULL &&
  6672. (s = strrchr(fname, '\\')) == NULL) {
  6673. s = fname;
  6674. } else {
  6675. s++;
  6676. }
  6677. /* There data is written to a temporary file first. */
  6678. /* Different users should use a different destination_dir. */
  6679. snprintf(path, sizeof(path) - 1, "%s/%s", destination_dir, s);
  6680. strcpy(tmp_path, path);
  6681. strcat(tmp_path, "~");
  6682. /* We open the file with exclusive lock held. This guarantee us
  6683. * there is no other thread can save into the same file
  6684. * simultaneously. */
  6685. fp = NULL;
  6686. /* Open file in binary mode. */
  6687. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  6688. break;
  6689. }
  6690. /* Move data to the beginning of the buffer */
  6691. /* part_request_info is no longer valid after this operation */
  6692. /* assert(len >= headers_len); */
  6693. if (len < headers_len) {
  6694. break;
  6695. }
  6696. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  6697. len -= headers_len;
  6698. /* Read POST data, write into file until boundary is found. */
  6699. eof = n = 0;
  6700. do {
  6701. len += n;
  6702. for (i = 0; i < len - bl; i++) {
  6703. if (!memcmp(&buf[i], "\r\n--", 4) &&
  6704. !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  6705. /* Found boundary, that's the end of file data. */
  6706. fwrite(buf, 1, (size_t)i, fp);
  6707. eof = 1;
  6708. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  6709. len -= i + bl;
  6710. break;
  6711. }
  6712. }
  6713. if (!eof && len > bl) {
  6714. fwrite(buf, 1, (size_t)(len - bl), fp);
  6715. memmove(buf, &buf[len - bl], (size_t)bl);
  6716. len = bl;
  6717. }
  6718. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  6719. } while (!eof && (n > 0));
  6720. fclose(fp);
  6721. if (eof) {
  6722. remove(path);
  6723. rename(tmp_path, path);
  6724. num_uploaded_files++;
  6725. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  6726. conn->ctx->callbacks.upload(conn, path);
  6727. }
  6728. } else {
  6729. remove(tmp_path);
  6730. }
  6731. }
  6732. return num_uploaded_files;
  6733. }
  6734. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  6735. {
  6736. unsigned int i;
  6737. int idx = -1;
  6738. if (ctx) {
  6739. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  6740. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  6741. }
  6742. }
  6743. return idx;
  6744. }
  6745. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  6746. {
  6747. char host[1025];
  6748. const char *host_header;
  6749. size_t hostlen;
  6750. host_header = mg_get_header(conn, "Host");
  6751. hostlen = sizeof(host);
  6752. if (host_header != NULL) {
  6753. char *pos;
  6754. mg_strlcpy(host, host_header, hostlen);
  6755. host[hostlen - 1] = '\0';
  6756. pos = strchr(host, ':');
  6757. if (pos != NULL) {
  6758. *pos = '\0';
  6759. }
  6760. } else {
  6761. /* Cannot get host from the Host: header.
  6762. * Fallback to our IP address. */
  6763. if (conn) {
  6764. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  6765. }
  6766. }
  6767. /* Send host, port, uri and (if it exists) ?query_string */
  6768. if (conn) {
  6769. mg_printf(conn,
  6770. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  6771. host,
  6772. (int)ntohs(
  6773. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  6774. conn->request_info.uri,
  6775. (conn->request_info.query_string == NULL) ? "" : "?",
  6776. (conn->request_info.query_string == NULL)
  6777. ? ""
  6778. : conn->request_info.query_string);
  6779. }
  6780. }
  6781. static void
  6782. mg_set_request_handler_type(struct mg_context *ctx,
  6783. const char *uri,
  6784. int is_websocket_handler,
  6785. int is_delete_request,
  6786. mg_request_handler handler,
  6787. mg_websocket_connect_handler connect_handler,
  6788. mg_websocket_ready_handler ready_handler,
  6789. mg_websocket_data_handler data_handler,
  6790. mg_websocket_close_handler close_handler,
  6791. void *cbdata)
  6792. {
  6793. struct mg_request_handler_info *tmp_rh, **lastref;
  6794. size_t urilen = strlen(uri);
  6795. if (is_websocket_handler) {
  6796. /* assert(handler == NULL); */
  6797. /* assert(is_delete_request || connect_handler!=NULL ||
  6798. * ready_handler!=NULL || data_handler!=NULL ||
  6799. * close_handler!=NULL);
  6800. */
  6801. if (handler != NULL) {
  6802. return;
  6803. }
  6804. if (!is_delete_request && connect_handler == NULL &&
  6805. ready_handler == NULL && data_handler == NULL &&
  6806. close_handler == NULL) {
  6807. return;
  6808. }
  6809. } else {
  6810. /* assert(connect_handler==NULL && ready_handler==NULL &&
  6811. * data_handler==NULL && close_handler==NULL); */
  6812. /* assert(is_delete_request || (handler!=NULL));
  6813. */
  6814. if (connect_handler != NULL || ready_handler != NULL ||
  6815. data_handler != NULL || close_handler != NULL) {
  6816. return;
  6817. }
  6818. if (!is_delete_request && (handler == NULL)) {
  6819. return;
  6820. }
  6821. }
  6822. if (!ctx) {
  6823. return;
  6824. }
  6825. mg_lock_context(ctx);
  6826. /* first try to find an existing handler */
  6827. lastref = &(ctx->request_handlers);
  6828. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  6829. tmp_rh = tmp_rh->next) {
  6830. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  6831. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6832. if (!is_delete_request) {
  6833. /* update existing handler */
  6834. if (!is_websocket_handler) {
  6835. tmp_rh->handler = handler;
  6836. } else {
  6837. tmp_rh->connect_handler = connect_handler;
  6838. tmp_rh->ready_handler = ready_handler;
  6839. tmp_rh->data_handler = data_handler;
  6840. tmp_rh->close_handler = close_handler;
  6841. }
  6842. tmp_rh->cbdata = cbdata;
  6843. } else {
  6844. /* remove existing handler */
  6845. *lastref = tmp_rh->next;
  6846. mg_free(tmp_rh->uri);
  6847. mg_free(tmp_rh);
  6848. }
  6849. mg_unlock_context(ctx);
  6850. return;
  6851. }
  6852. }
  6853. lastref = &(tmp_rh->next);
  6854. }
  6855. if (is_delete_request) {
  6856. /* no handler to set, this was a remove request to a non-existing
  6857. * handler */
  6858. mg_unlock_context(ctx);
  6859. return;
  6860. }
  6861. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  6862. sizeof(struct mg_request_handler_info), 1);
  6863. if (tmp_rh == NULL) {
  6864. mg_unlock_context(ctx);
  6865. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6866. return;
  6867. }
  6868. tmp_rh->uri = mg_strdup(uri);
  6869. if (!tmp_rh->uri) {
  6870. mg_unlock_context(ctx);
  6871. mg_free(tmp_rh);
  6872. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6873. return;
  6874. }
  6875. tmp_rh->uri_len = urilen;
  6876. if (!is_websocket_handler) {
  6877. tmp_rh->handler = handler;
  6878. } else {
  6879. tmp_rh->connect_handler = connect_handler;
  6880. tmp_rh->ready_handler = ready_handler;
  6881. tmp_rh->data_handler = data_handler;
  6882. tmp_rh->close_handler = close_handler;
  6883. }
  6884. tmp_rh->cbdata = cbdata;
  6885. tmp_rh->is_websocket_handler = is_websocket_handler;
  6886. tmp_rh->next = NULL;
  6887. *lastref = tmp_rh;
  6888. mg_unlock_context(ctx);
  6889. }
  6890. void mg_set_request_handler(struct mg_context *ctx,
  6891. const char *uri,
  6892. mg_request_handler handler,
  6893. void *cbdata)
  6894. {
  6895. mg_set_request_handler_type(
  6896. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  6897. }
  6898. void mg_set_websocket_handler(struct mg_context *ctx,
  6899. const char *uri,
  6900. mg_websocket_connect_handler connect_handler,
  6901. mg_websocket_ready_handler ready_handler,
  6902. mg_websocket_data_handler data_handler,
  6903. mg_websocket_close_handler close_handler,
  6904. void *cbdata)
  6905. {
  6906. int is_delete_request = (connect_handler == NULL) &&
  6907. (ready_handler == NULL) && (data_handler == NULL) &&
  6908. (close_handler == NULL);
  6909. mg_set_request_handler_type(ctx,
  6910. uri,
  6911. 1,
  6912. is_delete_request,
  6913. NULL,
  6914. connect_handler,
  6915. ready_handler,
  6916. data_handler,
  6917. close_handler,
  6918. cbdata);
  6919. }
  6920. static int get_request_handler(struct mg_connection *conn,
  6921. int is_websocket_request,
  6922. mg_request_handler *handler,
  6923. mg_websocket_connect_handler *connect_handler,
  6924. mg_websocket_ready_handler *ready_handler,
  6925. mg_websocket_data_handler *data_handler,
  6926. mg_websocket_close_handler *close_handler,
  6927. void **cbdata)
  6928. {
  6929. const struct mg_request_info *request_info = mg_get_request_info(conn);
  6930. if (request_info) {
  6931. const char *uri = request_info->uri;
  6932. size_t urilen = strlen(uri);
  6933. struct mg_request_handler_info *tmp_rh;
  6934. if (!conn || !conn->ctx) {
  6935. return 0;
  6936. }
  6937. mg_lock_context(conn->ctx);
  6938. /* first try for an exact match */
  6939. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6940. tmp_rh = tmp_rh->next) {
  6941. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6942. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6943. if (is_websocket_request) {
  6944. *connect_handler = tmp_rh->connect_handler;
  6945. *ready_handler = tmp_rh->ready_handler;
  6946. *data_handler = tmp_rh->data_handler;
  6947. *close_handler = tmp_rh->close_handler;
  6948. } else {
  6949. *handler = tmp_rh->handler;
  6950. }
  6951. *cbdata = tmp_rh->cbdata;
  6952. mg_unlock_context(conn->ctx);
  6953. return 1;
  6954. }
  6955. }
  6956. }
  6957. /* next try for a partial match, we will accept uri/something */
  6958. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6959. tmp_rh = tmp_rh->next) {
  6960. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6961. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  6962. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  6963. if (is_websocket_request) {
  6964. *connect_handler = tmp_rh->connect_handler;
  6965. *ready_handler = tmp_rh->ready_handler;
  6966. *data_handler = tmp_rh->data_handler;
  6967. *close_handler = tmp_rh->close_handler;
  6968. } else {
  6969. *handler = tmp_rh->handler;
  6970. }
  6971. *cbdata = tmp_rh->cbdata;
  6972. mg_unlock_context(conn->ctx);
  6973. return 1;
  6974. }
  6975. }
  6976. }
  6977. /* finally try for pattern match */
  6978. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6979. tmp_rh = tmp_rh->next) {
  6980. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6981. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  6982. if (is_websocket_request) {
  6983. *connect_handler = tmp_rh->connect_handler;
  6984. *ready_handler = tmp_rh->ready_handler;
  6985. *data_handler = tmp_rh->data_handler;
  6986. *close_handler = tmp_rh->close_handler;
  6987. } else {
  6988. *handler = tmp_rh->handler;
  6989. }
  6990. *cbdata = tmp_rh->cbdata;
  6991. mg_unlock_context(conn->ctx);
  6992. return 1;
  6993. }
  6994. }
  6995. }
  6996. mg_unlock_context(conn->ctx);
  6997. }
  6998. return 0; /* none found */
  6999. }
  7000. #if defined(USE_WEBSOCKET)
  7001. static int
  7002. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7003. void *cbdata)
  7004. {
  7005. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7006. if (pcallbacks->websocket_connect) {
  7007. return pcallbacks->websocket_connect(conn);
  7008. }
  7009. /* No handler set - assume "OK" */
  7010. return 0;
  7011. }
  7012. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  7013. void *cbdata)
  7014. {
  7015. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7016. if (pcallbacks->websocket_ready) {
  7017. pcallbacks->websocket_ready(conn);
  7018. }
  7019. }
  7020. static int deprecated_websocket_data_wrapper(
  7021. struct mg_connection *conn, int bits, char *data, size_t len, void *cbdata)
  7022. {
  7023. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7024. if (pcallbacks->websocket_data) {
  7025. return pcallbacks->websocket_data(conn, bits, data, len);
  7026. }
  7027. /* No handler set - assume "OK" */
  7028. return 1;
  7029. }
  7030. #endif
  7031. /* This is the heart of the Civetweb's logic.
  7032. * This function is called when the request is read, parsed and validated,
  7033. * and Civetweb must decide what action to take: serve a file, or
  7034. * a directory, or call embedded function, etcetera. */
  7035. static void handle_request(struct mg_connection *conn)
  7036. {
  7037. if (conn) {
  7038. struct mg_request_info *ri = &conn->request_info;
  7039. char path[PATH_MAX];
  7040. int uri_len, ssl_index, is_found, is_script_resource,
  7041. is_websocket_request, is_put_or_delete_request,
  7042. is_callback_resource;
  7043. int i;
  7044. struct file file = STRUCT_FILE_INITIALIZER;
  7045. time_t curtime = time(NULL);
  7046. mg_request_handler callback_handler = NULL;
  7047. mg_websocket_connect_handler ws_connect_handler = NULL;
  7048. mg_websocket_ready_handler ws_ready_handler = NULL;
  7049. mg_websocket_data_handler ws_data_handler = NULL;
  7050. mg_websocket_close_handler ws_close_handler = NULL;
  7051. void *callback_data = NULL;
  7052. #if !defined(NO_FILES)
  7053. char date[64];
  7054. #endif
  7055. path[0] = 0;
  7056. if (!ri) {
  7057. return;
  7058. }
  7059. /* 1. get the request url */
  7060. /* 1.1. split into url and query string */
  7061. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  7062. *((char *)conn->request_info.query_string++) = '\0';
  7063. }
  7064. uri_len = (int)strlen(ri->uri);
  7065. /* 1.2. decode url (if config says so) */
  7066. if (should_decode_url(conn)) {
  7067. mg_url_decode(ri->uri, uri_len, (char *)ri->uri, uri_len + 1, 0);
  7068. }
  7069. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  7070. * possible */
  7071. remove_double_dots_and_double_slashes((char *)ri->uri);
  7072. /* step 1. completed, the url is known now */
  7073. DEBUG_TRACE("URL: %s", ri->uri);
  7074. /* 2. do a https redirect, if required */
  7075. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  7076. ssl_index = get_first_ssl_listener_index(conn->ctx);
  7077. if (ssl_index >= 0) {
  7078. redirect_to_https_port(conn, ssl_index);
  7079. } else {
  7080. /* A http to https forward port has been specified,
  7081. * but no https port to forward to. */
  7082. send_http_error(conn,
  7083. 503,
  7084. "%s",
  7085. "Error: SSL forward not configured properly");
  7086. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  7087. }
  7088. return;
  7089. }
  7090. /* 3. if this ip has limited speed, set it for this connection */
  7091. conn->throttle = set_throttle(
  7092. conn->ctx->config[THROTTLE], get_remote_ip(conn), ri->uri);
  7093. /* 4. call a "handle everything" callback, if registered */
  7094. if (conn->ctx->callbacks.begin_request != NULL) {
  7095. /* Note that since V1.7 the "begin_request" function is called
  7096. * before an authorization check. If an authorization check is
  7097. * required, use a request_handler instead. */
  7098. i = conn->ctx->callbacks.begin_request(conn);
  7099. switch (i) {
  7100. case 1:
  7101. /* callback already processed the request */
  7102. return;
  7103. case 0:
  7104. /* civetweb should process the request */
  7105. break;
  7106. default:
  7107. /* unspecified - may change with the next version */
  7108. return;
  7109. }
  7110. }
  7111. /* request not yet handled by a handler or redirect, so the request
  7112. * is processed here */
  7113. /* 5. interpret the url to find out how the request must be handled */
  7114. /* 5.1. first test, if the request targets the regular http(s)://
  7115. * protocol namespace or the websocket ws(s):// protocol namespace. */
  7116. is_websocket_request = is_websocket_protocol(conn);
  7117. /* 5.2. check if the request will be handled by a callback */
  7118. if (get_request_handler(conn,
  7119. is_websocket_request,
  7120. &callback_handler,
  7121. &ws_connect_handler,
  7122. &ws_ready_handler,
  7123. &ws_data_handler,
  7124. &ws_close_handler,
  7125. &callback_data)) {
  7126. /* 5.2.1. A callback will handle this request. All requests handled
  7127. * by a callback have to be considered as requests to a script
  7128. * resource. */
  7129. is_callback_resource = 1;
  7130. is_script_resource = 1;
  7131. is_put_or_delete_request = is_put_or_delete_method(conn);
  7132. } else {
  7133. no_callback_resource:
  7134. /* 5.2.2. No callback is responsible for this request. The URI
  7135. * addresses a file based resource (static content or Lua/cgi
  7136. * scripts in the file system). */
  7137. is_callback_resource = 0;
  7138. interpret_uri(conn,
  7139. path,
  7140. sizeof(path),
  7141. &file,
  7142. &is_found,
  7143. &is_script_resource,
  7144. &is_websocket_request,
  7145. &is_put_or_delete_request);
  7146. }
  7147. /* 6. authorization check */
  7148. if (is_put_or_delete_request && !is_script_resource &&
  7149. !is_callback_resource) {
  7150. /* 6.1. this request is a PUT/DELETE to a real file */
  7151. /* 6.1.1. thus, the server must have real files */
  7152. #if defined(NO_FILES)
  7153. if (1) {
  7154. #else
  7155. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7156. #endif
  7157. /* This server does not have any real files, thus the
  7158. * PUT/DELETE methods are not valid. */
  7159. send_http_error(conn,
  7160. 405,
  7161. "%s method not allowed",
  7162. conn->request_info.request_method);
  7163. return;
  7164. }
  7165. /* 6.1.2. Check if put authorization for static files is available.
  7166. */
  7167. if (!is_authorized_for_put(conn)) {
  7168. send_authorization_request(conn);
  7169. return;
  7170. }
  7171. } else {
  7172. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  7173. * or it is a PUT or DELETE request to a resource that does not
  7174. * correspond to a file. Check authorization. */
  7175. if (!check_authorization(conn, path)) {
  7176. send_authorization_request(conn);
  7177. return;
  7178. }
  7179. }
  7180. /* request is authorized or does not need authorization */
  7181. /* 7. check if there are request handlers for this uri */
  7182. if (is_callback_resource) {
  7183. if (!is_websocket_request) {
  7184. if (callback_handler(conn, callback_data)) {
  7185. /* Do nothing, callback has served the request */
  7186. discard_unread_request_data(conn);
  7187. } else {
  7188. /* TODO (high): what if the handler did NOT handle the
  7189. * request */
  7190. /* The last version did handle this as a file request, but
  7191. * since a file request is not always a script resource,
  7192. * the authorization check might be different */
  7193. interpret_uri(conn,
  7194. path,
  7195. sizeof(path),
  7196. &file,
  7197. &is_found,
  7198. &is_script_resource,
  7199. &is_websocket_request,
  7200. &is_put_or_delete_request);
  7201. callback_handler = NULL;
  7202. /* TODO (very low): goto is deprecatedm but for the moment,
  7203. * a goto is
  7204. * simpler than some curious loop. */
  7205. /* The situation "callback does not handle the request"
  7206. * needs to be reconsidered anyway. */
  7207. goto no_callback_resource;
  7208. }
  7209. } else {
  7210. #if defined(USE_WEBSOCKET)
  7211. handle_websocket_request(conn,
  7212. path,
  7213. is_callback_resource,
  7214. ws_connect_handler,
  7215. ws_ready_handler,
  7216. ws_data_handler,
  7217. ws_close_handler,
  7218. callback_data);
  7219. #endif
  7220. }
  7221. return;
  7222. }
  7223. /* 8. handle websocket requests */
  7224. #if defined(USE_WEBSOCKET)
  7225. if (is_websocket_request) {
  7226. handle_websocket_request(
  7227. conn,
  7228. path,
  7229. !is_script_resource /* could be deprecated global callback */,
  7230. deprecated_websocket_connect_wrapper,
  7231. deprecated_websocket_ready_wrapper,
  7232. deprecated_websocket_data_wrapper,
  7233. NULL,
  7234. &conn->ctx->callbacks);
  7235. return;
  7236. } else
  7237. #endif
  7238. #if defined(NO_FILES)
  7239. /* 9a. In case the server uses only callbacks, this uri is unknown.
  7240. * Then, all request handling ends here. */
  7241. send_http_error(conn, 404, "%s", "Not Found");
  7242. #else
  7243. /* 9b. This request is either for a static file or resource handled
  7244. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  7245. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7246. send_http_error(conn, 404, "%s", "Not Found");
  7247. return;
  7248. }
  7249. /* 10. File is handled by a script. */
  7250. if (is_script_resource) {
  7251. handle_file_based_request(conn, path, &file);
  7252. return;
  7253. }
  7254. /* 11. Handle put/delete/mkcol requests */
  7255. if (is_put_or_delete_request) {
  7256. /* 11.1. PUT method */
  7257. if (!strcmp(ri->request_method, "PUT")) {
  7258. put_file(conn, path);
  7259. return;
  7260. }
  7261. /* 11.2. DELETE method */
  7262. if (!strcmp(ri->request_method, "DELETE")) {
  7263. delete_file(conn, path);
  7264. return;
  7265. }
  7266. /* 11.3. MKCOL method */
  7267. if (!strcmp(ri->request_method, "MKCOL")) {
  7268. mkcol(conn, path);
  7269. return;
  7270. }
  7271. /* 11.4. should never reach this point */
  7272. send_http_error(conn,
  7273. 405,
  7274. "%s method not allowed",
  7275. conn->request_info.request_method);
  7276. return;
  7277. }
  7278. /* 11. File does not exist, or it was configured that it should be
  7279. * hidden */
  7280. if (!is_found || (must_hide_file(conn, path))) {
  7281. send_http_error(conn, 404, "%s", "Not found");
  7282. return;
  7283. }
  7284. /* 12. Directories uris should end with a slash */
  7285. if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  7286. gmt_time_string(date, sizeof(date), &curtime);
  7287. mg_printf(conn,
  7288. "HTTP/1.1 301 Moved Permanently\r\n"
  7289. "Location: %s/\r\n"
  7290. "Date: %s\r\n"
  7291. "Content-Length: 0\r\n"
  7292. "Connection: %s\r\n\r\n",
  7293. ri->uri,
  7294. date,
  7295. suggest_connection_header(conn));
  7296. return;
  7297. }
  7298. /* 13. Handle other methods than GET/HEAD */
  7299. /* 13.1. Handle PROPFIND */
  7300. if (!strcmp(ri->request_method, "PROPFIND")) {
  7301. handle_propfind(conn, path, &file);
  7302. return;
  7303. }
  7304. /* 13.2. Handle OPTIONS for files */
  7305. if (!strcmp(ri->request_method, "OPTIONS")) {
  7306. /* This standard handler is only used for real files.
  7307. * Scripts should support the OPTIONS method themselves, to allow a
  7308. * maximum flexibility.
  7309. * Lua and CGI scripts may fully support CORS this way (including
  7310. * preflights). */
  7311. send_options(conn);
  7312. return;
  7313. }
  7314. /* 13.3. everything but GET and HEAD (e.g. POST) */
  7315. if (0 != strcmp(ri->request_method, "GET") &&
  7316. 0 != strcmp(ri->request_method, "HEAD")) {
  7317. send_http_error(conn,
  7318. 405,
  7319. "%s method not allowed",
  7320. conn->request_info.request_method);
  7321. return;
  7322. }
  7323. /* 14. directories */
  7324. if (file.is_directory) {
  7325. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  7326. /* 14.1. use a substitute file */
  7327. /* TODO (high): substitute index may be a script resource.
  7328. * define what should be possible in this case. */
  7329. } else {
  7330. /* 14.2. no substitute file */
  7331. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7332. "yes")) {
  7333. handle_directory_request(conn, path);
  7334. } else {
  7335. send_http_error(
  7336. conn, 403, "%s", "Error: Directory listing denied");
  7337. }
  7338. return;
  7339. }
  7340. }
  7341. handle_file_based_request(conn, path, &file);
  7342. #endif /* !defined(NO_FILES) */
  7343. #if 0
  7344. /* Perform redirect and auth checks before calling begin_request()
  7345. * handler.
  7346. * Otherwise, begin_request() would need to perform auth checks and
  7347. * redirects. */
  7348. #endif
  7349. }
  7350. return;
  7351. }
  7352. static void handle_file_based_request(struct mg_connection *conn,
  7353. const char *path,
  7354. struct file *file)
  7355. {
  7356. if (!conn || !conn->ctx) {
  7357. return;
  7358. }
  7359. if (0) {
  7360. #ifdef USE_LUA
  7361. } else if (match_prefix(
  7362. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  7363. strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  7364. path) > 0) {
  7365. /* Lua server page: an SSI like page containing mostly plain html code
  7366. * plus some tags with server generated contents. */
  7367. handle_lsp_request(conn, path, file, NULL);
  7368. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  7369. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  7370. path) > 0) {
  7371. /* Lua in-server module script: a CGI like script used to generate the
  7372. * entire reply. */
  7373. mg_exec_lua_script(conn, path, NULL);
  7374. #endif
  7375. #if !defined(NO_CGI)
  7376. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  7377. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  7378. path) > 0) {
  7379. /* CGI scripts may support all HTTP methods */
  7380. handle_cgi_request(conn, path);
  7381. #endif /* !NO_CGI */
  7382. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7383. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7384. path) > 0) {
  7385. handle_ssi_file_request(conn, path, file);
  7386. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  7387. /* Send 304 "Not Modified" - this must not send any body data */
  7388. send_http_error(conn, 304, "%s", "");
  7389. } else {
  7390. handle_static_file_request(conn, path, file);
  7391. }
  7392. }
  7393. static void close_all_listening_sockets(struct mg_context *ctx)
  7394. {
  7395. unsigned int i;
  7396. if (!ctx) {
  7397. return;
  7398. }
  7399. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7400. closesocket(ctx->listening_sockets[i].sock);
  7401. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  7402. }
  7403. mg_free(ctx->listening_sockets);
  7404. ctx->listening_sockets = NULL;
  7405. mg_free(ctx->listening_ports);
  7406. ctx->listening_ports = NULL;
  7407. }
  7408. /* Valid listening port specification is: [ip_address:]port[s]
  7409. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  7410. * Examples for IPv6: [::]:80, [::1]:80,
  7411. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  7412. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  7413. static int parse_port_string(const struct vec *vec, struct socket *so)
  7414. {
  7415. unsigned int a, b, c, d, port;
  7416. int ch, len;
  7417. #if defined(USE_IPV6)
  7418. char buf[100] = {0};
  7419. #endif
  7420. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  7421. * Also, all-zeroes in the socket address means binding to all addresses
  7422. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  7423. memset(so, 0, sizeof(*so));
  7424. so->lsa.sin.sin_family = AF_INET;
  7425. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  7426. 5) {
  7427. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  7428. so->lsa.sin.sin_addr.s_addr =
  7429. htonl((a << 24) | (b << 16) | (c << 8) | d);
  7430. so->lsa.sin.sin_port = htons((uint16_t)port);
  7431. #if defined(USE_IPV6)
  7432. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  7433. mg_inet_pton(
  7434. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  7435. /* IPv6 address, examples: see above */
  7436. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  7437. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  7438. #endif
  7439. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  7440. /* If only port is specified, bind to IPv4, INADDR_ANY */
  7441. so->lsa.sin.sin_port = htons((uint16_t)port);
  7442. } else {
  7443. /* Parsing failure. Make port invalid. */
  7444. port = 0;
  7445. len = 0;
  7446. }
  7447. /* sscanf and the option splitting code ensure the following condition */
  7448. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  7449. return 0;
  7450. }
  7451. ch = vec->ptr[len]; /* Next character after the port number */
  7452. so->is_ssl = (ch == 's');
  7453. so->ssl_redir = (ch == 'r');
  7454. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  7455. return is_valid_port(port) &&
  7456. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  7457. }
  7458. static int set_ports_option(struct mg_context *ctx)
  7459. {
  7460. const char *list;
  7461. int on = 1;
  7462. #if defined(USE_IPV6)
  7463. int off = 0;
  7464. #endif
  7465. struct vec vec;
  7466. struct socket so, *ptr;
  7467. in_port_t *portPtr;
  7468. union usa usa;
  7469. socklen_t len;
  7470. int portsTotal = 0;
  7471. int portsOk = 0;
  7472. if (!ctx) {
  7473. return 0;
  7474. }
  7475. memset(&so, 0, sizeof(so));
  7476. memset(&usa, 0, sizeof(usa));
  7477. len = sizeof(usa);
  7478. list = ctx->config[LISTENING_PORTS];
  7479. while ((list = next_option(list, &vec, NULL)) != NULL) {
  7480. portsTotal++;
  7481. if (!parse_port_string(&vec, &so)) {
  7482. mg_cry(fc(ctx),
  7483. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  7484. (int)vec.len,
  7485. vec.ptr,
  7486. portsTotal,
  7487. "[IP_ADDRESS:]PORT[s|r]");
  7488. continue;
  7489. }
  7490. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  7491. mg_cry(fc(ctx),
  7492. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  7493. "option set?",
  7494. portsTotal);
  7495. continue;
  7496. }
  7497. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  7498. INVALID_SOCKET) {
  7499. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  7500. continue;
  7501. }
  7502. #ifdef _WIN32
  7503. /* Windows SO_REUSEADDR lets many procs binds to a
  7504. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  7505. * if someone already has the socket -- DTL */
  7506. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  7507. * Windows might need a few seconds before
  7508. * the same port can be used again in the
  7509. * same process, so a short Sleep may be
  7510. * required between mg_stop and mg_start.
  7511. */
  7512. if (setsockopt(so.sock,
  7513. SOL_SOCKET,
  7514. SO_EXCLUSIVEADDRUSE,
  7515. (SOCK_OPT_TYPE)&on,
  7516. sizeof(on)) != 0) {
  7517. mg_cry(fc(ctx),
  7518. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  7519. portsTotal);
  7520. }
  7521. #else
  7522. if (setsockopt(so.sock,
  7523. SOL_SOCKET,
  7524. SO_REUSEADDR,
  7525. (SOCK_OPT_TYPE)&on,
  7526. sizeof(on)) != 0) {
  7527. mg_cry(fc(ctx),
  7528. "cannot set socket option SO_REUSEADDR (entry %i)",
  7529. portsTotal);
  7530. }
  7531. #endif
  7532. #if defined(USE_IPV6)
  7533. if (so.lsa.sa.sa_family == AF_INET6 &&
  7534. setsockopt(so.sock,
  7535. IPPROTO_IPV6,
  7536. IPV6_V6ONLY,
  7537. (void *)&off,
  7538. sizeof(off)) != 0) {
  7539. mg_cry(fc(ctx),
  7540. "cannot set socket option IPV6_V6ONLY (entry %i)",
  7541. portsTotal);
  7542. }
  7543. #endif
  7544. if (so.lsa.sa.sa_family == AF_INET) {
  7545. len = sizeof(so.lsa.sin);
  7546. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  7547. mg_cry(fc(ctx),
  7548. "cannot bind to %.*s: %d (%s)",
  7549. (int)vec.len,
  7550. vec.ptr,
  7551. (int)ERRNO,
  7552. strerror(errno));
  7553. closesocket(so.sock);
  7554. so.sock = INVALID_SOCKET;
  7555. continue;
  7556. }
  7557. }
  7558. #if defined(USE_IPV6)
  7559. else if (so.lsa.sa.sa_family == AF_INET6) {
  7560. len = sizeof(so.lsa.sin6);
  7561. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  7562. mg_cry(fc(ctx),
  7563. "cannot bind to IPv6 %.*s: %d (%s)",
  7564. (int)vec.len,
  7565. vec.ptr,
  7566. (int)ERRNO,
  7567. strerror(errno));
  7568. closesocket(so.sock);
  7569. so.sock = INVALID_SOCKET;
  7570. continue;
  7571. }
  7572. }
  7573. #endif
  7574. else {
  7575. mg_cry(fc(ctx),
  7576. "cannot bind: address family not supported (entry %i)",
  7577. portsTotal);
  7578. continue;
  7579. }
  7580. if (listen(so.sock, SOMAXCONN) != 0) {
  7581. mg_cry(fc(ctx),
  7582. "cannot listen to %.*s: %d (%s)",
  7583. (int)vec.len,
  7584. vec.ptr,
  7585. (int)ERRNO,
  7586. strerror(errno));
  7587. closesocket(so.sock);
  7588. so.sock = INVALID_SOCKET;
  7589. continue;
  7590. }
  7591. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  7592. int err = (int)ERRNO;
  7593. mg_cry(fc(ctx),
  7594. "call to getsockname failed %.*s: %d (%s)",
  7595. (int)vec.len,
  7596. vec.ptr,
  7597. err,
  7598. strerror(errno));
  7599. closesocket(so.sock);
  7600. so.sock = INVALID_SOCKET;
  7601. continue;
  7602. }
  7603. if ((ptr = (struct socket *)mg_realloc(
  7604. ctx->listening_sockets,
  7605. (ctx->num_listening_sockets + 1) *
  7606. sizeof(ctx->listening_sockets[0]))) == NULL) {
  7607. mg_cry(fc(ctx), "%s", "Out of memory");
  7608. closesocket(so.sock);
  7609. so.sock = INVALID_SOCKET;
  7610. continue;
  7611. }
  7612. if ((portPtr = (in_port_t *)mg_realloc(
  7613. ctx->listening_ports,
  7614. (ctx->num_listening_sockets + 1) *
  7615. sizeof(ctx->listening_ports[0]))) == NULL) {
  7616. mg_cry(fc(ctx), "%s", "Out of memory");
  7617. closesocket(so.sock);
  7618. so.sock = INVALID_SOCKET;
  7619. mg_free(ptr);
  7620. continue;
  7621. }
  7622. set_close_on_exec(so.sock, fc(ctx));
  7623. ctx->listening_sockets = ptr;
  7624. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  7625. ctx->listening_ports = portPtr;
  7626. ctx->listening_ports[ctx->num_listening_sockets] =
  7627. ntohs(usa.sin.sin_port);
  7628. ctx->num_listening_sockets++;
  7629. portsOk++;
  7630. }
  7631. if (portsOk != portsTotal) {
  7632. close_all_listening_sockets(ctx);
  7633. portsOk = 0;
  7634. }
  7635. return portsOk;
  7636. }
  7637. static const char *header_val(const struct mg_connection *conn,
  7638. const char *header)
  7639. {
  7640. const char *header_value;
  7641. if ((header_value = mg_get_header(conn, header)) == NULL) {
  7642. return "-";
  7643. } else {
  7644. return header_value;
  7645. }
  7646. }
  7647. static void log_access(const struct mg_connection *conn)
  7648. {
  7649. const struct mg_request_info *ri;
  7650. FILE *fp;
  7651. char date[64], src_addr[IP_ADDR_STR_LEN];
  7652. struct tm *tm;
  7653. const char *referer;
  7654. const char *user_agent;
  7655. char buf[4096];
  7656. if (!conn || !conn->ctx) {
  7657. return;
  7658. }
  7659. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  7660. ? NULL
  7661. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  7662. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  7663. return;
  7664. }
  7665. tm = localtime(&conn->conn_birth_time);
  7666. if (tm != NULL) {
  7667. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  7668. } else {
  7669. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  7670. date[sizeof(date) - 1] = '\0';
  7671. }
  7672. ri = &conn->request_info;
  7673. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7674. referer = header_val(conn, "Referer");
  7675. user_agent = header_val(conn, "User-Agent");
  7676. snprintf(buf,
  7677. sizeof(buf),
  7678. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  7679. src_addr,
  7680. ri->remote_user == NULL ? "-" : ri->remote_user,
  7681. date,
  7682. ri->request_method ? ri->request_method : "-",
  7683. ri->uri ? ri->uri : "-",
  7684. ri->http_version,
  7685. conn->status_code,
  7686. conn->num_bytes_sent,
  7687. referer,
  7688. user_agent);
  7689. if (conn->ctx->callbacks.log_access) {
  7690. conn->ctx->callbacks.log_access(conn, buf);
  7691. }
  7692. if (fp) {
  7693. flockfile(fp);
  7694. fprintf(fp, "%s", buf);
  7695. fputc('\n', fp);
  7696. fflush(fp);
  7697. funlockfile(fp);
  7698. fclose(fp);
  7699. }
  7700. }
  7701. /* Verify given socket address against the ACL.
  7702. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  7703. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  7704. {
  7705. int allowed, flag;
  7706. uint32_t net, mask;
  7707. struct vec vec;
  7708. if (ctx) {
  7709. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  7710. /* If any ACL is set, deny by default */
  7711. allowed = list == NULL ? '+' : '-';
  7712. while ((list = next_option(list, &vec, NULL)) != NULL) {
  7713. flag = vec.ptr[0];
  7714. if ((flag != '+' && flag != '-') ||
  7715. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  7716. mg_cry(
  7717. fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  7718. return -1;
  7719. }
  7720. if (net == (remote_ip & mask)) {
  7721. allowed = flag;
  7722. }
  7723. }
  7724. return allowed == '+';
  7725. }
  7726. return -1;
  7727. }
  7728. #if !defined(_WIN32)
  7729. static int set_uid_option(struct mg_context *ctx)
  7730. {
  7731. struct passwd *pw;
  7732. if (ctx) {
  7733. const char *uid = ctx->config[RUN_AS_USER];
  7734. int success = 0;
  7735. if (uid == NULL) {
  7736. success = 1;
  7737. } else {
  7738. if ((pw = getpwnam(uid)) == NULL) {
  7739. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  7740. } else if (setgid(pw->pw_gid) == -1) {
  7741. mg_cry(fc(ctx),
  7742. "%s: setgid(%s): %s",
  7743. __func__,
  7744. uid,
  7745. strerror(errno));
  7746. } else if (setgroups(0, NULL)) {
  7747. mg_cry(
  7748. fc(ctx), "%s: setgroups(): %s", __func__, strerror(errno));
  7749. } else if (setuid(pw->pw_uid) == -1) {
  7750. mg_cry(fc(ctx),
  7751. "%s: setuid(%s): %s",
  7752. __func__,
  7753. uid,
  7754. strerror(errno));
  7755. } else {
  7756. success = 1;
  7757. }
  7758. }
  7759. return success;
  7760. }
  7761. return 0;
  7762. }
  7763. #endif /* !_WIN32 */
  7764. #if !defined(NO_SSL)
  7765. static pthread_mutex_t *ssl_mutexes;
  7766. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  7767. {
  7768. if (!conn) {
  7769. return 0;
  7770. }
  7771. return (conn->ssl = SSL_new(s)) != NULL &&
  7772. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  7773. func(conn->ssl) == 1;
  7774. }
  7775. /* Return OpenSSL error message (from CRYPTO lib) */
  7776. static const char *ssl_error(void)
  7777. {
  7778. unsigned long err;
  7779. err = ERR_get_error();
  7780. return err == 0 ? "" : ERR_error_string(err, NULL);
  7781. }
  7782. static void
  7783. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  7784. {
  7785. (void)line;
  7786. (void)file;
  7787. if (mode & 1) {
  7788. /* 1 is CRYPTO_LOCK */
  7789. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  7790. } else {
  7791. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  7792. }
  7793. }
  7794. static unsigned long ssl_id_callback(void)
  7795. {
  7796. return (unsigned long)pthread_self();
  7797. }
  7798. #if !defined(NO_SSL_DL)
  7799. static void *
  7800. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  7801. {
  7802. union {
  7803. void *p;
  7804. void (*fp)(void);
  7805. } u;
  7806. void *dll_handle;
  7807. struct ssl_func *fp;
  7808. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  7809. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  7810. return NULL;
  7811. }
  7812. for (fp = sw; fp->name != NULL; fp++) {
  7813. #ifdef _WIN32
  7814. /* GetProcAddress() returns pointer to function */
  7815. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  7816. #else
  7817. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  7818. * pointers to function pointers. We need to use a union to make a
  7819. * cast. */
  7820. u.p = dlsym(dll_handle, fp->name);
  7821. #endif /* _WIN32 */
  7822. if (u.fp == NULL) {
  7823. mg_cry(fc(ctx),
  7824. "%s: %s: cannot find %s",
  7825. __func__,
  7826. dll_name,
  7827. fp->name);
  7828. dlclose(dll_handle);
  7829. return NULL;
  7830. } else {
  7831. fp->ptr = u.fp;
  7832. }
  7833. }
  7834. return dll_handle;
  7835. }
  7836. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  7837. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  7838. #endif /* NO_SSL_DL */
  7839. #if defined(SSL_ALREADY_INITIALIZED)
  7840. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  7841. #else
  7842. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  7843. #endif
  7844. static int initialize_ssl(struct mg_context *ctx)
  7845. {
  7846. int i;
  7847. size_t size;
  7848. #if !defined(NO_SSL_DL)
  7849. if (!cryptolib_dll_handle) {
  7850. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  7851. if (!cryptolib_dll_handle) {
  7852. return 0;
  7853. }
  7854. }
  7855. #endif /* NO_SSL_DL */
  7856. if (mg_atomic_inc(&cryptolib_users) > 1) {
  7857. return 1;
  7858. }
  7859. /* Initialize locking callbacks, needed for thread safety.
  7860. * http://www.openssl.org/support/faq.html#PROG1
  7861. */
  7862. i = CRYPTO_num_locks();
  7863. if (i < 0) {
  7864. i = 0;
  7865. }
  7866. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  7867. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  7868. mg_cry(
  7869. fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  7870. return 0;
  7871. }
  7872. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7873. pthread_mutex_init(&ssl_mutexes[i], NULL);
  7874. }
  7875. CRYPTO_set_locking_callback(&ssl_locking_callback);
  7876. CRYPTO_set_id_callback(&ssl_id_callback);
  7877. return 1;
  7878. }
  7879. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  7880. static int set_ssl_option(struct mg_context *ctx)
  7881. {
  7882. const char *pem;
  7883. int callback_ret;
  7884. /* If PEM file is not specified and the init_ssl callback
  7885. * is not specified, skip SSL initialization. */
  7886. if (!ctx) {
  7887. return 0;
  7888. }
  7889. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  7890. ctx->callbacks.init_ssl == NULL) {
  7891. return 1;
  7892. }
  7893. if (!initialize_ssl(ctx)) {
  7894. return 0;
  7895. }
  7896. #if !defined(NO_SSL_DL)
  7897. if (!ssllib_dll_handle) {
  7898. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  7899. if (!ssllib_dll_handle) {
  7900. return 0;
  7901. }
  7902. }
  7903. #endif /* NO_SSL_DL */
  7904. /* Initialize SSL library */
  7905. SSL_library_init();
  7906. SSL_load_error_strings();
  7907. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  7908. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  7909. return 0;
  7910. }
  7911. /* If a callback has been specified, call it. */
  7912. callback_ret =
  7913. (ctx->callbacks.init_ssl == NULL)
  7914. ? 0
  7915. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  7916. /* If callback returns 0, civetweb sets up the SSL certificate.
  7917. * If it returns 1, civetweb assumes the calback already did this.
  7918. * If it returns -1, initializing ssl fails. */
  7919. if (callback_ret < 0) {
  7920. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  7921. return 0;
  7922. }
  7923. if (callback_ret == 0) {
  7924. if (pem != NULL) {
  7925. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  7926. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  7927. mg_cry(fc(ctx),
  7928. "%s: cannot open %s: %s",
  7929. __func__,
  7930. pem,
  7931. ssl_error());
  7932. return 0;
  7933. }
  7934. }
  7935. }
  7936. if (pem != NULL) {
  7937. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  7938. }
  7939. return 1;
  7940. }
  7941. static void uninitialize_ssl(struct mg_context *ctx)
  7942. {
  7943. int i;
  7944. (void)ctx;
  7945. if (mg_atomic_dec(&cryptolib_users) == 0) {
  7946. CRYPTO_set_locking_callback(NULL);
  7947. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7948. pthread_mutex_destroy(&ssl_mutexes[i]);
  7949. }
  7950. CRYPTO_set_locking_callback(NULL);
  7951. CRYPTO_set_id_callback(NULL);
  7952. }
  7953. }
  7954. #endif /* !NO_SSL */
  7955. static int set_gpass_option(struct mg_context *ctx)
  7956. {
  7957. if (ctx) {
  7958. struct file file = STRUCT_FILE_INITIALIZER;
  7959. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  7960. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  7961. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  7962. return 0;
  7963. }
  7964. return 1;
  7965. }
  7966. return 0;
  7967. }
  7968. static int set_acl_option(struct mg_context *ctx)
  7969. {
  7970. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  7971. }
  7972. static void reset_per_request_attributes(struct mg_connection *conn)
  7973. {
  7974. if (!conn) {
  7975. return;
  7976. }
  7977. conn->path_info = NULL;
  7978. conn->num_bytes_sent = conn->consumed_content = 0;
  7979. conn->status_code = -1;
  7980. conn->is_chunked = 0;
  7981. conn->must_close = conn->request_len = conn->throttle = 0;
  7982. conn->request_info.content_length = -1;
  7983. conn->request_info.remote_user = NULL;
  7984. conn->request_info.request_method = NULL;
  7985. conn->request_info.uri = NULL;
  7986. conn->request_info.http_version = NULL;
  7987. conn->request_info.num_headers = 0;
  7988. conn->data_len = 0;
  7989. conn->chunk_remainder = 0;
  7990. }
  7991. static int set_sock_timeout(SOCKET sock, int milliseconds)
  7992. {
  7993. int r1, r2;
  7994. #ifdef _WIN32
  7995. DWORD t = (DWORD)milliseconds;
  7996. #else
  7997. #if defined(TCP_USER_TIMEOUT)
  7998. unsigned int uto = (unsigned int)milliseconds;
  7999. #endif
  8000. struct timeval t;
  8001. t.tv_sec = milliseconds / 1000;
  8002. t.tv_usec = (milliseconds * 1000) % 1000000;
  8003. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  8004. * max. time waiting for the acknowledged of TCP data before the connection
  8005. * will be forcefully closed and ETIMEDOUT is returned to the application.
  8006. * If this option is not set, the default timeout of 20-30 minutes is used.
  8007. */
  8008. /* #define TCP_USER_TIMEOUT (18) */
  8009. #if defined(TCP_USER_TIMEOUT)
  8010. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  8011. #endif
  8012. #endif
  8013. r1 =
  8014. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8015. r2 =
  8016. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8017. return r1 || r2;
  8018. }
  8019. static void close_socket_gracefully(struct mg_connection *conn)
  8020. {
  8021. #if defined(_WIN32)
  8022. char buf[MG_BUF_LEN];
  8023. int n;
  8024. #endif
  8025. struct linger linger;
  8026. if (!conn) {
  8027. return;
  8028. }
  8029. /* Set linger option to avoid socket hanging out after close. This prevent
  8030. * ephemeral port exhaust problem under high QPS. */
  8031. linger.l_onoff = 1;
  8032. linger.l_linger = 1;
  8033. if (setsockopt(conn->client.sock,
  8034. SOL_SOCKET,
  8035. SO_LINGER,
  8036. (char *)&linger,
  8037. sizeof(linger)) != 0) {
  8038. mg_cry(conn,
  8039. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  8040. __func__,
  8041. strerror(ERRNO));
  8042. }
  8043. /* Send FIN to the client */
  8044. shutdown(conn->client.sock, SHUT_WR);
  8045. set_non_blocking_mode(conn->client.sock);
  8046. #if defined(_WIN32)
  8047. /* Read and discard pending incoming data. If we do not do that and close
  8048. * the socket, the data in the send buffer may be discarded. This
  8049. * behaviour is seen on Windows, when client keeps sending data
  8050. * when server decides to close the connection; then when client
  8051. * does recv() it gets no data back. */
  8052. do {
  8053. n = pull(
  8054. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  8055. } while (n > 0);
  8056. #endif
  8057. /* Now we know that our FIN is ACK-ed, safe to close */
  8058. closesocket(conn->client.sock);
  8059. conn->client.sock = INVALID_SOCKET;
  8060. }
  8061. static void close_connection(struct mg_connection *conn)
  8062. {
  8063. if (!conn || !conn->ctx) {
  8064. return;
  8065. }
  8066. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8067. if (conn->lua_websocket_state) {
  8068. lua_websocket_close(conn, conn->lua_websocket_state);
  8069. conn->lua_websocket_state = NULL;
  8070. }
  8071. #endif
  8072. /* call the connection_close callback if assigned */
  8073. if ((conn->ctx->callbacks.connection_close != NULL) &&
  8074. (conn->ctx->context_type == 1)) {
  8075. conn->ctx->callbacks.connection_close(conn);
  8076. }
  8077. mg_lock_connection(conn);
  8078. conn->must_close = 1;
  8079. #ifndef NO_SSL
  8080. if (conn->ssl != NULL) {
  8081. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  8082. SSL_shutdown(conn->ssl);
  8083. SSL_free(conn->ssl);
  8084. conn->ssl = NULL;
  8085. }
  8086. #endif
  8087. if (conn->client.sock != INVALID_SOCKET) {
  8088. close_socket_gracefully(conn);
  8089. conn->client.sock = INVALID_SOCKET;
  8090. }
  8091. mg_unlock_connection(conn);
  8092. }
  8093. void mg_close_connection(struct mg_connection *conn)
  8094. {
  8095. struct mg_context *client_ctx = NULL;
  8096. unsigned int i;
  8097. if (conn == NULL) {
  8098. return;
  8099. }
  8100. if (conn->ctx->context_type == 2) {
  8101. client_ctx = conn->ctx;
  8102. /* client context: loops must end */
  8103. conn->ctx->stop_flag = 1;
  8104. }
  8105. #ifndef NO_SSL
  8106. if (conn->client_ssl_ctx != NULL) {
  8107. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  8108. }
  8109. #endif
  8110. close_connection(conn);
  8111. if (client_ctx != NULL) {
  8112. /* join worker thread and free context */
  8113. for (i = 0; i < client_ctx->workerthreadcount; i++) {
  8114. mg_join_thread(client_ctx->workerthreadids[i]);
  8115. }
  8116. mg_free(client_ctx->workerthreadids);
  8117. mg_free(client_ctx);
  8118. }
  8119. (void)pthread_mutex_destroy(&conn->mutex);
  8120. mg_free(conn);
  8121. }
  8122. struct mg_connection *mg_connect_client(
  8123. const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len)
  8124. {
  8125. static struct mg_context fake_ctx;
  8126. struct mg_connection *conn = NULL;
  8127. SOCKET sock;
  8128. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf, ebuf_len)) ==
  8129. INVALID_SOCKET) {
  8130. } else if ((conn = (struct mg_connection *)mg_calloc(
  8131. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  8132. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  8133. closesocket(sock);
  8134. #ifndef NO_SSL
  8135. } else if (use_ssl &&
  8136. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  8137. NULL) {
  8138. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  8139. closesocket(sock);
  8140. mg_free(conn);
  8141. conn = NULL;
  8142. #endif /* NO_SSL */
  8143. } else {
  8144. socklen_t len = sizeof(struct sockaddr);
  8145. conn->buf_size = MAX_REQUEST_SIZE;
  8146. conn->buf = (char *)(conn + 1);
  8147. conn->ctx = &fake_ctx;
  8148. conn->client.sock = sock;
  8149. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  8150. mg_cry(conn,
  8151. "%s: getsockname() failed: %s",
  8152. __func__,
  8153. strerror(ERRNO));
  8154. }
  8155. conn->client.is_ssl = use_ssl ? 1 : 0;
  8156. (void)pthread_mutex_init(&conn->mutex, NULL);
  8157. #ifndef NO_SSL
  8158. if (use_ssl) {
  8159. /* SSL_CTX_set_verify call is needed to switch off server
  8160. * certificate checking, which is off by default in OpenSSL and on
  8161. * in yaSSL. */
  8162. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  8163. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  8164. }
  8165. #endif
  8166. }
  8167. return conn;
  8168. }
  8169. static int is_valid_uri(const char *uri)
  8170. {
  8171. /* Conform to
  8172. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  8173. * URI can be an asterisk (*) or should start with slash. */
  8174. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  8175. }
  8176. static int
  8177. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  8178. {
  8179. const char *cl;
  8180. if (ebuf_len > 0) {
  8181. ebuf[0] = '\0';
  8182. }
  8183. *err = 0;
  8184. reset_per_request_attributes(conn);
  8185. if (!conn) {
  8186. snprintf(ebuf, ebuf_len, "%s", "Internal error");
  8187. *err = 500;
  8188. return 0;
  8189. }
  8190. /* Set the time the request was received. This value should be used for
  8191. * timeouts. */
  8192. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  8193. conn->request_len =
  8194. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  8195. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  8196. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  8197. snprintf(ebuf, ebuf_len, "%s", "Invalid request size");
  8198. *err = 500;
  8199. return 0;
  8200. }
  8201. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  8202. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  8203. *err = 413;
  8204. return 0;
  8205. } else if (conn->request_len <= 0) {
  8206. if (conn->data_len > 0) {
  8207. snprintf(ebuf, ebuf_len, "%s", "Client sent malformed request");
  8208. *err = 400;
  8209. } else {
  8210. /* Server did not send anything -> just close the connection */
  8211. conn->must_close = 1;
  8212. snprintf(ebuf, ebuf_len, "%s", "Client did not send a request");
  8213. *err = 0;
  8214. }
  8215. return 0;
  8216. } else if (parse_http_message(
  8217. conn->buf, conn->buf_size, &conn->request_info) <= 0) {
  8218. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  8219. *err = 400;
  8220. return 0;
  8221. } else {
  8222. /* Message is a valid request or response */
  8223. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  8224. /* Request/response has content length set */
  8225. char *endptr = NULL;
  8226. conn->content_len = strtoll(cl, &endptr, 10);
  8227. if (endptr == cl) {
  8228. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  8229. *err = 411;
  8230. return 0;
  8231. }
  8232. /* Publish the content length back to the request info. */
  8233. conn->request_info.content_length = conn->content_len;
  8234. } else if ((cl = get_header(&conn->request_info,
  8235. "Transfer-encoding")) != NULL &&
  8236. strcmp(cl, "chunked") == 0) {
  8237. conn->is_chunked = 1;
  8238. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  8239. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  8240. /* POST or PUT request without content length set */
  8241. conn->content_len = -1;
  8242. } else if (!mg_strncasecmp(
  8243. conn->request_info.request_method, "HTTP/", 5)) {
  8244. /* Response without content length set */
  8245. conn->content_len = -1;
  8246. } else {
  8247. /* Other request */
  8248. conn->content_len = 0;
  8249. }
  8250. }
  8251. return 1;
  8252. }
  8253. int mg_get_response(struct mg_connection *conn,
  8254. char *ebuf,
  8255. size_t ebuf_len,
  8256. int timeout)
  8257. {
  8258. if (conn) {
  8259. /* Implementation of API function for HTTP clients */
  8260. int err, ret;
  8261. struct mg_context *octx = conn->ctx;
  8262. struct mg_context rctx = *(conn->ctx);
  8263. char txt[32];
  8264. if (timeout >= 0) {
  8265. snprintf(txt, sizeof(txt), "%i", timeout);
  8266. rctx.config[REQUEST_TIMEOUT] = txt;
  8267. set_sock_timeout(conn->client.sock, timeout);
  8268. } else {
  8269. rctx.config[REQUEST_TIMEOUT] = NULL;
  8270. }
  8271. conn->ctx = &rctx;
  8272. ret = getreq(conn, ebuf, ebuf_len, &err);
  8273. conn->ctx = octx;
  8274. /* TODO (mid): Define proper return values - maybe return length?
  8275. * For the first test use <0 for error and >0 for OK */
  8276. return (ret == 0) ? -1 : +1;
  8277. }
  8278. return -1;
  8279. }
  8280. struct mg_connection *mg_download(const char *host,
  8281. int port,
  8282. int use_ssl,
  8283. char *ebuf,
  8284. size_t ebuf_len,
  8285. const char *fmt,
  8286. ...)
  8287. {
  8288. struct mg_connection *conn;
  8289. va_list ap;
  8290. int i;
  8291. int reqerr;
  8292. va_start(ap, fmt);
  8293. ebuf[0] = '\0';
  8294. /* open a connection */
  8295. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  8296. if (conn != NULL) {
  8297. i = mg_vprintf(conn, fmt, ap);
  8298. if (i <= 0) {
  8299. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  8300. } else {
  8301. getreq(conn, ebuf, ebuf_len, &reqerr);
  8302. }
  8303. }
  8304. /* if an error occured, close the connection */
  8305. if (ebuf[0] != '\0' && conn != NULL) {
  8306. mg_close_connection(conn);
  8307. conn = NULL;
  8308. }
  8309. va_end(ap);
  8310. return conn;
  8311. }
  8312. struct websocket_client_thread_data {
  8313. struct mg_connection *conn;
  8314. mg_websocket_data_handler data_handler;
  8315. mg_websocket_close_handler close_handler;
  8316. void *callback_data;
  8317. };
  8318. #if defined(USE_WEBSOCKET)
  8319. #ifdef _WIN32
  8320. static unsigned __stdcall websocket_client_thread(void *data)
  8321. #else
  8322. static void *websocket_client_thread(void *data)
  8323. #endif
  8324. {
  8325. struct websocket_client_thread_data *cdata =
  8326. (struct websocket_client_thread_data *)data;
  8327. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  8328. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  8329. if (cdata->close_handler != NULL) {
  8330. cdata->close_handler(cdata->conn, cdata->callback_data);
  8331. }
  8332. mg_free((void *)cdata);
  8333. #ifdef _WIN32
  8334. return 0;
  8335. #else
  8336. return NULL;
  8337. #endif
  8338. }
  8339. #endif
  8340. struct mg_connection *
  8341. mg_connect_websocket_client(const char *host,
  8342. int port,
  8343. int use_ssl,
  8344. char *error_buffer,
  8345. size_t error_buffer_size,
  8346. const char *path,
  8347. const char *origin,
  8348. mg_websocket_data_handler data_func,
  8349. mg_websocket_close_handler close_func,
  8350. void *user_data)
  8351. {
  8352. struct mg_connection *conn = NULL;
  8353. #if defined(USE_WEBSOCKET)
  8354. struct mg_context *newctx = NULL;
  8355. struct websocket_client_thread_data *thread_data;
  8356. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  8357. static const char *handshake_req;
  8358. if (origin != NULL) {
  8359. handshake_req = "GET %s HTTP/1.1\r\n"
  8360. "Host: %s\r\n"
  8361. "Upgrade: websocket\r\n"
  8362. "Connection: Upgrade\r\n"
  8363. "Sec-WebSocket-Key: %s\r\n"
  8364. "Sec-WebSocket-Version: 13\r\n"
  8365. "Origin: %s\r\n"
  8366. "\r\n";
  8367. } else {
  8368. handshake_req = "GET %s HTTP/1.1\r\n"
  8369. "Host: %s\r\n"
  8370. "Upgrade: websocket\r\n"
  8371. "Connection: Upgrade\r\n"
  8372. "Sec-WebSocket-Key: %s\r\n"
  8373. "Sec-WebSocket-Version: 13\r\n"
  8374. "\r\n";
  8375. }
  8376. /* Establish the client connection and request upgrade */
  8377. conn = mg_download(host,
  8378. port,
  8379. use_ssl,
  8380. error_buffer,
  8381. error_buffer_size,
  8382. handshake_req,
  8383. path,
  8384. host,
  8385. magic,
  8386. origin);
  8387. /* Connection object will be null if something goes wrong */
  8388. if (conn == NULL || (strcmp(conn->request_info.uri, "101") != 0)) {
  8389. if (!*error_buffer) {
  8390. /* if there is a connection, but it did not return 101,
  8391. * error_buffer is not yet set */
  8392. mg_snprintf(conn,
  8393. error_buffer,
  8394. error_buffer_size,
  8395. "Unexpected server reply");
  8396. }
  8397. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  8398. if (conn != NULL) {
  8399. mg_free(conn);
  8400. conn = NULL;
  8401. }
  8402. return conn;
  8403. }
  8404. /* For client connections, mg_context is fake. Since we need to set a
  8405. * callback function, we need to create a copy and modify it. */
  8406. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  8407. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  8408. newctx->user_data = user_data;
  8409. newctx->context_type = 2; /* client context type */
  8410. newctx->workerthreadcount = 1; /* one worker thread will be created */
  8411. newctx->workerthreadids =
  8412. (pthread_t *)mg_calloc(newctx->workerthreadcount, sizeof(pthread_t));
  8413. conn->ctx = newctx;
  8414. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  8415. sizeof(struct websocket_client_thread_data), 1);
  8416. thread_data->conn = conn;
  8417. thread_data->data_handler = data_func;
  8418. thread_data->close_handler = close_func;
  8419. thread_data->callback_data = NULL;
  8420. /* Start a thread to read the websocket client connection
  8421. * This thread will automatically stop when mg_disconnect is
  8422. * called on the client connection */
  8423. if (mg_start_thread_with_id(websocket_client_thread,
  8424. (void *)thread_data,
  8425. newctx->workerthreadids) != 0) {
  8426. mg_free((void *)thread_data);
  8427. mg_free((void *)newctx->workerthreadids);
  8428. mg_free((void *)newctx);
  8429. mg_free((void *)conn);
  8430. conn = NULL;
  8431. DEBUG_TRACE("%s",
  8432. "Websocket client connect thread could not be started\r\n");
  8433. }
  8434. #else
  8435. /* Appease "unused parameter" warnings */
  8436. (void)host;
  8437. (void)port;
  8438. (void)use_ssl;
  8439. (void)error_buffer;
  8440. (void)error_buffer_size;
  8441. (void)path;
  8442. (void)origin;
  8443. (void)user_data;
  8444. (void)data_func;
  8445. (void)close_func;
  8446. #endif
  8447. return conn;
  8448. }
  8449. static void process_new_connection(struct mg_connection *conn)
  8450. {
  8451. if (conn && conn->ctx) {
  8452. struct mg_request_info *ri = &conn->request_info;
  8453. int keep_alive_enabled, keep_alive, discard_len;
  8454. char ebuf[100];
  8455. int reqerr;
  8456. keep_alive_enabled =
  8457. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  8458. /* Important: on new connection, reset the receiving buffer. Credit
  8459. * goes to crule42. */
  8460. conn->data_len = 0;
  8461. do {
  8462. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  8463. /* The request sent by the client could not be understood by
  8464. * the server, or it was incomplete or a timeout. Send an
  8465. * error message and close the connection. */
  8466. if (reqerr > 0) {
  8467. /*assert(ebuf[0] != '\0');*/
  8468. send_http_error(conn, reqerr, "%s", ebuf);
  8469. }
  8470. } else if (!is_valid_uri(conn->request_info.uri)) {
  8471. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  8472. send_http_error(conn, 400, "%s", ebuf);
  8473. } else if (strcmp(ri->http_version, "1.0") &&
  8474. strcmp(ri->http_version, "1.1")) {
  8475. snprintf(ebuf,
  8476. sizeof(ebuf),
  8477. "Bad HTTP version: [%s]",
  8478. ri->http_version);
  8479. send_http_error(conn, 505, "%s", ebuf);
  8480. }
  8481. if (ebuf[0] == '\0') {
  8482. handle_request(conn);
  8483. if (conn->ctx->callbacks.end_request != NULL) {
  8484. conn->ctx->callbacks.end_request(conn, conn->status_code);
  8485. }
  8486. log_access(conn);
  8487. } else {
  8488. conn->must_close = 1;
  8489. }
  8490. if (ri->remote_user != NULL) {
  8491. mg_free((void *)ri->remote_user);
  8492. /* Important! When having connections with and without auth
  8493. * would cause double free and then crash */
  8494. ri->remote_user = NULL;
  8495. }
  8496. /* NOTE(lsm): order is important here. should_keep_alive() call is
  8497. * using parsed request, which will be invalid after memmove's
  8498. * below.
  8499. * Therefore, memorize should_keep_alive() result now for later use
  8500. * in loop exit condition. */
  8501. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  8502. conn->content_len >= 0 && should_keep_alive(conn);
  8503. /* Discard all buffered data for this request */
  8504. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  8505. conn->request_len + conn->content_len <
  8506. (int64_t)conn->data_len
  8507. ? (int)(conn->request_len + conn->content_len)
  8508. : conn->data_len;
  8509. /*assert(discard_len >= 0);*/
  8510. if (discard_len < 0)
  8511. break;
  8512. conn->data_len -= discard_len;
  8513. if (conn->data_len > 0) {
  8514. memmove(
  8515. conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  8516. }
  8517. /* assert(conn->data_len >= 0); */
  8518. /* assert(conn->data_len <= conn->buf_size); */
  8519. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  8520. break;
  8521. }
  8522. } while (keep_alive);
  8523. }
  8524. }
  8525. /* Worker threads take accepted socket from the queue */
  8526. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  8527. {
  8528. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8529. if (!ctx) {
  8530. return 0;
  8531. }
  8532. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8533. DEBUG_TRACE("%s", "going idle");
  8534. /* If the queue is empty, wait. We're idle at this point. */
  8535. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  8536. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  8537. }
  8538. /* If we're stopping, sq_head may be equal to sq_tail. */
  8539. if (ctx->sq_head > ctx->sq_tail) {
  8540. /* Copy socket from the queue and increment tail */
  8541. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  8542. ctx->sq_tail++;
  8543. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  8544. /* Wrap pointers if needed */
  8545. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  8546. ctx->sq_tail -= QUEUE_SIZE(ctx);
  8547. ctx->sq_head -= QUEUE_SIZE(ctx);
  8548. }
  8549. }
  8550. (void)pthread_cond_signal(&ctx->sq_empty);
  8551. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8552. return !ctx->stop_flag;
  8553. #undef QUEUE_SIZE
  8554. }
  8555. static void *worker_thread_run(void *thread_func_param)
  8556. {
  8557. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8558. struct mg_connection *conn;
  8559. struct mg_workerTLS tls;
  8560. uint32_t addr;
  8561. mg_set_thread_name("worker");
  8562. tls.is_master = 0;
  8563. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8564. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8565. #endif
  8566. conn =
  8567. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  8568. if (conn == NULL) {
  8569. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  8570. } else {
  8571. pthread_setspecific(sTlsKey, &tls);
  8572. conn->buf_size = MAX_REQUEST_SIZE;
  8573. conn->buf = (char *)(conn + 1);
  8574. conn->ctx = ctx;
  8575. conn->request_info.user_data = ctx->user_data;
  8576. /* Allocate a mutex for this connection to allow communication both
  8577. * within the request handler and from elsewhere in the application */
  8578. (void)pthread_mutex_init(&conn->mutex, NULL);
  8579. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  8580. * signal sq_empty condvar to wake up the master waiting in
  8581. * produce_socket() */
  8582. while (consume_socket(ctx, &conn->client)) {
  8583. conn->conn_birth_time = time(NULL);
  8584. /* Fill in IP, port info early so even if SSL setup below fails,
  8585. * error handler would have the corresponding info.
  8586. * Thanks to Johannes Winkelmann for the patch.
  8587. * TODO(lsm, high): Fix IPv6 case */
  8588. conn->request_info.remote_port =
  8589. ntohs(conn->client.rsa.sin.sin_port);
  8590. sockaddr_to_string(conn->request_info.remote_addr,
  8591. sizeof(conn->request_info.remote_addr),
  8592. &conn->client.rsa);
  8593. /* TODO: #if defined(MG_LEGACY_INTERFACE) */
  8594. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  8595. memcpy(&conn->request_info.remote_ip, &addr, 4);
  8596. /* #endif */
  8597. conn->request_info.is_ssl = conn->client.is_ssl;
  8598. if (!conn->client.is_ssl
  8599. #ifndef NO_SSL
  8600. ||
  8601. sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  8602. #endif
  8603. ) {
  8604. process_new_connection(conn);
  8605. }
  8606. close_connection(conn);
  8607. }
  8608. }
  8609. /* Signal master that we're done with connection and exiting */
  8610. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8611. ctx->num_threads--;
  8612. (void)pthread_cond_signal(&ctx->thread_cond);
  8613. /* assert(ctx->num_threads >= 0); */
  8614. if (ctx->num_threads < 0) {
  8615. return NULL;
  8616. }
  8617. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8618. pthread_setspecific(sTlsKey, NULL);
  8619. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8620. CloseHandle(tls.pthread_cond_helper_mutex);
  8621. #endif
  8622. mg_free(conn);
  8623. DEBUG_TRACE("%s", "exiting");
  8624. return NULL;
  8625. }
  8626. /* Threads have different return types on Windows and Unix. */
  8627. #ifdef _WIN32
  8628. static unsigned __stdcall worker_thread(void *thread_func_param)
  8629. {
  8630. worker_thread_run(thread_func_param);
  8631. return 0;
  8632. }
  8633. #else
  8634. static void *worker_thread(void *thread_func_param)
  8635. {
  8636. worker_thread_run(thread_func_param);
  8637. return NULL;
  8638. }
  8639. #endif /* _WIN32 */
  8640. /* Master thread adds accepted socket to a queue */
  8641. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  8642. {
  8643. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8644. if (!ctx) {
  8645. return;
  8646. }
  8647. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8648. /* If the queue is full, wait */
  8649. while (ctx->stop_flag == 0 &&
  8650. ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  8651. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  8652. }
  8653. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  8654. /* Copy socket to the queue and increment head */
  8655. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  8656. ctx->sq_head++;
  8657. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  8658. }
  8659. (void)pthread_cond_signal(&ctx->sq_full);
  8660. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8661. #undef QUEUE_SIZE
  8662. }
  8663. static void accept_new_connection(const struct socket *listener,
  8664. struct mg_context *ctx)
  8665. {
  8666. struct socket so;
  8667. char src_addr[IP_ADDR_STR_LEN];
  8668. socklen_t len = sizeof(so.rsa);
  8669. int on = 1;
  8670. int timeout;
  8671. if (!listener) {
  8672. return;
  8673. }
  8674. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  8675. INVALID_SOCKET) {
  8676. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  8677. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  8678. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  8679. closesocket(so.sock);
  8680. so.sock = INVALID_SOCKET;
  8681. } else {
  8682. /* Put so socket structure into the queue */
  8683. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  8684. set_close_on_exec(so.sock, fc(ctx));
  8685. so.is_ssl = listener->is_ssl;
  8686. so.ssl_redir = listener->ssl_redir;
  8687. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  8688. mg_cry(fc(ctx),
  8689. "%s: getsockname() failed: %s",
  8690. __func__,
  8691. strerror(ERRNO));
  8692. }
  8693. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  8694. * is enabled, and client resets the connection, server won't get
  8695. * TCP FIN or RST and will keep the connection open forever. With TCP
  8696. * keep-alive, next keep-alive handshake will figure out that the
  8697. * client is down and will close the server end.
  8698. * Thanks to Igor Klopov who suggested the patch. */
  8699. if (setsockopt(so.sock,
  8700. SOL_SOCKET,
  8701. SO_KEEPALIVE,
  8702. (SOCK_OPT_TYPE)&on,
  8703. sizeof(on)) != 0) {
  8704. mg_cry(fc(ctx),
  8705. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  8706. __func__,
  8707. strerror(ERRNO));
  8708. }
  8709. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  8710. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  8711. } else {
  8712. timeout = -1;
  8713. }
  8714. /* Set socket timeout to the given value, but not more than a
  8715. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  8716. * so the server can exit after that time if requested. */
  8717. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  8718. set_sock_timeout(so.sock, timeout);
  8719. } else {
  8720. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  8721. }
  8722. produce_socket(ctx, &so);
  8723. }
  8724. }
  8725. static void master_thread_run(void *thread_func_param)
  8726. {
  8727. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8728. struct mg_workerTLS tls;
  8729. struct pollfd *pfd;
  8730. unsigned int i;
  8731. unsigned int workerthreadcount;
  8732. if (!ctx) {
  8733. return;
  8734. }
  8735. mg_set_thread_name("master");
  8736. /* Increase priority of the master thread */
  8737. #if defined(_WIN32)
  8738. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  8739. #elif defined(USE_MASTER_THREAD_PRIORITY)
  8740. int min_prio = sched_get_priority_min(SCHED_RR);
  8741. int max_prio = sched_get_priority_max(SCHED_RR);
  8742. if ((min_prio >= 0) && (max_prio >= 0) &&
  8743. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  8744. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  8745. struct sched_param sched_param = {0};
  8746. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  8747. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  8748. }
  8749. #endif
  8750. /* Initialize thread local storage */
  8751. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8752. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8753. #endif
  8754. tls.is_master = 1;
  8755. pthread_setspecific(sTlsKey, &tls);
  8756. /* Server starts *now* */
  8757. ctx->start_time = (unsigned long)time(NULL);
  8758. /* Allocate memory for the listening sockets, and start the server */
  8759. pfd =
  8760. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  8761. while (pfd != NULL && ctx->stop_flag == 0) {
  8762. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8763. pfd[i].fd = ctx->listening_sockets[i].sock;
  8764. pfd[i].events = POLLIN;
  8765. }
  8766. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  8767. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8768. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  8769. * successful poll, and POLLIN is defined as
  8770. * (POLLRDNORM | POLLRDBAND)
  8771. * Therefore, we're checking pfd[i].revents & POLLIN, not
  8772. * pfd[i].revents == POLLIN. */
  8773. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  8774. accept_new_connection(&ctx->listening_sockets[i], ctx);
  8775. }
  8776. }
  8777. }
  8778. }
  8779. mg_free(pfd);
  8780. DEBUG_TRACE("%s", "stopping workers");
  8781. /* Stop signal received: somebody called mg_stop. Quit. */
  8782. close_all_listening_sockets(ctx);
  8783. /* Wakeup workers that are waiting for connections to handle. */
  8784. pthread_cond_broadcast(&ctx->sq_full);
  8785. /* Wait until all threads finish */
  8786. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8787. while (ctx->num_threads > 0) {
  8788. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  8789. }
  8790. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8791. /* Join all worker threads to avoid leaking threads. */
  8792. workerthreadcount = ctx->workerthreadcount;
  8793. for (i = 0; i < workerthreadcount; i++) {
  8794. mg_join_thread(ctx->workerthreadids[i]);
  8795. }
  8796. #if !defined(NO_SSL)
  8797. if (ctx->ssl_ctx != NULL) {
  8798. uninitialize_ssl(ctx);
  8799. }
  8800. #endif
  8801. DEBUG_TRACE("%s", "exiting");
  8802. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8803. CloseHandle(tls.pthread_cond_helper_mutex);
  8804. #endif
  8805. pthread_setspecific(sTlsKey, NULL);
  8806. /* Signal mg_stop() that we're done.
  8807. * WARNING: This must be the very last thing this
  8808. * thread does, as ctx becomes invalid after this line. */
  8809. ctx->stop_flag = 2;
  8810. }
  8811. /* Threads have different return types on Windows and Unix. */
  8812. #ifdef _WIN32
  8813. static unsigned __stdcall master_thread(void *thread_func_param)
  8814. {
  8815. master_thread_run(thread_func_param);
  8816. return 0;
  8817. }
  8818. #else
  8819. static void *master_thread(void *thread_func_param)
  8820. {
  8821. master_thread_run(thread_func_param);
  8822. return NULL;
  8823. }
  8824. #endif /* _WIN32 */
  8825. static void free_context(struct mg_context *ctx)
  8826. {
  8827. int i;
  8828. struct mg_request_handler_info *tmp_rh;
  8829. if (ctx == NULL) {
  8830. return;
  8831. }
  8832. if (ctx->callbacks.exit_context) {
  8833. ctx->callbacks.exit_context(ctx);
  8834. }
  8835. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  8836. */
  8837. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  8838. (void)pthread_cond_destroy(&ctx->thread_cond);
  8839. (void)pthread_cond_destroy(&ctx->sq_empty);
  8840. (void)pthread_cond_destroy(&ctx->sq_full);
  8841. /* Destroy other context global data structures mutex */
  8842. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  8843. #if defined(USE_TIMERS)
  8844. timers_exit(ctx);
  8845. #endif
  8846. /* Deallocate config parameters */
  8847. for (i = 0; i < NUM_OPTIONS; i++) {
  8848. if (ctx->config[i] != NULL) {
  8849. #if defined(_MSC_VER)
  8850. #pragma warning(suppress : 6001)
  8851. #endif
  8852. mg_free(ctx->config[i]);
  8853. }
  8854. }
  8855. /* Deallocate request handlers */
  8856. while (ctx->request_handlers) {
  8857. tmp_rh = ctx->request_handlers;
  8858. ctx->request_handlers = tmp_rh->next;
  8859. mg_free(tmp_rh->uri);
  8860. mg_free(tmp_rh);
  8861. }
  8862. #ifndef NO_SSL
  8863. /* Deallocate SSL context */
  8864. if (ctx->ssl_ctx != NULL) {
  8865. SSL_CTX_free(ctx->ssl_ctx);
  8866. }
  8867. if (ssl_mutexes != NULL) {
  8868. mg_free(ssl_mutexes);
  8869. ssl_mutexes = NULL;
  8870. }
  8871. #endif /* !NO_SSL */
  8872. /* Deallocate worker thread ID array */
  8873. if (ctx->workerthreadids != NULL) {
  8874. mg_free(ctx->workerthreadids);
  8875. }
  8876. /* Deallocate the tls variable */
  8877. if (mg_atomic_dec(&sTlsInit) == 0) {
  8878. pthread_key_delete(sTlsKey);
  8879. }
  8880. /* deallocate system name string */
  8881. mg_free(ctx->systemName);
  8882. /* Deallocate context itself */
  8883. mg_free(ctx);
  8884. }
  8885. void mg_stop(struct mg_context *ctx)
  8886. {
  8887. if (!ctx) {
  8888. return;
  8889. }
  8890. ctx->stop_flag = 1;
  8891. /* Wait until mg_fini() stops */
  8892. while (ctx->stop_flag != 2) {
  8893. (void)mg_sleep(10);
  8894. }
  8895. mg_join_thread(ctx->masterthreadid);
  8896. free_context(ctx);
  8897. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8898. (void)WSACleanup();
  8899. #endif /* _WIN32 && !__SYMBIAN32__ */
  8900. }
  8901. static void get_system_name(char **sysName)
  8902. {
  8903. #if defined(_WIN32)
  8904. #if !defined(__SYMBIAN32__)
  8905. char name[128];
  8906. DWORD dwVersion = 0;
  8907. DWORD dwMajorVersion = 0;
  8908. DWORD dwMinorVersion = 0;
  8909. DWORD dwBuild = 0;
  8910. #ifdef _MSC_VER
  8911. #pragma warning(push)
  8912. // GetVersion was declared deprecated
  8913. #pragma warning(disable : 4996)
  8914. #endif
  8915. dwVersion = GetVersion();
  8916. #ifdef _MSC_VER
  8917. #pragma warning(pop)
  8918. #endif
  8919. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  8920. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  8921. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  8922. (void)dwBuild;
  8923. sprintf(name,
  8924. "Windows %u.%u",
  8925. (unsigned)dwMajorVersion,
  8926. (unsigned)dwMinorVersion);
  8927. *sysName = mg_strdup(name);
  8928. #else
  8929. *sysName = mg_strdup("Symbian");
  8930. #endif
  8931. #else
  8932. struct utsname name;
  8933. memset(&name, 0, sizeof(name));
  8934. uname(&name);
  8935. *sysName = mg_strdup(name.sysname);
  8936. #endif
  8937. }
  8938. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  8939. void *user_data,
  8940. const char **options)
  8941. {
  8942. struct mg_context *ctx;
  8943. const char *name, *value, *default_value;
  8944. int idx, ok, workerthreadcount;
  8945. unsigned int i;
  8946. void (*exit_callback)(const struct mg_context *ctx) = 0;
  8947. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8948. WSADATA data;
  8949. WSAStartup(MAKEWORD(2, 2), &data);
  8950. #if defined(_MSC_VER)
  8951. #pragma warning(suppress : 28125)
  8952. #endif
  8953. if (!sTlsInit) {
  8954. InitializeCriticalSection(&global_log_file_lock);
  8955. }
  8956. #endif /* _WIN32 && !__SYMBIAN32__ */
  8957. /* Allocate context and initialize reasonable general case defaults. */
  8958. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  8959. return NULL;
  8960. }
  8961. if (mg_atomic_inc(&sTlsInit) == 1) {
  8962. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  8963. /* Fatal error - abort start. However, this situation should never
  8964. * occur in practice. */
  8965. mg_atomic_dec(&sTlsInit);
  8966. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  8967. mg_free(ctx);
  8968. return NULL;
  8969. }
  8970. } else {
  8971. /* TODO (low): istead of sleeping, check if sTlsKey is already
  8972. * initialized. */
  8973. mg_sleep(1);
  8974. }
  8975. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  8976. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  8977. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  8978. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  8979. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  8980. if (!ok) {
  8981. /* Fatal error - abort start. However, this situation should never
  8982. * occur in practice. */
  8983. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  8984. mg_free(ctx);
  8985. return NULL;
  8986. }
  8987. if (callbacks) {
  8988. ctx->callbacks = *callbacks;
  8989. exit_callback = callbacks->exit_context;
  8990. ctx->callbacks.exit_context = 0;
  8991. }
  8992. ctx->user_data = user_data;
  8993. ctx->request_handlers = NULL;
  8994. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8995. ctx->shared_lua_websockets = 0;
  8996. #endif
  8997. while (options && (name = *options++) != NULL) {
  8998. if ((idx = get_option_index(name)) == -1) {
  8999. mg_cry(fc(ctx), "Invalid option: %s", name);
  9000. free_context(ctx);
  9001. return NULL;
  9002. } else if ((value = *options++) == NULL) {
  9003. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  9004. free_context(ctx);
  9005. return NULL;
  9006. }
  9007. if (ctx->config[idx] != NULL) {
  9008. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  9009. mg_free(ctx->config[idx]);
  9010. }
  9011. ctx->config[idx] = mg_strdup(value);
  9012. DEBUG_TRACE("[%s] -> [%s]", name, value);
  9013. }
  9014. /* Set default value if needed */
  9015. for (i = 0; config_options[i].name != NULL; i++) {
  9016. default_value = config_options[i].default_value;
  9017. if (ctx->config[i] == NULL && default_value != NULL) {
  9018. ctx->config[i] = mg_strdup(default_value);
  9019. }
  9020. }
  9021. #if defined(NO_FILES)
  9022. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  9023. mg_cry(fc(ctx), "%s", "Document root must not be set");
  9024. free_context(ctx);
  9025. return NULL;
  9026. }
  9027. #endif
  9028. get_system_name(&ctx->systemName);
  9029. /* NOTE(lsm): order is important here. SSL certificates must
  9030. * be initialized before listening ports. UID must be set last. */
  9031. if (!set_gpass_option(ctx) ||
  9032. #if !defined(NO_SSL)
  9033. !set_ssl_option(ctx) ||
  9034. #endif
  9035. !set_ports_option(ctx) ||
  9036. #if !defined(_WIN32)
  9037. !set_uid_option(ctx) ||
  9038. #endif
  9039. !set_acl_option(ctx)) {
  9040. free_context(ctx);
  9041. return NULL;
  9042. }
  9043. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  9044. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  9045. * won't kill the whole process. */
  9046. (void)signal(SIGPIPE, SIG_IGN);
  9047. #endif /* !_WIN32 && !__SYMBIAN32__ */
  9048. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  9049. if (workerthreadcount > MAX_WORKER_THREADS) {
  9050. mg_cry(fc(ctx), "Too many worker threads");
  9051. free_context(ctx);
  9052. return NULL;
  9053. }
  9054. if (workerthreadcount > 0) {
  9055. ctx->workerthreadcount = ((unsigned int)(workerthreadcount));
  9056. ctx->workerthreadids =
  9057. (pthread_t *)mg_calloc(ctx->workerthreadcount, sizeof(pthread_t));
  9058. if (ctx->workerthreadids == NULL) {
  9059. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  9060. free_context(ctx);
  9061. return NULL;
  9062. }
  9063. }
  9064. #if defined(USE_TIMERS)
  9065. if (timers_init(ctx) != 0) {
  9066. mg_cry(fc(ctx), "Error creating timers");
  9067. free_context(ctx);
  9068. return NULL;
  9069. }
  9070. #endif
  9071. /* Context has been created - init user libraries */
  9072. if (ctx->callbacks.init_context) {
  9073. ctx->callbacks.init_context(ctx);
  9074. }
  9075. ctx->callbacks.exit_context = exit_callback;
  9076. ctx->context_type = 1; /* server context */
  9077. /* Start master (listening) thread */
  9078. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  9079. /* Start worker threads */
  9080. for (i = 0; i < ctx->workerthreadcount; i++) {
  9081. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9082. ctx->num_threads++;
  9083. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9084. if (mg_start_thread_with_id(
  9085. worker_thread, ctx, &ctx->workerthreadids[i]) != 0) {
  9086. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9087. ctx->num_threads--;
  9088. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9089. if (i > 0) {
  9090. mg_cry(fc(ctx),
  9091. "Cannot start worker thread %i: error %ld",
  9092. i + 1,
  9093. (long)ERRNO);
  9094. } else {
  9095. mg_cry(
  9096. fc(ctx), "Cannot create threads: error %ld", (long)ERRNO);
  9097. free_context(ctx);
  9098. return NULL;
  9099. }
  9100. break;
  9101. }
  9102. }
  9103. return ctx;
  9104. }