civetweb.c 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273
  1. /* Copyright (c) 2004-2013 Sergey Lyubka
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. * THE SOFTWARE.
  20. */
  21. #if defined(_WIN32)
  22. #if !defined(_CRT_SECURE_NO_WARNINGS)
  23. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  24. #endif
  25. #else
  26. #ifdef __linux__
  27. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  28. #endif
  29. #define _LARGEFILE_SOURCE /* Enable 64-bit file offsets */
  30. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  31. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  32. #endif
  33. #if defined (_MSC_VER)
  34. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  35. #pragma warning (disable : 4306 )
  36. /* conditional expression is constant: introduced by FD_SET(..) */
  37. #pragma warning (disable : 4127)
  38. /* non-constant aggregate initializer: issued due to missing C99 support */
  39. #pragma warning (disable : 4204)
  40. #endif
  41. /* Disable WIN32_LEAN_AND_MEAN.
  42. This makes windows.h always include winsock2.h */
  43. #if defined(WIN32_LEAN_AND_MEAN) && (_MSC_VER <= 1400)
  44. #undef WIN32_LEAN_AND_MEAN
  45. #endif
  46. #if defined USE_IPV6 && defined(_WIN32)
  47. #include <ws2tcpip.h>
  48. #endif
  49. #if defined(__SYMBIAN32__)
  50. #define NO_SSL /* SSL is not supported */
  51. #define NO_CGI /* CGI is not supported */
  52. #define PATH_MAX FILENAME_MAX
  53. #endif /* __SYMBIAN32__ */
  54. #ifndef IGNORE_UNUSED_RESULT
  55. #define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
  56. #endif
  57. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  58. #include <sys/types.h>
  59. #include <sys/stat.h>
  60. #include <errno.h>
  61. #include <signal.h>
  62. #include <fcntl.h>
  63. #endif /* !_WIN32_WCE */
  64. #include <time.h>
  65. #include <stdlib.h>
  66. #include <stdarg.h>
  67. #include <assert.h>
  68. #include <string.h>
  69. #include <ctype.h>
  70. #include <limits.h>
  71. #include <stddef.h>
  72. #include <stdio.h>
  73. #define MAX_WORKER_THREADS 1024
  74. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  75. #if defined(_MSC_VER) && _MSC_VER <= 1400
  76. #undef _WIN32_WINNT
  77. #define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
  78. #endif
  79. #include <windows.h>
  80. #ifndef PATH_MAX
  81. #define PATH_MAX MAX_PATH
  82. #endif
  83. #ifndef _WIN32_WCE
  84. #include <process.h>
  85. #include <direct.h>
  86. #include <io.h>
  87. #else /* _WIN32_WCE */
  88. #define NO_CGI /* WinCE has no pipes */
  89. typedef long off_t;
  90. #define errno GetLastError()
  91. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  92. #endif /* _WIN32_WCE */
  93. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  94. ((uint64_t)((uint32_t)(hi))) << 32))
  95. #define RATE_DIFF 10000000 /* 100 nsecs */
  96. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  97. #define SYS2UNIX_TIME(lo, hi) \
  98. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  99. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  100. The rest of MS compilers use __FUNCTION__, not C99 __func__
  101. Also use _strtoui64 on modern M$ compilers */
  102. #if defined(_MSC_VER) && _MSC_VER < 1300
  103. #define STRX(x) #x
  104. #define STR(x) STRX(x)
  105. #define __func__ __FILE__ ":" STR(__LINE__)
  106. #define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
  107. #define strtoll(x, y, z) _atoi64(x)
  108. #else
  109. #define __func__ __FUNCTION__
  110. #define strtoull(x, y, z) _strtoui64(x, y, z)
  111. #define strtoll(x, y, z) _strtoi64(x, y, z)
  112. #endif /* _MSC_VER */
  113. #define ERRNO GetLastError()
  114. #define NO_SOCKLEN_T
  115. #define SSL_LIB "ssleay32.dll"
  116. #define CRYPTO_LIB "libeay32.dll"
  117. #define O_NONBLOCK 0
  118. #if !defined(EWOULDBLOCK)
  119. #define EWOULDBLOCK WSAEWOULDBLOCK
  120. #endif /* !EWOULDBLOCK */
  121. #define _POSIX_
  122. #define INT64_FMT "I64d"
  123. #define WINCDECL __cdecl
  124. #define SHUT_WR 1
  125. #define snprintf _snprintf
  126. #define vsnprintf _vsnprintf
  127. #define mg_sleep(x) Sleep(x)
  128. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  129. #ifndef popen
  130. #define popen(x, y) _popen(x, y)
  131. #endif
  132. #ifndef pclose
  133. #define pclose(x) _pclose(x)
  134. #endif
  135. #define close(x) _close(x)
  136. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  137. #define RTLD_LAZY 0
  138. #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  139. #define fdopen(x, y) _fdopen((x), (y))
  140. #define write(x, y, z) _write((x), (y), (unsigned) z)
  141. #define read(x, y, z) _read((x), (y), (unsigned) z)
  142. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  143. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  144. #define sleep(x) Sleep((x) * 1000)
  145. #define rmdir(x) _rmdir(x)
  146. #if !defined(va_copy)
  147. #define va_copy(x, y) x = y
  148. #endif /* !va_copy MINGW #defines va_copy */
  149. #if !defined(fileno)
  150. #define fileno(x) _fileno(x)
  151. #endif /* !fileno MINGW #defines fileno */
  152. typedef HANDLE pthread_mutex_t;
  153. typedef DWORD pthread_key_t;
  154. typedef HANDLE pthread_t;
  155. typedef struct {
  156. CRITICAL_SECTION threadIdSec;
  157. int waitingthreadcount; /* The number of threads queued. */
  158. pthread_t *waitingthreadhdls; /* The thread handles. */
  159. } pthread_cond_t;
  160. typedef DWORD clockid_t;
  161. #define CLOCK_MONOTONIC (1)
  162. #define CLOCK_REALTIME (2)
  163. struct timespec {
  164. time_t tv_sec; /* seconds */
  165. long tv_nsec; /* nanoseconds */
  166. };
  167. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  168. static int pthread_mutex_lock(pthread_mutex_t *);
  169. static int pthread_mutex_unlock(pthread_mutex_t *);
  170. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  171. struct file;
  172. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  173. #if defined(HAVE_STDINT)
  174. #include <stdint.h>
  175. #else
  176. typedef unsigned int uint32_t;
  177. typedef unsigned short uint16_t;
  178. typedef unsigned __int64 uint64_t;
  179. typedef __int64 int64_t;
  180. #define INT64_MAX 9223372036854775807
  181. #endif /* HAVE_STDINT */
  182. /* POSIX dirent interface */
  183. struct dirent {
  184. char d_name[PATH_MAX];
  185. };
  186. typedef struct DIR {
  187. HANDLE handle;
  188. WIN32_FIND_DATAW info;
  189. struct dirent result;
  190. } DIR;
  191. #if !defined(USE_IPV6) && defined(_WIN32)
  192. #ifndef HAVE_POLL
  193. struct pollfd {
  194. SOCKET fd;
  195. short events;
  196. short revents;
  197. };
  198. #define POLLIN 1
  199. #endif
  200. #endif
  201. /* Mark required libraries */
  202. #ifdef _MSC_VER
  203. #pragma comment(lib, "Ws2_32.lib")
  204. #endif
  205. #else /* UNIX specific */
  206. #include <sys/wait.h>
  207. #include <sys/socket.h>
  208. #include <sys/poll.h>
  209. #include <netinet/in.h>
  210. #include <arpa/inet.h>
  211. #include <sys/time.h>
  212. #include <stdint.h>
  213. #include <inttypes.h>
  214. #include <netdb.h>
  215. #include <pwd.h>
  216. #include <unistd.h>
  217. #include <dirent.h>
  218. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  219. #include <dlfcn.h>
  220. #endif
  221. #include <pthread.h>
  222. #if defined(__MACH__)
  223. #define SSL_LIB "libssl.dylib"
  224. #define CRYPTO_LIB "libcrypto.dylib"
  225. #else
  226. #if !defined(SSL_LIB)
  227. #define SSL_LIB "libssl.so"
  228. #endif
  229. #if !defined(CRYPTO_LIB)
  230. #define CRYPTO_LIB "libcrypto.so"
  231. #endif
  232. #endif
  233. #ifndef O_BINARY
  234. #define O_BINARY 0
  235. #endif /* O_BINARY */
  236. #define closesocket(a) close(a)
  237. #define mg_mkdir(x, y) mkdir(x, y)
  238. #define mg_remove(x) remove(x)
  239. #define mg_sleep(x) usleep((x) * 1000)
  240. #define ERRNO errno
  241. #define INVALID_SOCKET (-1)
  242. #define INT64_FMT PRId64
  243. typedef int SOCKET;
  244. #define WINCDECL
  245. #endif /* End of Windows and UNIX specific includes */
  246. #include "civetweb.h"
  247. #define PASSWORDS_FILE_NAME ".htpasswd"
  248. #define CGI_ENVIRONMENT_SIZE 4096
  249. #define MAX_CGI_ENVIR_VARS 64
  250. #define MG_BUF_LEN 8192
  251. #ifndef MAX_REQUEST_SIZE
  252. #define MAX_REQUEST_SIZE 16384
  253. #endif
  254. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  255. #ifdef _WIN32
  256. static CRITICAL_SECTION global_log_file_lock;
  257. static DWORD pthread_self(void)
  258. {
  259. return GetCurrentThreadId();
  260. }
  261. int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
  262. {
  263. assert(_must_be_zero == NULL);
  264. if ((key!=0) && (_must_be_zero == NULL)) {
  265. *key = TlsAlloc();
  266. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  267. }
  268. return -2;
  269. }
  270. int pthread_key_delete(pthread_key_t key)
  271. {
  272. return TlsFree(key) ? 0 : 1;
  273. }
  274. int pthread_setspecific(pthread_key_t key, void * value)
  275. {
  276. return TlsSetValue(key, value) ? 0 : 1;
  277. }
  278. void *pthread_getspecific(pthread_key_t key)
  279. {
  280. return TlsGetValue(key);
  281. }
  282. #endif /* _WIN32 */
  283. #define MD5_STATIC static
  284. #include "md5.inl"
  285. #ifdef DEBUG_TRACE
  286. #undef DEBUG_TRACE
  287. #define DEBUG_TRACE(x)
  288. #else
  289. #if defined(DEBUG)
  290. #define DEBUG_TRACE(x) do { \
  291. flockfile(stdout); \
  292. printf("*** %lu.%p.%s.%d: ", \
  293. (unsigned long) time(NULL), (void *) pthread_self(), \
  294. __func__, __LINE__); \
  295. printf x; \
  296. putchar('\n'); \
  297. fflush(stdout); \
  298. funlockfile(stdout); \
  299. } while (0)
  300. #else
  301. #define DEBUG_TRACE(x)
  302. #endif /* DEBUG */
  303. #endif /* DEBUG_TRACE */
  304. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  305. #ifdef NO_SOCKLEN_T
  306. typedef int socklen_t;
  307. #endif /* NO_SOCKLEN_T */
  308. #define _DARWIN_UNLIMITED_SELECT
  309. #define IP_ADDR_STR_LEN 50 /* IPv6 hex string is 46 chars */
  310. #if !defined(MSG_NOSIGNAL)
  311. #define MSG_NOSIGNAL 0
  312. #endif
  313. #if !defined(SOMAXCONN)
  314. #define SOMAXCONN 100
  315. #endif
  316. #if !defined(PATH_MAX)
  317. #define PATH_MAX 4096
  318. #endif
  319. /* Size of the accepted socket queue */
  320. #if !defined(MGSQLEN)
  321. #define MGSQLEN 20
  322. #endif
  323. static const char *http_500_error = "Internal Server Error";
  324. #if defined(NO_SSL_DL)
  325. #include <openssl/ssl.h>
  326. #include <openssl/err.h>
  327. #else
  328. /* SSL loaded dynamically from DLL.
  329. I put the prototypes here to be independent from OpenSSL source
  330. installation. */
  331. typedef struct ssl_st SSL;
  332. typedef struct ssl_method_st SSL_METHOD;
  333. typedef struct ssl_ctx_st SSL_CTX;
  334. struct ssl_func {
  335. const char *name; /* SSL function name */
  336. void (*ptr)(void); /* Function pointer */
  337. };
  338. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  339. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  340. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  341. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  342. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  343. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  344. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  345. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  346. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  347. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  348. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  349. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  350. const char *, int)) ssl_sw[11].ptr)
  351. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  352. const char *, int)) ssl_sw[12].ptr)
  353. #define SSL_CTX_set_default_passwd_cb \
  354. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  355. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  356. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  357. #define SSL_CTX_use_certificate_chain_file \
  358. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  359. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  360. #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
  361. #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
  362. #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
  363. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  364. #define CRYPTO_set_locking_callback \
  365. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  366. #define CRYPTO_set_id_callback \
  367. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  368. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  369. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  370. /* set_ssl_option() function updates this array.
  371. It loads SSL library dynamically and changes NULLs to the actual addresses
  372. of respective functions. The macros above (like SSL_connect()) are really
  373. just calling these functions indirectly via the pointer. */
  374. static struct ssl_func ssl_sw[] = {
  375. {"SSL_free", NULL},
  376. {"SSL_accept", NULL},
  377. {"SSL_connect", NULL},
  378. {"SSL_read", NULL},
  379. {"SSL_write", NULL},
  380. {"SSL_get_error", NULL},
  381. {"SSL_set_fd", NULL},
  382. {"SSL_new", NULL},
  383. {"SSL_CTX_new", NULL},
  384. {"SSLv23_server_method", NULL},
  385. {"SSL_library_init", NULL},
  386. {"SSL_CTX_use_PrivateKey_file", NULL},
  387. {"SSL_CTX_use_certificate_file",NULL},
  388. {"SSL_CTX_set_default_passwd_cb",NULL},
  389. {"SSL_CTX_free", NULL},
  390. {"SSL_load_error_strings", NULL},
  391. {"SSL_CTX_use_certificate_chain_file", NULL},
  392. {"SSLv23_client_method", NULL},
  393. {"SSL_pending", NULL},
  394. {"SSL_CTX_set_verify", NULL},
  395. {"SSL_shutdown", NULL},
  396. {NULL, NULL}
  397. };
  398. /* Similar array as ssl_sw. These functions could be located in different
  399. lib. */
  400. #if !defined(NO_SSL)
  401. static struct ssl_func crypto_sw[] = {
  402. {"CRYPTO_num_locks", NULL},
  403. {"CRYPTO_set_locking_callback", NULL},
  404. {"CRYPTO_set_id_callback", NULL},
  405. {"ERR_get_error", NULL},
  406. {"ERR_error_string", NULL},
  407. {NULL, NULL}
  408. };
  409. #endif /* NO_SSL */
  410. #endif /* NO_SSL_DL */
  411. static const char *month_names[] = {
  412. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  413. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  414. };
  415. /* Unified socket address. For IPv6 support, add IPv6 address structure
  416. in the union u. */
  417. union usa {
  418. struct sockaddr sa;
  419. struct sockaddr_in sin;
  420. #if defined(USE_IPV6)
  421. struct sockaddr_in6 sin6;
  422. #endif
  423. };
  424. /* Describes a string (chunk of memory). */
  425. struct vec {
  426. const char *ptr;
  427. size_t len;
  428. };
  429. struct file {
  430. int is_directory;
  431. time_t modification_time;
  432. int64_t size;
  433. FILE *fp;
  434. const char *membuf; /* Non-NULL if file data is in memory */
  435. /* set to 1 if the content is gzipped
  436. in which case we need a content-encoding: gzip header */
  437. int gzipped;
  438. };
  439. #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
  440. /* Describes listening socket, or socket which was accept()-ed by the master
  441. thread and queued for future handling by the worker thread. */
  442. struct socket {
  443. SOCKET sock; /* Listening socket */
  444. union usa lsa; /* Local socket address */
  445. union usa rsa; /* Remote socket address */
  446. unsigned is_ssl:1; /* Is port SSL-ed */
  447. unsigned ssl_redir:1; /* Is port supposed to redirect everything to SSL
  448. port */
  449. };
  450. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  451. enum {
  452. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  453. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  454. ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  455. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  456. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  457. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
  458. NUM_OPTIONS
  459. };
  460. static const char *config_options[] = {
  461. "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  462. "cgi_environment", NULL,
  463. "put_delete_auth_file", NULL,
  464. "cgi_interpreter", NULL,
  465. "protect_uri", NULL,
  466. "authentication_domain", "mydomain.com",
  467. "ssi_pattern", "**.shtml$|**.shtm$",
  468. "throttle", NULL,
  469. "access_log_file", NULL,
  470. "enable_directory_listing", "yes",
  471. "error_log_file", NULL,
  472. "global_auth_file", NULL,
  473. "index_files",
  474. "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",
  475. "enable_keep_alive", "no",
  476. "access_control_list", NULL,
  477. "extra_mime_types", NULL,
  478. "listening_ports", "8080",
  479. "document_root", NULL,
  480. "ssl_certificate", NULL,
  481. "num_threads", "50",
  482. "run_as_user", NULL,
  483. "url_rewrite_patterns", NULL,
  484. "hide_files_patterns", NULL,
  485. "request_timeout_ms", "30000",
  486. NULL
  487. };
  488. struct mg_request_handler_info {
  489. char *uri;
  490. size_t uri_len;
  491. mg_request_handler handler;
  492. void *cbdata;
  493. struct mg_request_handler_info *next;
  494. };
  495. struct mg_context {
  496. volatile int stop_flag; /* Should we stop event loop */
  497. void *ssllib_dll_handle; /* Store the ssl library handle. */
  498. void *cryptolib_dll_handle; /* Store the crypto library handle. */
  499. SSL_CTX *ssl_ctx; /* SSL context */
  500. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  501. struct mg_callbacks callbacks; /* User-defined callback function */
  502. void *user_data; /* User-defined data */
  503. struct socket *listening_sockets;
  504. int num_listening_sockets;
  505. volatile int num_threads; /* Number of threads */
  506. pthread_mutex_t mutex; /* Protects (max|num)_threads */
  507. pthread_cond_t cond; /* Condvar for tracking workers terminations */
  508. struct socket queue[MGSQLEN]; /* Accepted sockets */
  509. volatile int sq_head; /* Head of the socket queue */
  510. volatile int sq_tail; /* Tail of the socket queue */
  511. pthread_cond_t sq_full; /* Signaled when socket is produced */
  512. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  513. pthread_t masterthreadid; /* The master thread ID. */
  514. int workerthreadcount; /* The amount of worker threads. */
  515. pthread_t *workerthreadids;/* The worker thread IDs. */
  516. /* linked list of uri handlers */
  517. struct mg_request_handler_info *request_handlers;
  518. };
  519. struct mg_connection {
  520. struct mg_request_info request_info;
  521. struct mg_context *ctx;
  522. SSL *ssl; /* SSL descriptor */
  523. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  524. struct socket client; /* Connected client */
  525. time_t birth_time; /* Time when request was received */
  526. int64_t num_bytes_sent; /* Total bytes sent to client */
  527. int64_t content_len; /* Content-Length header value */
  528. int64_t consumed_content; /* How many bytes of content have been read */
  529. char *buf; /* Buffer for received data */
  530. char *path_info; /* PATH_INFO part of the URL */
  531. int must_close; /* 1 if connection must be closed */
  532. int buf_size; /* Buffer size */
  533. int request_len; /* Size of the request + headers in a buffer */
  534. int data_len; /* Total size of data in a buffer */
  535. int status_code; /* HTTP reply status code, e.g. 200 */
  536. int throttle; /* Throttling, bytes/sec. <= 0 means no
  537. throttle */
  538. time_t last_throttle_time; /* Last time throttled data was sent */
  539. int64_t last_throttle_bytes;/* Bytes sent this second */
  540. pthread_mutex_t mutex; /* Used by mg_lock/mg_unlock to ensure atomic
  541. transmissions for websockets */
  542. };
  543. static pthread_key_t sTlsKey; /* Thread local storage index */
  544. static int sTlsInit = 0;
  545. struct mg_workerTLS {
  546. int is_master;
  547. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  548. HANDLE pthread_cond_helper_mutex;
  549. #endif
  550. };
  551. /* Directory entry */
  552. struct de {
  553. struct mg_connection *conn;
  554. char *file_name;
  555. struct file file;
  556. };
  557. const char **mg_get_valid_option_names(void)
  558. {
  559. return config_options;
  560. }
  561. static int is_file_in_memory(struct mg_connection *conn, const char *path,
  562. struct file *filep)
  563. {
  564. size_t size = 0;
  565. if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
  566. conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  567. /* NOTE: override filep->size only on success. Otherwise, it might
  568. break constructs like if (!mg_stat() || !mg_fopen()) ... */
  569. filep->size = size;
  570. }
  571. return filep->membuf != NULL;
  572. }
  573. static int is_file_opened(const struct file *filep)
  574. {
  575. return filep->membuf != NULL || filep->fp != NULL;
  576. }
  577. static int mg_fopen(struct mg_connection *conn, const char *path,
  578. const char *mode, struct file *filep)
  579. {
  580. if (!is_file_in_memory(conn, path, filep)) {
  581. #ifdef _WIN32
  582. wchar_t wbuf[PATH_MAX], wmode[20];
  583. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  584. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  585. filep->fp = _wfopen(wbuf, wmode);
  586. #else
  587. filep->fp = fopen(path, mode);
  588. #endif
  589. }
  590. return is_file_opened(filep);
  591. }
  592. static void mg_fclose(struct file *filep)
  593. {
  594. if (filep != NULL && filep->fp != NULL) {
  595. fclose(filep->fp);
  596. }
  597. }
  598. static int get_option_index(const char *name)
  599. {
  600. int i;
  601. for (i = 0; config_options[i * 2] != NULL; i++) {
  602. if (strcmp(config_options[i * 2], name) == 0) {
  603. return i;
  604. }
  605. }
  606. return -1;
  607. }
  608. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  609. {
  610. int i;
  611. if ((i = get_option_index(name)) == -1) {
  612. return NULL;
  613. } else if (ctx->config[i] == NULL) {
  614. return "";
  615. } else {
  616. return ctx->config[i];
  617. }
  618. }
  619. static void sockaddr_to_string(char *buf, size_t len,
  620. const union usa *usa)
  621. {
  622. buf[0] = '\0';
  623. #if defined(USE_IPV6)
  624. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  625. (void *) &usa->sin.sin_addr :
  626. (void *) &usa->sin6.sin6_addr, buf, len);
  627. #elif defined(_WIN32)
  628. /* Only Windoze Vista (and newer) have inet_ntop() */
  629. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  630. #else
  631. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  632. #endif
  633. }
  634. /* Print error message to the opened error log stream. */
  635. void mg_cry(struct mg_connection *conn, const char *fmt, ...)
  636. {
  637. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  638. va_list ap;
  639. FILE *fp;
  640. time_t timestamp;
  641. va_start(ap, fmt);
  642. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  643. va_end(ap);
  644. /* Do not lock when getting the callback value, here and below.
  645. I suppose this is fine, since function cannot disappear in the
  646. same way string option can. */
  647. if (conn->ctx->callbacks.log_message == NULL ||
  648. conn->ctx->callbacks.log_message(conn, buf) == 0) {
  649. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  650. fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  651. if (fp != NULL) {
  652. flockfile(fp);
  653. timestamp = time(NULL);
  654. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  655. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  656. src_addr);
  657. if (conn->request_info.request_method != NULL) {
  658. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  659. conn->request_info.uri);
  660. }
  661. fprintf(fp, "%s", buf);
  662. fputc('\n', fp);
  663. funlockfile(fp);
  664. fclose(fp);
  665. }
  666. }
  667. }
  668. /* Return fake connection structure. Used for logging, if connection
  669. is not applicable at the moment of logging. */
  670. static struct mg_connection *fc(struct mg_context *ctx)
  671. {
  672. static struct mg_connection fake_connection;
  673. fake_connection.ctx = ctx;
  674. return &fake_connection;
  675. }
  676. const char *mg_version(void)
  677. {
  678. return CIVETWEB_VERSION;
  679. }
  680. struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
  681. {
  682. return &conn->request_info;
  683. }
  684. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  685. {
  686. for (; *src != '\0' && n > 1; n--) {
  687. *dst++ = *src++;
  688. }
  689. *dst = '\0';
  690. }
  691. static int lowercase(const char *s)
  692. {
  693. return tolower(* (const unsigned char *) s);
  694. }
  695. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  696. {
  697. int diff = 0;
  698. if (len > 0)
  699. do {
  700. diff = lowercase(s1++) - lowercase(s2++);
  701. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  702. return diff;
  703. }
  704. static int mg_strcasecmp(const char *s1, const char *s2)
  705. {
  706. int diff;
  707. do {
  708. diff = lowercase(s1++) - lowercase(s2++);
  709. } while (diff == 0 && s1[-1] != '\0');
  710. return diff;
  711. }
  712. static char * mg_strndup(const char *ptr, size_t len)
  713. {
  714. char *p;
  715. if ((p = (char *) malloc(len + 1)) != NULL) {
  716. mg_strlcpy(p, ptr, len + 1);
  717. }
  718. return p;
  719. }
  720. static char * mg_strdup(const char *str)
  721. {
  722. return mg_strndup(str, strlen(str));
  723. }
  724. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  725. {
  726. int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
  727. for (i = 0; i <= big_len - small_len; i++) {
  728. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  729. return big_str + i;
  730. }
  731. }
  732. return NULL;
  733. }
  734. /* Like snprintf(), but never returns negative value, or a value
  735. that is larger than a supplied buffer.
  736. Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  737. in his audit report. */
  738. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  739. const char *fmt, va_list ap)
  740. {
  741. int n;
  742. if (buflen == 0)
  743. return 0;
  744. n = vsnprintf(buf, buflen, fmt, ap);
  745. if (n < 0) {
  746. mg_cry(conn, "vsnprintf error");
  747. n = 0;
  748. } else if (n >= (int) buflen) {
  749. mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
  750. n > 200 ? 200 : n, buf);
  751. n = (int) buflen - 1;
  752. }
  753. buf[n] = '\0';
  754. return n;
  755. }
  756. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  757. PRINTF_FORMAT_STRING(const char *fmt), ...)
  758. PRINTF_ARGS(4, 5);
  759. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  760. const char *fmt, ...)
  761. {
  762. va_list ap;
  763. int n;
  764. va_start(ap, fmt);
  765. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  766. va_end(ap);
  767. return n;
  768. }
  769. /* Skip the characters until one of the delimiters characters found.
  770. 0-terminate resulting word. Skip the delimiter and following whitespaces.
  771. Advance pointer to buffer to the next word. Return found 0-terminated word.
  772. Delimiters can be quoted with quotechar. */
  773. static char *skip_quoted(char **buf, const char *delimiters,
  774. const char *whitespace, char quotechar)
  775. {
  776. char *p, *begin_word, *end_word, *end_whitespace;
  777. begin_word = *buf;
  778. end_word = begin_word + strcspn(begin_word, delimiters);
  779. /* Check for quotechar */
  780. if (end_word > begin_word) {
  781. p = end_word - 1;
  782. while (*p == quotechar) {
  783. /* If there is anything beyond end_word, copy it */
  784. if (*end_word == '\0') {
  785. *p = '\0';
  786. break;
  787. } else {
  788. size_t end_off = strcspn(end_word + 1, delimiters);
  789. memmove (p, end_word, end_off + 1);
  790. p += end_off; /* p must correspond to end_word - 1 */
  791. end_word += end_off + 1;
  792. }
  793. }
  794. for (p++; p < end_word; p++) {
  795. *p = '\0';
  796. }
  797. }
  798. if (*end_word == '\0') {
  799. *buf = end_word;
  800. } else {
  801. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  802. for (p = end_word; p < end_whitespace; p++) {
  803. *p = '\0';
  804. }
  805. *buf = end_whitespace;
  806. }
  807. return begin_word;
  808. }
  809. /* Simplified version of skip_quoted without quote char
  810. and whitespace == delimiters */
  811. static char *skip(char **buf, const char *delimiters)
  812. {
  813. return skip_quoted(buf, delimiters, delimiters, 0);
  814. }
  815. /* Return HTTP header value, or NULL if not found. */
  816. static const char *get_header(const struct mg_request_info *ri,
  817. const char *name)
  818. {
  819. int i;
  820. for (i = 0; i < ri->num_headers; i++)
  821. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  822. return ri->http_headers[i].value;
  823. return NULL;
  824. }
  825. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  826. {
  827. return get_header(&conn->request_info, name);
  828. }
  829. /* A helper function for traversing a comma separated list of values.
  830. It returns a list pointer shifted to the next value, or NULL if the end
  831. of the list found.
  832. Value is stored in val vector. If value has form "x=y", then eq_val
  833. vector is initialized to point to the "y" part, and val vector length
  834. is adjusted to point only to "x". */
  835. static const char *next_option(const char *list, struct vec *val,
  836. struct vec *eq_val)
  837. {
  838. if (list == NULL || *list == '\0') {
  839. /* End of the list */
  840. list = NULL;
  841. } else {
  842. val->ptr = list;
  843. if ((list = strchr(val->ptr, ',')) != NULL) {
  844. /* Comma found. Store length and shift the list ptr */
  845. val->len = list - val->ptr;
  846. list++;
  847. } else {
  848. /* This value is the last one */
  849. list = val->ptr + strlen(val->ptr);
  850. val->len = list - val->ptr;
  851. }
  852. if (eq_val != NULL) {
  853. /* Value has form "x=y", adjust pointers and lengths
  854. so that val points to "x", and eq_val points to "y". */
  855. eq_val->len = 0;
  856. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  857. if (eq_val->ptr != NULL) {
  858. eq_val->ptr++; /* Skip over '=' character */
  859. eq_val->len = val->ptr + val->len - eq_val->ptr;
  860. val->len = (eq_val->ptr - val->ptr) - 1;
  861. }
  862. }
  863. }
  864. return list;
  865. }
  866. /* Perform case-insensitive match of string against pattern */
  867. static int match_prefix(const char *pattern, int pattern_len, const char *str)
  868. {
  869. const char *or_str;
  870. int i, j, len, res;
  871. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  872. res = match_prefix(pattern, (int)(or_str - pattern), str);
  873. return res > 0 ? res :
  874. match_prefix(or_str + 1, (int)((pattern + pattern_len) - (or_str + 1)), str);
  875. }
  876. i = j = 0;
  877. res = -1;
  878. for (; i < pattern_len; i++, j++) {
  879. if (pattern[i] == '?' && str[j] != '\0') {
  880. continue;
  881. } else if (pattern[i] == '$') {
  882. return str[j] == '\0' ? j : -1;
  883. } else if (pattern[i] == '*') {
  884. i++;
  885. if (pattern[i] == '*') {
  886. i++;
  887. len = (int) strlen(str + j);
  888. } else {
  889. len = (int) strcspn(str + j, "/");
  890. }
  891. if (i == pattern_len) {
  892. return j + len;
  893. }
  894. do {
  895. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  896. } while (res == -1 && len-- > 0);
  897. return res == -1 ? -1 : j + res + len;
  898. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  899. return -1;
  900. }
  901. }
  902. return j;
  903. }
  904. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  905. This function must tolerate situations when connection info is not
  906. set up, for example if request parsing failed. */
  907. static int should_keep_alive(const struct mg_connection *conn)
  908. {
  909. const char *http_version = conn->request_info.http_version;
  910. const char *header = mg_get_header(conn, "Connection");
  911. if (conn->must_close ||
  912. conn->status_code == 401 ||
  913. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  914. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  915. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  916. return 0;
  917. }
  918. return 1;
  919. }
  920. static const char *suggest_connection_header(const struct mg_connection *conn)
  921. {
  922. return should_keep_alive(conn) ? "keep-alive" : "close";
  923. }
  924. static void send_http_error(struct mg_connection *, int, const char *,
  925. PRINTF_FORMAT_STRING(const char *fmt), ...)
  926. PRINTF_ARGS(4, 5);
  927. static void send_http_error(struct mg_connection *conn, int status,
  928. const char *reason, const char *fmt, ...)
  929. {
  930. char buf[MG_BUF_LEN];
  931. va_list ap;
  932. int len = 0;
  933. conn->status_code = status;
  934. if (conn->ctx->callbacks.http_error == NULL ||
  935. conn->ctx->callbacks.http_error(conn, status)) {
  936. buf[0] = '\0';
  937. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  938. if (status > 199 && status != 204 && status != 304) {
  939. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  940. buf[len++] = '\n';
  941. va_start(ap, fmt);
  942. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  943. va_end(ap);
  944. }
  945. DEBUG_TRACE(("[%s]", buf));
  946. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  947. "Content-Length: %d\r\n"
  948. "Connection: %s\r\n\r\n", status, reason, len,
  949. suggest_connection_header(conn));
  950. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  951. }
  952. }
  953. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  954. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  955. {
  956. (void) unused;
  957. *mutex = CreateMutex(NULL, FALSE, NULL);
  958. return *mutex == NULL ? -1 : 0;
  959. }
  960. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  961. {
  962. return CloseHandle(*mutex) == 0 ? -1 : 0;
  963. }
  964. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  965. {
  966. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  967. }
  968. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  969. {
  970. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  971. }
  972. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  973. {
  974. FILETIME ft;
  975. ULARGE_INTEGER li;
  976. BOOL ok = FALSE;
  977. double d;
  978. static double perfcnt_per_sec = 0.0;
  979. if (tp) {
  980. if (clk_id == CLOCK_REALTIME) {
  981. GetSystemTimeAsFileTime(&ft);
  982. li.LowPart = ft.dwLowDateTime;
  983. li.HighPart = ft.dwHighDateTime;
  984. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  985. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  986. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  987. ok = TRUE;
  988. } else if (clk_id == CLOCK_MONOTONIC) {
  989. if (perfcnt_per_sec==0) {
  990. QueryPerformanceFrequency((LARGE_INTEGER *) &li);
  991. perfcnt_per_sec = 1.0 / li.QuadPart;
  992. }
  993. if (perfcnt_per_sec!=0) {
  994. QueryPerformanceCounter((LARGE_INTEGER *) &li);
  995. d = li.QuadPart * perfcnt_per_sec;
  996. tp->tv_sec = (time_t)d;
  997. d -= tp->tv_sec;
  998. tp->tv_nsec = (long)(d*1.0E9);
  999. ok = TRUE;
  1000. }
  1001. }
  1002. }
  1003. return ok ? 0 : -1;
  1004. }
  1005. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1006. {
  1007. (void) unused;
  1008. InitializeCriticalSection(&cv->threadIdSec);
  1009. cv->waitingthreadcount = 0;
  1010. cv->waitingthreadhdls = calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1011. return (cv->waitingthreadhdls!=NULL) ? 0 : -1;
  1012. }
  1013. static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex, const struct timespec * abstime)
  1014. {
  1015. struct mg_workerTLS * tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1016. int ok;
  1017. struct timespec tsnow;
  1018. int64_t nsnow, nswaitabs, nswaitrel;
  1019. DWORD mswaitrel;
  1020. EnterCriticalSection(&cv->threadIdSec);
  1021. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1022. cv->waitingthreadhdls[cv->waitingthreadcount] = tls->pthread_cond_helper_mutex;
  1023. cv->waitingthreadcount++;
  1024. LeaveCriticalSection(&cv->threadIdSec);
  1025. if (abstime) {
  1026. clock_gettime(CLOCK_REALTIME, &tsnow);
  1027. nsnow = (((uint64_t)tsnow.tv_sec)<<32) + tsnow.tv_nsec;
  1028. nswaitabs = (((uint64_t)abstime->tv_sec)<<32) + abstime->tv_nsec;
  1029. nswaitrel = nswaitabs - nsnow;
  1030. if (nswaitrel<0) nswaitrel=0;
  1031. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1032. } else {
  1033. mswaitrel = INFINITE;
  1034. }
  1035. pthread_mutex_unlock(mutex);
  1036. ok = (WAIT_OBJECT_0 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1037. pthread_mutex_lock(mutex);
  1038. return ok ? 0 : -1;
  1039. }
  1040. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  1041. {
  1042. return pthread_cond_timedwait(cv, mutex, NULL);
  1043. }
  1044. static int pthread_cond_signal(pthread_cond_t *cv)
  1045. {
  1046. int i;
  1047. HANDLE wkup = NULL;
  1048. BOOL ok = FALSE;
  1049. EnterCriticalSection(&cv->threadIdSec);
  1050. if (cv->waitingthreadcount) {
  1051. wkup = cv->waitingthreadhdls[0];
  1052. ok = SetEvent(wkup);
  1053. for (i=1; i<cv->waitingthreadcount; i++) {
  1054. cv->waitingthreadhdls[i-1] = cv->waitingthreadhdls[i];
  1055. }
  1056. cv->waitingthreadcount--;
  1057. assert(ok);
  1058. }
  1059. LeaveCriticalSection(&cv->threadIdSec);
  1060. return ok ? 0 : 1;
  1061. }
  1062. static int pthread_cond_broadcast(pthread_cond_t *cv)
  1063. {
  1064. EnterCriticalSection(&cv->threadIdSec);
  1065. while (cv->waitingthreadcount) {
  1066. pthread_cond_signal(cv);
  1067. }
  1068. LeaveCriticalSection(&cv->threadIdSec);
  1069. return 0;
  1070. }
  1071. static int pthread_cond_destroy(pthread_cond_t *cv)
  1072. {
  1073. EnterCriticalSection(&cv->threadIdSec);
  1074. assert(cv->waitingthreadcount==0);
  1075. cv->waitingthreadhdls = 0;
  1076. free(cv->waitingthreadhdls);
  1077. LeaveCriticalSection(&cv->threadIdSec);
  1078. DeleteCriticalSection(&cv->threadIdSec);
  1079. return 0;
  1080. }
  1081. /* For Windows, change all slashes to backslashes in path names. */
  1082. static void change_slashes_to_backslashes(char *path)
  1083. {
  1084. int i;
  1085. for (i = 0; path[i] != '\0'; i++) {
  1086. if (path[i] == '/')
  1087. path[i] = '\\';
  1088. /* i > 0 check is to preserve UNC paths, like \\server\file.txt */
  1089. if (path[i] == '\\' && i > 0)
  1090. while (path[i + 1] == '\\' || path[i + 1] == '/')
  1091. (void) memmove(path + i + 1,
  1092. path + i + 2, strlen(path + i + 1));
  1093. }
  1094. }
  1095. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1096. wbuf and wbuf_len is a target buffer and its length. */
  1097. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  1098. {
  1099. char buf[PATH_MAX], buf2[PATH_MAX];
  1100. mg_strlcpy(buf, path, sizeof(buf));
  1101. change_slashes_to_backslashes(buf);
  1102. /* Convert to Unicode and back. If doubly-converted string does not
  1103. match the original, something is fishy, reject. */
  1104. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1105. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1106. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1107. NULL, NULL);
  1108. if (strcmp(buf, buf2) != 0) {
  1109. wbuf[0] = L'\0';
  1110. }
  1111. }
  1112. #if defined(_WIN32_WCE)
  1113. static time_t time(time_t *ptime)
  1114. {
  1115. time_t t;
  1116. SYSTEMTIME st;
  1117. FILETIME ft;
  1118. GetSystemTime(&st);
  1119. SystemTimeToFileTime(&st, &ft);
  1120. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1121. if (ptime != NULL) {
  1122. *ptime = t;
  1123. }
  1124. return t;
  1125. }
  1126. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  1127. {
  1128. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  1129. FILETIME ft, lft;
  1130. SYSTEMTIME st;
  1131. TIME_ZONE_INFORMATION tzinfo;
  1132. if (ptm == NULL) {
  1133. return NULL;
  1134. }
  1135. * (int64_t *) &ft = t;
  1136. FileTimeToLocalFileTime(&ft, &lft);
  1137. FileTimeToSystemTime(&lft, &st);
  1138. ptm->tm_year = st.wYear - 1900;
  1139. ptm->tm_mon = st.wMonth - 1;
  1140. ptm->tm_wday = st.wDayOfWeek;
  1141. ptm->tm_mday = st.wDay;
  1142. ptm->tm_hour = st.wHour;
  1143. ptm->tm_min = st.wMinute;
  1144. ptm->tm_sec = st.wSecond;
  1145. ptm->tm_yday = 0; /* hope nobody uses this */
  1146. ptm->tm_isdst =
  1147. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1148. return ptm;
  1149. }
  1150. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  1151. {
  1152. /* FIXME(lsm): fix this. */
  1153. return localtime(ptime, ptm);
  1154. }
  1155. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1156. const struct tm *tm)
  1157. {
  1158. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  1159. return 0;
  1160. }
  1161. #endif
  1162. /* Windows happily opens files with some garbage at the end of file name.
  1163. For example, fopen("a.cgi ", "r") on Windows successfully opens
  1164. "a.cgi", despite one would expect an error back.
  1165. This function returns non-0 if path ends with some garbage. */
  1166. static int path_cannot_disclose_cgi(const char *path)
  1167. {
  1168. static const char *allowed_last_characters = "_-";
  1169. int last = path[strlen(path) - 1];
  1170. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  1171. }
  1172. static int mg_stat(struct mg_connection *conn, const char *path,
  1173. struct file *filep)
  1174. {
  1175. wchar_t wbuf[PATH_MAX];
  1176. WIN32_FILE_ATTRIBUTE_DATA info;
  1177. if (!is_file_in_memory(conn, path, filep)) {
  1178. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1179. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1180. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1181. filep->modification_time = SYS2UNIX_TIME(
  1182. info.ftLastWriteTime.dwLowDateTime,
  1183. info.ftLastWriteTime.dwHighDateTime);
  1184. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1185. /* If file name is fishy, reset the file structure and return
  1186. error.
  1187. Note it is important to reset, not just return the error, cause
  1188. functions like is_file_opened() check the struct. */
  1189. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  1190. memset(filep, 0, sizeof(*filep));
  1191. }
  1192. }
  1193. }
  1194. return filep->membuf != NULL || filep->modification_time != 0;
  1195. }
  1196. static int mg_remove(const char *path)
  1197. {
  1198. wchar_t wbuf[PATH_MAX];
  1199. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1200. return DeleteFileW(wbuf) ? 0 : -1;
  1201. }
  1202. static int mg_mkdir(const char *path, int mode)
  1203. {
  1204. char buf[PATH_MAX];
  1205. wchar_t wbuf[PATH_MAX];
  1206. (void) mode;
  1207. mg_strlcpy(buf, path, sizeof(buf));
  1208. change_slashes_to_backslashes(buf);
  1209. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  1210. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1211. }
  1212. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  1213. static DIR * opendir(const char *name)
  1214. {
  1215. DIR *dir = NULL;
  1216. wchar_t wpath[PATH_MAX];
  1217. DWORD attrs;
  1218. if (name == NULL) {
  1219. SetLastError(ERROR_BAD_ARGUMENTS);
  1220. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  1221. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1222. } else {
  1223. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1224. attrs = GetFileAttributesW(wpath);
  1225. if (attrs != 0xFFFFFFFF &&
  1226. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1227. (void) wcscat(wpath, L"\\*");
  1228. dir->handle = FindFirstFileW(wpath, &dir->info);
  1229. dir->result.d_name[0] = '\0';
  1230. } else {
  1231. free(dir);
  1232. dir = NULL;
  1233. }
  1234. }
  1235. return dir;
  1236. }
  1237. static int closedir(DIR *dir)
  1238. {
  1239. int result = 0;
  1240. if (dir != NULL) {
  1241. if (dir->handle != INVALID_HANDLE_VALUE)
  1242. result = FindClose(dir->handle) ? 0 : -1;
  1243. free(dir);
  1244. } else {
  1245. result = -1;
  1246. SetLastError(ERROR_BAD_ARGUMENTS);
  1247. }
  1248. return result;
  1249. }
  1250. static struct dirent *readdir(DIR *dir)
  1251. {
  1252. struct dirent *result = 0;
  1253. if (dir) {
  1254. if (dir->handle != INVALID_HANDLE_VALUE) {
  1255. result = &dir->result;
  1256. (void) WideCharToMultiByte(CP_UTF8, 0,
  1257. dir->info.cFileName, -1, result->d_name,
  1258. sizeof(result->d_name), NULL, NULL);
  1259. if (!FindNextFileW(dir->handle, &dir->info)) {
  1260. (void) FindClose(dir->handle);
  1261. dir->handle = INVALID_HANDLE_VALUE;
  1262. }
  1263. } else {
  1264. SetLastError(ERROR_FILE_NOT_FOUND);
  1265. }
  1266. } else {
  1267. SetLastError(ERROR_BAD_ARGUMENTS);
  1268. }
  1269. return result;
  1270. }
  1271. #ifndef HAVE_POLL
  1272. static int poll(struct pollfd *pfd, int n, int milliseconds)
  1273. {
  1274. struct timeval tv;
  1275. fd_set set;
  1276. int i, result;
  1277. SOCKET maxfd = 0;
  1278. tv.tv_sec = milliseconds / 1000;
  1279. tv.tv_usec = (milliseconds % 1000) * 1000;
  1280. FD_ZERO(&set);
  1281. for (i = 0; i < n; i++) {
  1282. FD_SET((SOCKET) pfd[i].fd, &set);
  1283. pfd[i].revents = 0;
  1284. if (pfd[i].fd > maxfd) {
  1285. maxfd = pfd[i].fd;
  1286. }
  1287. }
  1288. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  1289. for (i = 0; i < n; i++) {
  1290. if (FD_ISSET(pfd[i].fd, &set)) {
  1291. pfd[i].revents = POLLIN;
  1292. }
  1293. }
  1294. }
  1295. return result;
  1296. }
  1297. #endif /* HAVE_POLL */
  1298. static void set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  1299. {
  1300. (void) conn; /* Unused. */
  1301. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  1302. }
  1303. int mg_start_thread(mg_thread_func_t f, void *p)
  1304. {
  1305. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1306. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384 */
  1307. return (long)_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == -1L ? -1 : 0;
  1308. #else
  1309. return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1310. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1311. }
  1312. /* Start a thread storing the thread context. */
  1313. static int mg_start_thread_with_id(unsigned (__stdcall *f)(void *), void *p,
  1314. pthread_t *threadidptr)
  1315. {
  1316. uintptr_t uip;
  1317. HANDLE threadhandle;
  1318. int result;
  1319. uip = _beginthreadex(NULL, 0, (unsigned (__stdcall *)(void *)) f, p, 0,
  1320. NULL);
  1321. threadhandle = (HANDLE) uip;
  1322. if (threadidptr != NULL) {
  1323. *threadidptr = threadhandle;
  1324. }
  1325. result = (threadhandle == NULL) ? -1 : 0;
  1326. return result;
  1327. }
  1328. /* Wait for a thread to finish. */
  1329. static int mg_join_thread(pthread_t threadid)
  1330. {
  1331. int result;
  1332. DWORD dwevent;
  1333. result = -1;
  1334. dwevent = WaitForSingleObject(threadid, INFINITE);
  1335. if (dwevent == WAIT_FAILED) {
  1336. int err;
  1337. err = GetLastError();
  1338. DEBUG_TRACE(("WaitForSingleObject() failed, error %d", err));
  1339. } else {
  1340. if (dwevent == WAIT_OBJECT_0) {
  1341. CloseHandle(threadid);
  1342. result = 0;
  1343. }
  1344. }
  1345. return result;
  1346. }
  1347. static HANDLE dlopen(const char *dll_name, int flags)
  1348. {
  1349. wchar_t wbuf[PATH_MAX];
  1350. (void) flags;
  1351. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1352. return LoadLibraryW(wbuf);
  1353. }
  1354. static int dlclose(void *handle)
  1355. {
  1356. int result;
  1357. if (FreeLibrary(handle) != 0) {
  1358. result = 0;
  1359. } else {
  1360. result = -1;
  1361. }
  1362. return result;
  1363. }
  1364. #if !defined(NO_CGI)
  1365. #define SIGKILL 0
  1366. static int kill(pid_t pid, int sig_num)
  1367. {
  1368. (void) TerminateProcess(pid, sig_num);
  1369. (void) CloseHandle(pid);
  1370. return 0;
  1371. }
  1372. static void trim_trailing_whitespaces(char *s)
  1373. {
  1374. char *e = s + strlen(s) - 1;
  1375. while (e > s && isspace(* (unsigned char *) e)) {
  1376. *e-- = '\0';
  1377. }
  1378. }
  1379. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1380. char *envblk, char *envp[], int fdin,
  1381. int fdout, const char *dir)
  1382. {
  1383. HANDLE me;
  1384. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  1385. cmdline[PATH_MAX], buf[PATH_MAX];
  1386. struct file file = STRUCT_FILE_INITIALIZER;
  1387. STARTUPINFOA si;
  1388. PROCESS_INFORMATION pi = { 0 };
  1389. (void) envp;
  1390. memset(&si, 0, sizeof(si));
  1391. si.cb = sizeof(si);
  1392. /* TODO(lsm): redirect CGI errors to the error log file */
  1393. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1394. si.wShowWindow = SW_HIDE;
  1395. me = GetCurrentProcess();
  1396. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
  1397. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1398. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
  1399. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1400. /* If CGI file is a script, try to read the interpreter line */
  1401. interp = conn->ctx->config[CGI_INTERPRETER];
  1402. if (interp == NULL) {
  1403. buf[0] = buf[1] = '\0';
  1404. /* Read the first line of the script into the buffer */
  1405. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1406. if (mg_fopen(conn, cmdline, "r", &file)) {
  1407. p = (char *) file.membuf;
  1408. mg_fgets(buf, sizeof(buf), &file, &p);
  1409. mg_fclose(&file);
  1410. buf[sizeof(buf) - 1] = '\0';
  1411. }
  1412. if (buf[0] == '#' && buf[1] == '!') {
  1413. trim_trailing_whitespaces(buf + 2);
  1414. } else {
  1415. buf[2] = '\0';
  1416. }
  1417. interp = buf + 2;
  1418. }
  1419. if (interp[0] != '\0') {
  1420. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  1421. interp = full_interp;
  1422. }
  1423. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  1424. mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
  1425. interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
  1426. DEBUG_TRACE(("Running [%s]", cmdline));
  1427. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1428. CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
  1429. mg_cry(conn, "%s: CreateProcess(%s): %ld",
  1430. __func__, cmdline, ERRNO);
  1431. pi.hProcess = (pid_t) -1;
  1432. }
  1433. (void) CloseHandle(si.hStdOutput);
  1434. (void) CloseHandle(si.hStdInput);
  1435. if (pi.hThread != NULL)
  1436. (void) CloseHandle(pi.hThread);
  1437. return (pid_t) pi.hProcess;
  1438. }
  1439. #endif /* !NO_CGI */
  1440. static int set_non_blocking_mode(SOCKET sock)
  1441. {
  1442. unsigned long on = 1;
  1443. return ioctlsocket(sock, FIONBIO, &on);
  1444. }
  1445. #else
  1446. static int mg_stat(struct mg_connection *conn, const char *path,
  1447. struct file *filep)
  1448. {
  1449. struct stat st;
  1450. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  1451. filep->size = st.st_size;
  1452. filep->modification_time = st.st_mtime;
  1453. filep->is_directory = S_ISDIR(st.st_mode);
  1454. } else {
  1455. filep->modification_time = (time_t) 0;
  1456. }
  1457. return filep->membuf != NULL || filep->modification_time != (time_t) 0;
  1458. }
  1459. static void set_close_on_exec(int fd, struct mg_connection *conn /* may be null */)
  1460. {
  1461. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  1462. if (conn)
  1463. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  1464. __func__, strerror(ERRNO));
  1465. }
  1466. }
  1467. int mg_start_thread(mg_thread_func_t func, void *param)
  1468. {
  1469. pthread_t thread_id;
  1470. pthread_attr_t attr;
  1471. int result;
  1472. (void) pthread_attr_init(&attr);
  1473. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1474. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1475. /* Compile-time option to control stack size,
  1476. e.g. -DUSE_STACK_SIZE=16384 */
  1477. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1478. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1479. result = pthread_create(&thread_id, &attr, func, param);
  1480. pthread_attr_destroy(&attr);
  1481. return result;
  1482. }
  1483. /* Start a thread storing the thread context. */
  1484. static int mg_start_thread_with_id(mg_thread_func_t func, void *param,
  1485. pthread_t *threadidptr)
  1486. {
  1487. pthread_t thread_id;
  1488. pthread_attr_t attr;
  1489. int result;
  1490. (void) pthread_attr_init(&attr);
  1491. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1492. /* Compile-time option to control stack size,
  1493. e.g. -DUSE_STACK_SIZE=16384 */
  1494. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1495. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  1496. result = pthread_create(&thread_id, &attr, func, param);
  1497. pthread_attr_destroy(&attr);
  1498. if (threadidptr != NULL) {
  1499. *threadidptr = thread_id;
  1500. }
  1501. return result;
  1502. }
  1503. /* Wait for a thread to finish. */
  1504. static int mg_join_thread(pthread_t threadid)
  1505. {
  1506. int result;
  1507. result = pthread_join(threadid, NULL);
  1508. return result;
  1509. }
  1510. #ifndef NO_CGI
  1511. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1512. char *envblk, char *envp[], int fdin,
  1513. int fdout, const char *dir)
  1514. {
  1515. pid_t pid;
  1516. const char *interp;
  1517. (void) envblk;
  1518. if ((pid = fork()) == -1) {
  1519. /* Parent */
  1520. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1521. } else if (pid == 0) {
  1522. /* Child */
  1523. if (chdir(dir) != 0) {
  1524. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1525. } else if (dup2(fdin, 0) == -1) {
  1526. mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  1527. } else if (dup2(fdout, 1) == -1) {
  1528. mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  1529. } else {
  1530. /* Not redirecting stderr to stdout, to avoid output being littered
  1531. with the error messages. */
  1532. (void) close(fdin);
  1533. (void) close(fdout);
  1534. /* After exec, all signal handlers are restored to their default
  1535. values, with one exception of SIGCHLD. According to
  1536. POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  1537. leave unchanged after exec if it was set to be ignored. Restore
  1538. it to default action. */
  1539. signal(SIGCHLD, SIG_DFL);
  1540. interp = conn->ctx->config[CGI_INTERPRETER];
  1541. if (interp == NULL) {
  1542. (void) execle(prog, prog, NULL, envp);
  1543. mg_cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1544. } else {
  1545. (void) execle(interp, interp, prog, NULL, envp);
  1546. mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1547. strerror(ERRNO));
  1548. }
  1549. }
  1550. exit(EXIT_FAILURE);
  1551. }
  1552. return pid;
  1553. }
  1554. #endif /* !NO_CGI */
  1555. static int set_non_blocking_mode(SOCKET sock)
  1556. {
  1557. int flags;
  1558. flags = fcntl(sock, F_GETFL, 0);
  1559. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1560. return 0;
  1561. }
  1562. #endif /* _WIN32 */
  1563. /* Write data to the IO channel - opened file descriptor, socket or SSL
  1564. descriptor. Return number of bytes written. */
  1565. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1566. int64_t len)
  1567. {
  1568. int64_t sent;
  1569. int n, k;
  1570. (void) ssl; /* Get rid of warning */
  1571. sent = 0;
  1572. while (sent < len) {
  1573. /* How many bytes we send in this iteration */
  1574. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1575. #ifndef NO_SSL
  1576. if (ssl != NULL) {
  1577. n = SSL_write(ssl, buf + sent, k);
  1578. } else
  1579. #endif
  1580. if (fp != NULL) {
  1581. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1582. if (ferror(fp))
  1583. n = -1;
  1584. } else {
  1585. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1586. }
  1587. if (n <= 0)
  1588. break;
  1589. sent += n;
  1590. }
  1591. return sent;
  1592. }
  1593. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1594. Return negative value on error, or number of bytes read on success. */
  1595. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1596. {
  1597. int nread;
  1598. if (fp != NULL) {
  1599. /* Use read() instead of fread(), because if we're reading from the
  1600. CGI pipe, fread() may block until IO buffer is filled up. We cannot
  1601. afford to block and must pass all read bytes immediately to the
  1602. client. */
  1603. nread = read(fileno(fp), buf, (size_t) len);
  1604. #ifndef NO_SSL
  1605. } else if (conn->ssl != NULL) {
  1606. nread = SSL_read(conn->ssl, buf, len);
  1607. #endif
  1608. } else {
  1609. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1610. }
  1611. return conn->ctx->stop_flag ? -1 : nread;
  1612. }
  1613. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1614. {
  1615. int n, nread = 0;
  1616. while (len > 0 && conn->ctx->stop_flag == 0) {
  1617. n = pull(fp, conn, buf + nread, len);
  1618. if (n < 0) {
  1619. nread = n; /* Propagate the error */
  1620. break;
  1621. } else if (n == 0) {
  1622. break; /* No more data to read */
  1623. } else {
  1624. conn->consumed_content += n;
  1625. nread += n;
  1626. len -= n;
  1627. }
  1628. }
  1629. return nread;
  1630. }
  1631. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  1632. {
  1633. int n, buffered_len, nread;
  1634. const char *body;
  1635. /* If Content-Length is not set, read until socket is closed */
  1636. if (conn->consumed_content == 0 && conn->content_len == 0) {
  1637. conn->content_len = INT64_MAX;
  1638. conn->must_close = 1;
  1639. }
  1640. nread = 0;
  1641. if (conn->consumed_content < conn->content_len) {
  1642. /* Adjust number of bytes to read. */
  1643. int64_t to_read = conn->content_len - conn->consumed_content;
  1644. if (to_read < (int64_t) len) {
  1645. len = (size_t) to_read;
  1646. }
  1647. /* Return buffered data */
  1648. body = conn->buf + conn->request_len + conn->consumed_content;
  1649. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  1650. if (buffered_len > 0) {
  1651. if (len < (size_t) buffered_len) {
  1652. buffered_len = (int) len;
  1653. }
  1654. memcpy(buf, body, (size_t) buffered_len);
  1655. len -= buffered_len;
  1656. conn->consumed_content += buffered_len;
  1657. nread += buffered_len;
  1658. buf = (char *) buf + buffered_len;
  1659. }
  1660. /* We have returned all buffered data. Read new data from the remote
  1661. socket. */
  1662. n = pull_all(NULL, conn, (char *) buf, (int) len);
  1663. nread = n >= 0 ? nread + n : n;
  1664. }
  1665. return nread;
  1666. }
  1667. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  1668. {
  1669. time_t now;
  1670. int64_t n, total, allowed;
  1671. if (conn->throttle > 0) {
  1672. if ((now = time(NULL)) != conn->last_throttle_time) {
  1673. conn->last_throttle_time = now;
  1674. conn->last_throttle_bytes = 0;
  1675. }
  1676. allowed = conn->throttle - conn->last_throttle_bytes;
  1677. if (allowed > (int64_t) len) {
  1678. allowed = len;
  1679. }
  1680. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1681. (int64_t) allowed)) == allowed) {
  1682. buf = (char *) buf + total;
  1683. conn->last_throttle_bytes += total;
  1684. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1685. allowed = conn->throttle > (int64_t) len - total ?
  1686. (int64_t) len - total : conn->throttle;
  1687. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1688. (int64_t) allowed)) != allowed) {
  1689. break;
  1690. }
  1691. sleep(1);
  1692. conn->last_throttle_bytes = allowed;
  1693. conn->last_throttle_time = time(NULL);
  1694. buf = (char *) buf + n;
  1695. total += n;
  1696. }
  1697. }
  1698. } else {
  1699. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1700. (int64_t) len);
  1701. }
  1702. return (int) total;
  1703. }
  1704. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  1705. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  1706. {
  1707. va_list ap_copy;
  1708. int size = MG_BUF_LEN;
  1709. int len = -1;
  1710. *buf = NULL;
  1711. while (len == -1) {
  1712. if (*buf) free(*buf);
  1713. *buf = (char *)malloc(size *= 4);
  1714. if (!*buf) break;
  1715. va_copy(ap_copy, ap);
  1716. len = vsnprintf(*buf, size, fmt, ap_copy);
  1717. va_end(ap_copy);
  1718. }
  1719. return len;
  1720. }
  1721. /* Print message to buffer. If buffer is large enough to hold the message,
  1722. return buffer. If buffer is to small, allocate large enough buffer on heap,
  1723. and return allocated buffer. */
  1724. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  1725. {
  1726. va_list ap_copy;
  1727. int len;
  1728. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  1729. buffer is too small. Also, older versions of msvcrt.dll do not have
  1730. _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  1731. Therefore, we make two passes: on first pass, get required message
  1732. length.
  1733. On second pass, actually print the message. */
  1734. va_copy(ap_copy, ap);
  1735. len = vsnprintf(NULL, 0, fmt, ap_copy);
  1736. va_end(ap_copy);
  1737. if (len < 0) {
  1738. /* C runtime is not standard compliant, vsnprintf() returned -1.
  1739. Switch to alternative code path that uses incremental allocations.
  1740. */
  1741. va_copy(ap_copy, ap);
  1742. len = alloc_vprintf2(buf, fmt, ap);
  1743. va_end(ap_copy);
  1744. } else if (len > (int) size &&
  1745. (size = len + 1) > 0 &&
  1746. (*buf = (char *) malloc(size)) == NULL) {
  1747. len = -1; /* Allocation failed, mark failure */
  1748. } else {
  1749. va_copy(ap_copy, ap);
  1750. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  1751. va_end(ap_copy);
  1752. }
  1753. return len;
  1754. }
  1755. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap);
  1756. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  1757. {
  1758. char mem[MG_BUF_LEN], *buf = mem;
  1759. int len;
  1760. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  1761. len = mg_write(conn, buf, (size_t) len);
  1762. }
  1763. if (buf != mem && buf != NULL) {
  1764. free(buf);
  1765. }
  1766. return len;
  1767. }
  1768. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  1769. {
  1770. va_list ap;
  1771. int result;
  1772. va_start(ap, fmt);
  1773. result = mg_vprintf(conn, fmt, ap);
  1774. va_end(ap);
  1775. return result;
  1776. }
  1777. int mg_url_decode(const char *src, int src_len, char *dst,
  1778. int dst_len, int is_form_url_encoded)
  1779. {
  1780. int i, j, a, b;
  1781. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1782. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1783. if (src[i] == '%' && i < src_len - 2 &&
  1784. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1785. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1786. a = tolower(* (const unsigned char *) (src + i + 1));
  1787. b = tolower(* (const unsigned char *) (src + i + 2));
  1788. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1789. i += 2;
  1790. } else if (is_form_url_encoded && src[i] == '+') {
  1791. dst[j] = ' ';
  1792. } else {
  1793. dst[j] = src[i];
  1794. }
  1795. }
  1796. dst[j] = '\0'; /* Null-terminate the destination */
  1797. return i >= src_len ? j : -1;
  1798. }
  1799. int mg_get_var(const char *data, size_t data_len, const char *name,
  1800. char *dst, size_t dst_len)
  1801. {
  1802. return mg_get_var2(data,data_len,name,dst,dst_len,0);
  1803. }
  1804. int mg_get_var2(const char *data, size_t data_len, const char *name,
  1805. char *dst, size_t dst_len, size_t occurrence)
  1806. {
  1807. const char *p, *e, *s;
  1808. size_t name_len;
  1809. int len;
  1810. if (dst == NULL || dst_len == 0) {
  1811. len = -2;
  1812. } else if (data == NULL || name == NULL || data_len == 0) {
  1813. len = -1;
  1814. dst[0] = '\0';
  1815. } else {
  1816. name_len = strlen(name);
  1817. e = data + data_len;
  1818. len = -1;
  1819. dst[0] = '\0';
  1820. /* data is "var1=val1&var2=val2...". Find variable first */
  1821. for (p = data; p + name_len < e; p++) {
  1822. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  1823. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  1824. /* Point p to variable value */
  1825. p += name_len + 1;
  1826. /* Point s to the end of the value */
  1827. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1828. if (s == NULL) {
  1829. s = e;
  1830. }
  1831. assert(s >= p);
  1832. /* Decode variable into destination buffer */
  1833. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  1834. /* Redirect error code from -1 to -2 (destination buffer too
  1835. small). */
  1836. if (len == -1) {
  1837. len = -2;
  1838. }
  1839. break;
  1840. }
  1841. }
  1842. }
  1843. return len;
  1844. }
  1845. int mg_get_cookie(const char *cookie_header, const char *var_name,
  1846. char *dst, size_t dst_size)
  1847. {
  1848. const char *s, *p, *end;
  1849. int name_len, len = -1;
  1850. if (dst == NULL || dst_size == 0) {
  1851. len = -2;
  1852. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  1853. len = -1;
  1854. dst[0] = '\0';
  1855. } else {
  1856. name_len = (int) strlen(var_name);
  1857. end = s + strlen(s);
  1858. dst[0] = '\0';
  1859. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  1860. if (s[name_len] == '=') {
  1861. s += name_len + 1;
  1862. if ((p = strchr(s, ' ')) == NULL)
  1863. p = end;
  1864. if (p[-1] == ';')
  1865. p--;
  1866. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1867. s++;
  1868. p--;
  1869. }
  1870. if ((size_t) (p - s) < dst_size) {
  1871. len = (int)(p - s);
  1872. mg_strlcpy(dst, s, (size_t) len + 1);
  1873. } else {
  1874. len = -3;
  1875. }
  1876. break;
  1877. }
  1878. }
  1879. }
  1880. return len;
  1881. }
  1882. static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1883. size_t buf_len, struct file *filep)
  1884. {
  1885. struct vec a, b;
  1886. const char *rewrite, *uri = conn->request_info.uri,
  1887. *root = conn->ctx->config[DOCUMENT_ROOT];
  1888. char *p;
  1889. int match_len;
  1890. char gz_path[PATH_MAX];
  1891. char const* accept_encoding;
  1892. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  1893. of the path one byte on the right.
  1894. If document_root is NULL, leave the file empty. */
  1895. mg_snprintf(conn, buf, buf_len - 1, "%s%s",
  1896. root == NULL ? "" : root,
  1897. root == NULL ? "" : uri);
  1898. rewrite = conn->ctx->config[REWRITE];
  1899. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1900. if ((match_len = match_prefix(a.ptr, (int) a.len, uri)) > 0) {
  1901. mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
  1902. uri + match_len);
  1903. break;
  1904. }
  1905. }
  1906. if (mg_stat(conn, buf, filep)) return;
  1907. /* if we can't find the actual file, look for the file
  1908. with the same name but a .gz extension. If we find it,
  1909. use that and set the gzipped flag in the file struct
  1910. to indicate that the response need to have the content-
  1911. encoding: gzip header
  1912. we can only do this if the browser declares support */
  1913. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  1914. if (strstr(accept_encoding,"gzip") != NULL) {
  1915. snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
  1916. if (mg_stat(conn, gz_path, filep)) {
  1917. filep->gzipped = 1;
  1918. return;
  1919. }
  1920. }
  1921. }
  1922. /* Support PATH_INFO for CGI scripts. */
  1923. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1924. if (*p == '/') {
  1925. *p = '\0';
  1926. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1927. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1928. mg_stat(conn, buf, filep)) {
  1929. /* Shift PATH_INFO block one character right, e.g.
  1930. "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1931. conn->path_info is pointing to the local variable "path"
  1932. declared in handle_request(), so PATH_INFO is not valid
  1933. after handle_request returns. */
  1934. conn->path_info = p + 1;
  1935. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  1936. trailing \0 */
  1937. p[1] = '/';
  1938. break;
  1939. } else {
  1940. *p = '/';
  1941. }
  1942. }
  1943. }
  1944. }
  1945. /* Check whether full request is buffered. Return:
  1946. -1 if request is malformed
  1947. 0 if request is not yet fully buffered
  1948. >0 actual request length, including last \r\n\r\n */
  1949. static int get_request_len(const char *buf, int buflen)
  1950. {
  1951. const char *s, *e;
  1952. int len = 0;
  1953. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1954. /* Control characters are not allowed but >=128 is. */
  1955. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1956. *s != '\n' && * (const unsigned char *) s < 128) {
  1957. len = -1;
  1958. break; /* [i_a] abort scan as soon as one malformed character is
  1959. found; */
  1960. /* don't let subsequent \r\n\r\n win us over anyhow */
  1961. } else if (s[0] == '\n' && s[1] == '\n') {
  1962. len = (int) (s - buf) + 2;
  1963. } else if (s[0] == '\n' && &s[1] < e &&
  1964. s[1] == '\r' && s[2] == '\n') {
  1965. len = (int) (s - buf) + 3;
  1966. }
  1967. return len;
  1968. }
  1969. /* Convert month to the month number. Return -1 on error, or month number */
  1970. static int get_month_index(const char *s)
  1971. {
  1972. size_t i;
  1973. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1974. if (!strcmp(s, month_names[i]))
  1975. return (int) i;
  1976. return -1;
  1977. }
  1978. static int num_leap_years(int year)
  1979. {
  1980. return year / 4 - year / 100 + year / 400;
  1981. }
  1982. /* Parse UTC date-time string, and return the corresponding time_t value. */
  1983. static time_t parse_date_string(const char *datetime)
  1984. {
  1985. static const unsigned short days_before_month[] = {
  1986. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1987. };
  1988. char month_str[32];
  1989. int second, minute, hour, day, month, year, leap_days, days;
  1990. time_t result = (time_t) 0;
  1991. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1992. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1993. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1994. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1995. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1996. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1997. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1998. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1999. year > 1970 &&
  2000. (month = get_month_index(month_str)) != -1) {
  2001. leap_days = num_leap_years(year) - num_leap_years(1970);
  2002. year -= 1970;
  2003. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  2004. result = (time_t) days * 24 * 3600 + (time_t) hour * 3600 +
  2005. minute * 60 + second;
  2006. }
  2007. return result;
  2008. }
  2009. /* Protect against directory disclosure attack by removing '..',
  2010. excessive '/' and '\' characters */
  2011. static void remove_double_dots_and_double_slashes(char *s)
  2012. {
  2013. char *p = s;
  2014. while (*s != '\0') {
  2015. *p++ = *s++;
  2016. if (s[-1] == '/' || s[-1] == '\\') {
  2017. /* Skip all following slashes, backslashes and double-dots */
  2018. while (s[0] != '\0') {
  2019. if (s[0] == '/' || s[0] == '\\') {
  2020. s++;
  2021. } else if (s[0] == '.' && s[1] == '.') {
  2022. s += 2;
  2023. } else {
  2024. break;
  2025. }
  2026. }
  2027. }
  2028. }
  2029. *p = '\0';
  2030. }
  2031. static const struct {
  2032. const char *extension;
  2033. size_t ext_len;
  2034. const char *mime_type;
  2035. } builtin_mime_types[] = {
  2036. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  2037. application types */
  2038. {".doc", 4, "application/msword"},
  2039. {".eps", 4, "application/postscript"},
  2040. {".exe", 4, "application/octet-stream"},
  2041. {".js", 3, "application/javascript"},
  2042. {".json", 5, "application/json"},
  2043. {".pdf", 4, "application/pdf"},
  2044. {".ps", 3, "application/postscript"},
  2045. {".rtf", 4, "application/rtf"},
  2046. {".xhtml", 6, "application/xhtml+xml"},
  2047. {".xsl", 4, "application/xml"},
  2048. {".xslt", 5, "application/xml"},
  2049. /* audio */
  2050. {".mp3", 4, "audio/mpeg"},
  2051. {".oga", 4, "audio/ogg"},
  2052. {".ogg", 4, "audio/ogg"},
  2053. /* image */
  2054. {".gif", 4, "image/gif"},
  2055. {".ief", 4, "image/ief"},
  2056. {".jpeg", 5, "image/jpeg"},
  2057. {".jpg", 4, "image/jpeg"},
  2058. {".jpm", 4, "image/jpm"},
  2059. {".jpx", 4, "image/jpx"},
  2060. {".png", 4, "image/png"},
  2061. {".svg", 4, "image/svg+xml"},
  2062. {".tif", 4, "image/tiff"},
  2063. {".tiff", 5, "image/tiff"},
  2064. /* model */
  2065. {".wrl", 4, "model/vrml"},
  2066. /* text */
  2067. {".css", 4, "text/css"},
  2068. {".csv", 4, "text/csv"},
  2069. {".htm", 4, "text/html"},
  2070. {".html", 5, "text/html"},
  2071. {".sgm", 4, "text/sgml"},
  2072. {".shtm", 5, "text/html"},
  2073. {".shtml", 6, "text/html"},
  2074. {".txt", 4, "text/plain"},
  2075. {".xml", 4, "text/xml"},
  2076. /* video */
  2077. {".mov", 4, "video/quicktime"},
  2078. {".mp4", 4, "video/mp4"},
  2079. {".mpeg", 5, "video/mpeg"},
  2080. {".mpg", 4, "video/mpeg"},
  2081. {".ogv", 4, "video/ogg"},
  2082. {".qt", 3, "video/quicktime"},
  2083. /* not registered types
  2084. (http://reference.sitepoint.com/html/mime-types-full,
  2085. http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  2086. {".arj", 4, "application/x-arj-compressed"},
  2087. {".gz", 3, "application/x-gunzip"},
  2088. {".rar", 4, "application/x-arj-compressed"},
  2089. {".swf", 4, "application/x-shockwave-flash"},
  2090. {".tar", 4, "application/x-tar"},
  2091. {".tgz", 4, "application/x-tar-gz"},
  2092. {".torrent", 8, "application/x-bittorrent"},
  2093. {".ppt", 4, "application/x-mspowerpoint"},
  2094. {".xls", 4, "application/x-msexcel"},
  2095. {".zip", 4, "application/x-zip-compressed"},
  2096. {".aac", 4, "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  2097. {".aif", 4, "audio/x-aif"},
  2098. {".m3u", 4, "audio/x-mpegurl"},
  2099. {".mid", 4, "audio/x-midi"},
  2100. {".ra", 3, "audio/x-pn-realaudio"},
  2101. {".ram", 4, "audio/x-pn-realaudio"},
  2102. {".wav", 4, "audio/x-wav"},
  2103. {".bmp", 4, "image/bmp"},
  2104. {".ico", 4, "image/x-icon"},
  2105. {".pct", 4, "image/x-pct"},
  2106. {".pict", 5, "image/pict"},
  2107. {".rgb", 4, "image/x-rgb"},
  2108. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  2109. {".asf", 4, "video/x-ms-asf"},
  2110. {".avi", 4, "video/x-msvideo"},
  2111. {".m4v", 4, "video/x-m4v"},
  2112. {NULL, 0, NULL}
  2113. };
  2114. const char *mg_get_builtin_mime_type(const char *path)
  2115. {
  2116. const char *ext;
  2117. size_t i, path_len;
  2118. path_len = strlen(path);
  2119. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  2120. ext = path + (path_len - builtin_mime_types[i].ext_len);
  2121. if (path_len > builtin_mime_types[i].ext_len &&
  2122. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  2123. return builtin_mime_types[i].mime_type;
  2124. }
  2125. }
  2126. return "text/plain";
  2127. }
  2128. /* Look at the "path" extension and figure what mime type it has.
  2129. Store mime type in the vector. */
  2130. static void get_mime_type(struct mg_context *ctx, const char *path,
  2131. struct vec *vec)
  2132. {
  2133. struct vec ext_vec, mime_vec;
  2134. const char *list, *ext;
  2135. size_t path_len;
  2136. path_len = strlen(path);
  2137. /* Scan user-defined mime types first, in case user wants to
  2138. override default mime types. */
  2139. list = ctx->config[EXTRA_MIME_TYPES];
  2140. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  2141. /* ext now points to the path suffix */
  2142. ext = path + path_len - ext_vec.len;
  2143. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  2144. *vec = mime_vec;
  2145. return;
  2146. }
  2147. }
  2148. vec->ptr = mg_get_builtin_mime_type(path);
  2149. vec->len = strlen(vec->ptr);
  2150. }
  2151. /* Stringify binary data. Output buffer must be twice as big as input,
  2152. because each byte takes 2 bytes in string representation */
  2153. static void bin2str(char *to, const unsigned char *p, size_t len)
  2154. {
  2155. static const char *hex = "0123456789abcdef";
  2156. for (; len--; p++) {
  2157. *to++ = hex[p[0] >> 4];
  2158. *to++ = hex[p[0] & 0x0f];
  2159. }
  2160. *to = '\0';
  2161. }
  2162. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  2163. char *mg_md5(char buf[33], ...)
  2164. {
  2165. md5_byte_t hash[16];
  2166. const char *p;
  2167. va_list ap;
  2168. md5_state_t ctx;
  2169. md5_init(&ctx);
  2170. va_start(ap, buf);
  2171. while ((p = va_arg(ap, const char *)) != NULL) {
  2172. md5_append(&ctx, (const md5_byte_t *) p, (int) strlen(p));
  2173. }
  2174. va_end(ap);
  2175. md5_finish(&ctx, hash);
  2176. bin2str(buf, hash, sizeof(hash));
  2177. return buf;
  2178. }
  2179. /* Check the user's password, return 1 if OK */
  2180. static int check_password(const char *method, const char *ha1, const char *uri,
  2181. const char *nonce, const char *nc, const char *cnonce,
  2182. const char *qop, const char *response)
  2183. {
  2184. char ha2[32 + 1], expected_response[32 + 1];
  2185. /* Some of the parameters may be NULL */
  2186. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  2187. qop == NULL || response == NULL) {
  2188. return 0;
  2189. }
  2190. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  2191. /* TODO(lsm): check for authentication timeout */
  2192. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  2193. strlen(response) != 32
  2194. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  2195. ) {
  2196. return 0;
  2197. }
  2198. mg_md5(ha2, method, ":", uri, NULL);
  2199. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  2200. ":", cnonce, ":", qop, ":", ha2, NULL);
  2201. return mg_strcasecmp(response, expected_response) == 0;
  2202. }
  2203. /* Use the global passwords file, if specified by auth_gpass option,
  2204. or search for .htpasswd in the requested directory. */
  2205. static void open_auth_file(struct mg_connection *conn, const char *path,
  2206. struct file *filep)
  2207. {
  2208. char name[PATH_MAX];
  2209. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  2210. struct file file = STRUCT_FILE_INITIALIZER;
  2211. if (gpass != NULL) {
  2212. /* Use global passwords file */
  2213. if (!mg_fopen(conn, gpass, "r", filep)) {
  2214. #ifdef DEBUG
  2215. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  2216. #endif
  2217. }
  2218. /* Important: using local struct file to test path for is_directory
  2219. flag.
  2220. If filep is used, mg_stat() makes it appear as if auth file was
  2221. opened. */
  2222. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  2223. mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  2224. path, '/', PASSWORDS_FILE_NAME);
  2225. if (!mg_fopen(conn, name, "r", filep)) {
  2226. #ifdef DEBUG
  2227. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2228. #endif
  2229. }
  2230. } else {
  2231. /* Try to find .htpasswd in requested directory. */
  2232. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  2233. if (e[0] == '/')
  2234. break;
  2235. mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  2236. (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
  2237. if (!mg_fopen(conn, name, "r", filep)) {
  2238. #ifdef DEBUG
  2239. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2240. #endif
  2241. }
  2242. }
  2243. }
  2244. /* Parsed Authorization header */
  2245. struct ah {
  2246. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  2247. };
  2248. /* Return 1 on success. Always initializes the ah structure. */
  2249. static int parse_auth_header(struct mg_connection *conn, char *buf,
  2250. size_t buf_size, struct ah *ah)
  2251. {
  2252. char *name, *value, *s;
  2253. const char *auth_header;
  2254. (void) memset(ah, 0, sizeof(*ah));
  2255. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  2256. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  2257. return 0;
  2258. }
  2259. /* Make modifiable copy of the auth header */
  2260. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  2261. s = buf;
  2262. /* Parse authorization header */
  2263. for (;;) {
  2264. /* Gobble initial spaces */
  2265. while (isspace(* (unsigned char *) s)) {
  2266. s++;
  2267. }
  2268. name = skip_quoted(&s, "=", " ", 0);
  2269. /* Value is either quote-delimited, or ends at first comma or space. */
  2270. if (s[0] == '\"') {
  2271. s++;
  2272. value = skip_quoted(&s, "\"", " ", '\\');
  2273. if (s[0] == ',') {
  2274. s++;
  2275. }
  2276. } else {
  2277. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  2278. spaces */
  2279. }
  2280. if (*name == '\0') {
  2281. break;
  2282. }
  2283. if (!strcmp(name, "username")) {
  2284. ah->user = value;
  2285. } else if (!strcmp(name, "cnonce")) {
  2286. ah->cnonce = value;
  2287. } else if (!strcmp(name, "response")) {
  2288. ah->response = value;
  2289. } else if (!strcmp(name, "uri")) {
  2290. ah->uri = value;
  2291. } else if (!strcmp(name, "qop")) {
  2292. ah->qop = value;
  2293. } else if (!strcmp(name, "nc")) {
  2294. ah->nc = value;
  2295. } else if (!strcmp(name, "nonce")) {
  2296. ah->nonce = value;
  2297. }
  2298. }
  2299. /* CGI needs it as REMOTE_USER */
  2300. if (ah->user != NULL) {
  2301. conn->request_info.remote_user = mg_strdup(ah->user);
  2302. } else {
  2303. return 0;
  2304. }
  2305. return 1;
  2306. }
  2307. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  2308. {
  2309. char *eof;
  2310. size_t len;
  2311. char *memend;
  2312. if (filep->membuf != NULL && *p != NULL) {
  2313. memend = (char *) &filep->membuf[filep->size];
  2314. eof = (char *) memchr(*p, '\n', memend - *p); /* Search for \n from p
  2315. till the end of
  2316. stream */
  2317. if (eof != NULL) {
  2318. eof += 1; /* Include \n */
  2319. } else {
  2320. eof = memend; /* Copy remaining data */
  2321. }
  2322. len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
  2323. memcpy(buf, *p, len);
  2324. buf[len] = '\0';
  2325. *p += len;
  2326. return len ? eof : NULL;
  2327. } else if (filep->fp != NULL) {
  2328. return fgets(buf, (int)size, filep->fp);
  2329. } else {
  2330. return NULL;
  2331. }
  2332. }
  2333. /* Authorize against the opened passwords file. Return 1 if authorized. */
  2334. static int authorize(struct mg_connection *conn, struct file *filep)
  2335. {
  2336. struct ah ah;
  2337. char line[256], f_user[256] = "", ha1[256] = "", f_domain[256] = "", buf[MG_BUF_LEN], *p;
  2338. if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
  2339. return 0;
  2340. }
  2341. /* Loop over passwords file */
  2342. p = (char *) filep->membuf;
  2343. while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
  2344. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  2345. continue;
  2346. }
  2347. if (!strcmp(ah.user, f_user) &&
  2348. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
  2349. return check_password(conn->request_info.request_method, ha1, ah.uri,
  2350. ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
  2351. }
  2352. return 0;
  2353. }
  2354. /* Return 1 if request is authorised, 0 otherwise. */
  2355. static int check_authorization(struct mg_connection *conn, const char *path)
  2356. {
  2357. char fname[PATH_MAX];
  2358. struct vec uri_vec, filename_vec;
  2359. const char *list;
  2360. struct file file = STRUCT_FILE_INITIALIZER;
  2361. int authorized = 1;
  2362. list = conn->ctx->config[PROTECT_URI];
  2363. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2364. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2365. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2366. (int) filename_vec.len, filename_vec.ptr);
  2367. if (!mg_fopen(conn, fname, "r", &file)) {
  2368. mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2369. }
  2370. break;
  2371. }
  2372. }
  2373. if (!is_file_opened(&file)) {
  2374. open_auth_file(conn, path, &file);
  2375. }
  2376. if (is_file_opened(&file)) {
  2377. authorized = authorize(conn, &file);
  2378. mg_fclose(&file);
  2379. }
  2380. return authorized;
  2381. }
  2382. static void send_authorization_request(struct mg_connection *conn)
  2383. {
  2384. conn->status_code = 401;
  2385. mg_printf(conn,
  2386. "HTTP/1.1 401 Unauthorized\r\n"
  2387. "Content-Length: 0\r\n"
  2388. "WWW-Authenticate: Digest qop=\"auth\", "
  2389. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2390. conn->ctx->config[AUTHENTICATION_DOMAIN],
  2391. (unsigned long) time(NULL));
  2392. }
  2393. static int is_authorized_for_put(struct mg_connection *conn)
  2394. {
  2395. struct file file = STRUCT_FILE_INITIALIZER;
  2396. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  2397. int ret = 0;
  2398. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  2399. ret = authorize(conn, &file);
  2400. mg_fclose(&file);
  2401. }
  2402. return ret;
  2403. }
  2404. int mg_modify_passwords_file(const char *fname, const char *domain,
  2405. const char *user, const char *pass)
  2406. {
  2407. int found;
  2408. char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+1];
  2409. FILE *fp, *fp2;
  2410. found = 0;
  2411. fp = fp2 = NULL;
  2412. /* Regard empty password as no password - remove user record. */
  2413. if (pass != NULL && pass[0] == '\0') {
  2414. pass = NULL;
  2415. }
  2416. (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  2417. tmp[sizeof(tmp) - 1] = 0;
  2418. /* Create the file if does not exist */
  2419. if ((fp = fopen(fname, "a+")) != NULL) {
  2420. (void) fclose(fp);
  2421. }
  2422. /* Open the given file and temporary file */
  2423. if ((fp = fopen(fname, "r")) == NULL) {
  2424. return 0;
  2425. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  2426. fclose(fp);
  2427. return 0;
  2428. }
  2429. /* Copy the stuff to temporary file */
  2430. while (fgets(line, sizeof(line), fp) != NULL) {
  2431. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2432. continue;
  2433. }
  2434. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2435. found++;
  2436. if (pass != NULL) {
  2437. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2438. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2439. }
  2440. } else {
  2441. fprintf(fp2, "%s", line);
  2442. }
  2443. }
  2444. /* If new user, just add it */
  2445. if (!found && pass != NULL) {
  2446. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2447. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2448. }
  2449. /* Close files */
  2450. fclose(fp);
  2451. fclose(fp2);
  2452. /* Put the temp file in place of real file */
  2453. IGNORE_UNUSED_RESULT(remove(fname));
  2454. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  2455. return 1;
  2456. }
  2457. static SOCKET conn2(struct mg_context *ctx /* may be null */, const char *host, int port,
  2458. int use_ssl, char *ebuf, size_t ebuf_len)
  2459. {
  2460. struct sockaddr_in sain;
  2461. struct hostent *he;
  2462. SOCKET sock = INVALID_SOCKET;
  2463. if (host == NULL) {
  2464. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  2465. } else if (use_ssl && SSLv23_client_method == NULL) {
  2466. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  2467. /* TODO(lsm): use something threadsafe instead of gethostbyname() */
  2468. } else if ((he = gethostbyname(host)) == NULL) {
  2469. snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
  2470. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  2471. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  2472. } else {
  2473. set_close_on_exec(sock, fc(ctx));
  2474. memset(&sain, '\0', sizeof(sain));
  2475. sain.sin_family = AF_INET;
  2476. sain.sin_port = htons((uint16_t) port);
  2477. sain.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  2478. if (connect(sock, (struct sockaddr *) &sain, sizeof(sain)) != 0) {
  2479. snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
  2480. host, port, strerror(ERRNO));
  2481. closesocket(sock);
  2482. sock = INVALID_SOCKET;
  2483. }
  2484. }
  2485. return sock;
  2486. }
  2487. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  2488. {
  2489. static const char *dont_escape = "._-$,;~()";
  2490. static const char *hex = "0123456789abcdef";
  2491. char *pos = dst;
  2492. const char *end = dst + dst_len - 1;
  2493. for (; *src != '\0' && pos < end; src++, pos++) {
  2494. if (isalnum(*(const unsigned char *) src) ||
  2495. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2496. *pos = *src;
  2497. } else if (pos + 2 < end) {
  2498. pos[0] = '%';
  2499. pos[1] = hex[(* (const unsigned char *) src) >> 4];
  2500. pos[2] = hex[(* (const unsigned char *) src) & 0xf];
  2501. pos += 2;
  2502. } else {
  2503. return -1;
  2504. }
  2505. }
  2506. *pos = '\0';
  2507. return (*src == '\0') ? (int)(pos - dst) : -1;
  2508. }
  2509. static void print_dir_entry(struct de *de)
  2510. {
  2511. char size[64], mod[64], href[PATH_MAX];
  2512. struct tm *tm;
  2513. if (de->file.is_directory) {
  2514. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2515. } else {
  2516. /* We use (signed) cast below because MSVC 6 compiler cannot
  2517. convert unsigned __int64 to double. Sigh. */
  2518. if (de->file.size < 1024) {
  2519. mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
  2520. } else if (de->file.size < 0x100000) {
  2521. mg_snprintf(de->conn, size, sizeof(size),
  2522. "%.1fk", (double) de->file.size / 1024.0);
  2523. } else if (de->file.size < 0x40000000) {
  2524. mg_snprintf(de->conn, size, sizeof(size),
  2525. "%.1fM", (double) de->file.size / 1048576);
  2526. } else {
  2527. mg_snprintf(de->conn, size, sizeof(size),
  2528. "%.1fG", (double) de->file.size / 1073741824);
  2529. }
  2530. }
  2531. tm = localtime(&de->file.modification_time);
  2532. if (tm != NULL) {
  2533. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  2534. } else {
  2535. strncpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  2536. mod[sizeof(mod) - 1] = '\0';
  2537. }
  2538. mg_url_encode(de->file_name, href, sizeof(href));
  2539. de->conn->num_bytes_sent += mg_printf(de->conn,
  2540. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2541. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2542. de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
  2543. de->file_name, de->file.is_directory ? "/" : "", mod, size);
  2544. }
  2545. /* This function is called from send_directory() and used for
  2546. sorting directory entries by size, or name, or modification time.
  2547. On windows, __cdecl specification is needed in case if project is built
  2548. with __stdcall convention. qsort always requires __cdels callback. */
  2549. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  2550. {
  2551. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2552. const char *query_string = a->conn->request_info.query_string;
  2553. int cmp_result = 0;
  2554. if (query_string == NULL) {
  2555. query_string = "na";
  2556. }
  2557. if (a->file.is_directory && !b->file.is_directory) {
  2558. return -1; /* Always put directories on top */
  2559. } else if (!a->file.is_directory && b->file.is_directory) {
  2560. return 1; /* Always put directories on top */
  2561. } else if (*query_string == 'n') {
  2562. cmp_result = strcmp(a->file_name, b->file_name);
  2563. } else if (*query_string == 's') {
  2564. cmp_result = a->file.size == b->file.size ? 0 :
  2565. a->file.size > b->file.size ? 1 : -1;
  2566. } else if (*query_string == 'd') {
  2567. cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
  2568. a->file.modification_time > b->file.modification_time ? 1 : -1;
  2569. }
  2570. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2571. }
  2572. static int must_hide_file(struct mg_connection *conn, const char *path)
  2573. {
  2574. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2575. const char *pattern = conn->ctx->config[HIDE_FILES];
  2576. return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
  2577. (pattern != NULL && match_prefix(pattern, (int)strlen(pattern), path) > 0);
  2578. }
  2579. static int scan_directory(struct mg_connection *conn, const char *dir,
  2580. void *data, void (*cb)(struct de *, void *))
  2581. {
  2582. char path[PATH_MAX];
  2583. struct dirent *dp;
  2584. DIR *dirp;
  2585. struct de de;
  2586. if ((dirp = opendir(dir)) == NULL) {
  2587. return 0;
  2588. } else {
  2589. de.conn = conn;
  2590. while ((dp = readdir(dirp)) != NULL) {
  2591. /* Do not show current dir and hidden files */
  2592. if (!strcmp(dp->d_name, ".") ||
  2593. !strcmp(dp->d_name, "..") ||
  2594. must_hide_file(conn, dp->d_name)) {
  2595. continue;
  2596. }
  2597. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2598. /* If we don't memset stat structure to zero, mtime will have
  2599. garbage and strftime() will segfault later on in
  2600. print_dir_entry(). memset is required only if mg_stat()
  2601. fails. For more details, see
  2602. http://code.google.com/p/mongoose/issues/detail?id=79 */
  2603. memset(&de.file, 0, sizeof(de.file));
  2604. if (!mg_stat(conn, path, &de.file)) {
  2605. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  2606. __func__, path, strerror(ERRNO));
  2607. }
  2608. de.file_name = dp->d_name;
  2609. cb(&de, data);
  2610. }
  2611. (void) closedir(dirp);
  2612. }
  2613. return 1;
  2614. }
  2615. static int remove_directory(struct mg_connection *conn, const char *dir)
  2616. {
  2617. char path[PATH_MAX];
  2618. struct dirent *dp;
  2619. DIR *dirp;
  2620. struct de de;
  2621. if ((dirp = opendir(dir)) == NULL) {
  2622. return 0;
  2623. } else {
  2624. de.conn = conn;
  2625. while ((dp = readdir(dirp)) != NULL) {
  2626. /* Do not show current dir (but show hidden files as they will
  2627. also be removed) */
  2628. if (!strcmp(dp->d_name, ".") ||
  2629. !strcmp(dp->d_name, "..")) {
  2630. continue;
  2631. }
  2632. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2633. /* If we don't memset stat structure to zero, mtime will have
  2634. garbage and strftime() will segfault later on in
  2635. print_dir_entry(). memset is required only if mg_stat()
  2636. fails. For more details, see
  2637. http://code.google.com/p/mongoose/issues/detail?id=79 */
  2638. memset(&de.file, 0, sizeof(de.file));
  2639. if (!mg_stat(conn, path, &de.file)) {
  2640. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  2641. __func__, path, strerror(ERRNO));
  2642. }
  2643. if(de.file.modification_time) {
  2644. if(de.file.is_directory) {
  2645. remove_directory(conn, path);
  2646. } else {
  2647. mg_remove(path);
  2648. }
  2649. }
  2650. }
  2651. (void) closedir(dirp);
  2652. IGNORE_UNUSED_RESULT(rmdir(dir));
  2653. }
  2654. return 1;
  2655. }
  2656. struct dir_scan_data {
  2657. struct de *entries;
  2658. int num_entries;
  2659. int arr_size;
  2660. };
  2661. /* Behaves like realloc(), but frees original pointer on failure */
  2662. static void *realloc2(void *ptr, size_t size)
  2663. {
  2664. void *new_ptr = realloc(ptr, size);
  2665. if (new_ptr == NULL) {
  2666. free(ptr);
  2667. }
  2668. return new_ptr;
  2669. }
  2670. static void dir_scan_callback(struct de *de, void *data)
  2671. {
  2672. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2673. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2674. dsd->arr_size *= 2;
  2675. dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
  2676. sizeof(dsd->entries[0]));
  2677. }
  2678. if (dsd->entries == NULL) {
  2679. /* TODO(lsm): propagate an error to the caller */
  2680. dsd->num_entries = 0;
  2681. } else {
  2682. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2683. dsd->entries[dsd->num_entries].file = de->file;
  2684. dsd->entries[dsd->num_entries].conn = de->conn;
  2685. dsd->num_entries++;
  2686. }
  2687. }
  2688. static void handle_directory_request(struct mg_connection *conn,
  2689. const char *dir)
  2690. {
  2691. int i, sort_direction;
  2692. struct dir_scan_data data = { NULL, 0, 128 };
  2693. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2694. send_http_error(conn, 500, "Cannot open directory",
  2695. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2696. return;
  2697. }
  2698. sort_direction = conn->request_info.query_string != NULL &&
  2699. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2700. conn->must_close = 1;
  2701. mg_printf(conn, "%s",
  2702. "HTTP/1.1 200 OK\r\n"
  2703. "Connection: close\r\n"
  2704. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2705. conn->num_bytes_sent += mg_printf(conn,
  2706. "<html><head><title>Index of %s</title>"
  2707. "<style>th {text-align: left;}</style></head>"
  2708. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2709. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2710. "<th><a href=\"?d%c\">Modified</a></th>"
  2711. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2712. "<tr><td colspan=\"3\"><hr></td></tr>",
  2713. conn->request_info.uri, conn->request_info.uri,
  2714. sort_direction, sort_direction, sort_direction);
  2715. /* Print first entry - link to a parent directory */
  2716. conn->num_bytes_sent += mg_printf(conn,
  2717. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2718. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2719. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2720. /* Sort and print directory entries */
  2721. if (data.entries != NULL) {
  2722. qsort(data.entries, (size_t) data.num_entries,
  2723. sizeof(data.entries[0]), compare_dir_entries);
  2724. for (i = 0; i < data.num_entries; i++) {
  2725. print_dir_entry(&data.entries[i]);
  2726. free(data.entries[i].file_name);
  2727. }
  2728. free(data.entries);
  2729. }
  2730. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2731. conn->status_code = 200;
  2732. }
  2733. /* Send len bytes from the opened file to the client. */
  2734. static void send_file_data(struct mg_connection *conn, struct file *filep,
  2735. int64_t offset, int64_t len)
  2736. {
  2737. char buf[MG_BUF_LEN];
  2738. int to_read, num_read, num_written;
  2739. /* Sanity check the offset */
  2740. offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
  2741. if (len > 0 && filep->membuf != NULL && filep->size > 0) {
  2742. if (len > filep->size - offset) {
  2743. len = filep->size - offset;
  2744. }
  2745. mg_write(conn, filep->membuf + offset, (size_t) len);
  2746. } else if (len > 0 && filep->fp != NULL) {
  2747. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  2748. mg_cry(conn, "%s: fseeko() failed: %s",
  2749. __func__, strerror(ERRNO));
  2750. }
  2751. while (len > 0) {
  2752. /* Calculate how much to read from the file in the buffer */
  2753. to_read = sizeof(buf);
  2754. if ((int64_t) to_read > len) {
  2755. to_read = (int) len;
  2756. }
  2757. /* Read from file, exit the loop on error */
  2758. if ((num_read = (int) fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
  2759. break;
  2760. }
  2761. /* Send read bytes to the client, exit the loop on error */
  2762. if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
  2763. break;
  2764. }
  2765. /* Both read and were successful, adjust counters */
  2766. conn->num_bytes_sent += num_written;
  2767. len -= num_written;
  2768. }
  2769. }
  2770. }
  2771. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  2772. {
  2773. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2774. }
  2775. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2776. {
  2777. struct tm *tm;
  2778. tm = gmtime(t);
  2779. if (tm != NULL) {
  2780. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2781. } else {
  2782. strncpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2783. buf[buf_len - 1] = '\0';
  2784. }
  2785. }
  2786. static void construct_etag(char *buf, size_t buf_len,
  2787. const struct file *filep)
  2788. {
  2789. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2790. (unsigned long) filep->modification_time, filep->size);
  2791. }
  2792. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  2793. {
  2794. if (filep != NULL && filep->fp != NULL) {
  2795. #ifdef _WIN32
  2796. (void) conn; /* Unused. */
  2797. #else
  2798. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  2799. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2800. __func__, strerror(ERRNO));
  2801. }
  2802. #endif
  2803. }
  2804. }
  2805. static void handle_file_request(struct mg_connection *conn, const char *path,
  2806. struct file *filep)
  2807. {
  2808. char date[64], lm[64], etag[64], range[64];
  2809. const char *msg = "OK", *hdr;
  2810. time_t curtime = time(NULL);
  2811. int64_t cl, r1, r2;
  2812. struct vec mime_vec;
  2813. int n;
  2814. char gz_path[PATH_MAX];
  2815. char const* encoding = "";
  2816. get_mime_type(conn->ctx, path, &mime_vec);
  2817. cl = filep->size;
  2818. conn->status_code = 200;
  2819. range[0] = '\0';
  2820. /* if this file is in fact a pre-gzipped file, rewrite its filename
  2821. it's important to rewrite the filename after resolving
  2822. the mime type from it, to preserve the actual file's type */
  2823. if (filep->gzipped) {
  2824. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  2825. path = gz_path;
  2826. encoding = "Content-Encoding: gzip\r\n";
  2827. }
  2828. if (!mg_fopen(conn, path, "rb", filep)) {
  2829. send_http_error(conn, 500, http_500_error,
  2830. "fopen(%s): %s", path, strerror(ERRNO));
  2831. return;
  2832. }
  2833. fclose_on_exec(filep, conn);
  2834. /* If Range: header specified, act accordingly */
  2835. r1 = r2 = 0;
  2836. hdr = mg_get_header(conn, "Range");
  2837. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  2838. r1 >= 0 && r2 >= 0) {
  2839. /* actually, range requests don't play well with a pre-gzipped
  2840. file (since the range is specified in the uncompressed space) */
  2841. if (filep->gzipped) {
  2842. send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
  2843. mg_fclose(filep);
  2844. return;
  2845. }
  2846. conn->status_code = 206;
  2847. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
  2848. mg_snprintf(conn, range, sizeof(range),
  2849. "Content-Range: bytes "
  2850. "%" INT64_FMT "-%"
  2851. INT64_FMT "/%" INT64_FMT "\r\n",
  2852. r1, r1 + cl - 1, filep->size);
  2853. msg = "Partial Content";
  2854. }
  2855. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2856. http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  2857. gmt_time_string(date, sizeof(date), &curtime);
  2858. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  2859. construct_etag(etag, sizeof(etag), filep);
  2860. (void) mg_printf(conn,
  2861. "HTTP/1.1 %d %s\r\n"
  2862. "Date: %s\r\n"
  2863. "Last-Modified: %s\r\n"
  2864. "Etag: %s\r\n"
  2865. "Content-Type: %.*s\r\n"
  2866. "Content-Length: %" INT64_FMT "\r\n"
  2867. "Connection: %s\r\n"
  2868. "Accept-Ranges: bytes\r\n"
  2869. "%s%s\r\n",
  2870. conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
  2871. mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
  2872. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2873. send_file_data(conn, filep, r1, cl);
  2874. }
  2875. mg_fclose(filep);
  2876. }
  2877. void mg_send_file(struct mg_connection *conn, const char *path)
  2878. {
  2879. struct file file = STRUCT_FILE_INITIALIZER;
  2880. if (mg_stat(conn, path, &file)) {
  2881. handle_file_request(conn, path, &file);
  2882. } else {
  2883. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2884. }
  2885. }
  2886. /* Parse HTTP headers from the given buffer, advance buffer to the point
  2887. where parsing stopped. */
  2888. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  2889. {
  2890. int i;
  2891. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2892. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2893. ri->http_headers[i].value = skip(buf, "\r\n");
  2894. if (ri->http_headers[i].name[0] == '\0')
  2895. break;
  2896. ri->num_headers = i + 1;
  2897. }
  2898. }
  2899. static int is_valid_http_method(const char *method)
  2900. {
  2901. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2902. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2903. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2904. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  2905. || !strcmp(method, "MKCOL")
  2906. ;
  2907. }
  2908. /* Parse HTTP request, fill in mg_request_info structure.
  2909. This function modifies the buffer by NUL-terminating
  2910. HTTP request components, header names and header values. */
  2911. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  2912. {
  2913. int is_request, request_length = get_request_len(buf, len);
  2914. if (request_length > 0) {
  2915. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port */
  2916. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2917. ri->num_headers = 0;
  2918. buf[request_length - 1] = '\0';
  2919. /* RFC says that all initial whitespaces should be ingored */
  2920. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2921. buf++;
  2922. }
  2923. ri->request_method = skip(&buf, " ");
  2924. ri->uri = skip(&buf, " ");
  2925. ri->http_version = skip(&buf, "\r\n");
  2926. /* HTTP message could be either HTTP request or HTTP response, e.g.
  2927. "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  2928. is_request = is_valid_http_method(ri->request_method);
  2929. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  2930. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  2931. request_length = -1;
  2932. } else {
  2933. if (is_request) {
  2934. ri->http_version += 5;
  2935. }
  2936. parse_http_headers(&buf, ri);
  2937. }
  2938. }
  2939. return request_length;
  2940. }
  2941. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  2942. or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2943. buffer (which marks the end of HTTP request). Buffer buf may already
  2944. have some data. The length of the data is stored in nread.
  2945. Upon every read operation, increase nread by the number of bytes read. */
  2946. static int read_request(FILE *fp, struct mg_connection *conn,
  2947. char *buf, int bufsiz, int *nread)
  2948. {
  2949. int request_len, n = 0;
  2950. request_len = get_request_len(buf, *nread);
  2951. while (conn->ctx->stop_flag == 0 &&
  2952. *nread < bufsiz && request_len == 0 &&
  2953. (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
  2954. *nread += n;
  2955. assert(*nread <= bufsiz);
  2956. request_len = get_request_len(buf, *nread);
  2957. }
  2958. return request_len <= 0 && n <= 0 ? -1 : request_len;
  2959. }
  2960. /* For given directory path, substitute it to valid index file.
  2961. Return 0 if index file has been found, -1 if not found.
  2962. If the file is found, it's stats is returned in stp. */
  2963. static int substitute_index_file(struct mg_connection *conn, char *path,
  2964. size_t path_len, struct file *filep)
  2965. {
  2966. const char *list = conn->ctx->config[INDEX_FILES];
  2967. struct file file = STRUCT_FILE_INITIALIZER;
  2968. struct vec filename_vec;
  2969. size_t n = strlen(path);
  2970. int found = 0;
  2971. /* The 'path' given to us points to the directory. Remove all trailing
  2972. directory separator characters from the end of the path, and
  2973. then append single directory separator character. */
  2974. while (n > 0 && path[n - 1] == '/') {
  2975. n--;
  2976. }
  2977. path[n] = '/';
  2978. /* Traverse index files list. For each entry, append it to the given
  2979. path and see if the file exists. If it exists, break the loop */
  2980. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2981. /* Ignore too long entries that may overflow path buffer */
  2982. if (filename_vec.len > path_len - (n + 2))
  2983. continue;
  2984. /* Prepare full path to the index file */
  2985. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2986. /* Does it exist? */
  2987. if (mg_stat(conn, path, &file)) {
  2988. /* Yes it does, break the loop */
  2989. *filep = file;
  2990. found = 1;
  2991. break;
  2992. }
  2993. }
  2994. /* If no index file exists, restore directory path */
  2995. if (!found) {
  2996. path[n] = '\0';
  2997. }
  2998. return found;
  2999. }
  3000. /* Return True if we should reply 304 Not Modified. */
  3001. static int is_not_modified(const struct mg_connection *conn,
  3002. const struct file *filep)
  3003. {
  3004. char etag[64];
  3005. const char *ims = mg_get_header(conn, "If-Modified-Since");
  3006. const char *inm = mg_get_header(conn, "If-None-Match");
  3007. construct_etag(etag, sizeof(etag), filep);
  3008. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  3009. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  3010. }
  3011. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  3012. SOCKET sock, SSL *ssl)
  3013. {
  3014. const char *expect, *body;
  3015. char buf[MG_BUF_LEN];
  3016. int to_read, nread, buffered_len, success = 0;
  3017. expect = mg_get_header(conn, "Expect");
  3018. assert(fp != NULL);
  3019. if (conn->content_len == -1) {
  3020. send_http_error(conn, 411, "Length Required", "%s", "");
  3021. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  3022. send_http_error(conn, 417, "Expectation Failed", "%s", "");
  3023. } else {
  3024. if (expect != NULL) {
  3025. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  3026. }
  3027. body = conn->buf + conn->request_len + conn->consumed_content;
  3028. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  3029. assert(buffered_len >= 0);
  3030. assert(conn->consumed_content == 0);
  3031. if (buffered_len > 0) {
  3032. if ((int64_t) buffered_len > conn->content_len) {
  3033. buffered_len = (int) conn->content_len;
  3034. }
  3035. push(fp, sock, ssl, body, (int64_t) buffered_len);
  3036. conn->consumed_content += buffered_len;
  3037. }
  3038. nread = 0;
  3039. while (conn->consumed_content < conn->content_len) {
  3040. to_read = sizeof(buf);
  3041. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  3042. to_read = (int) (conn->content_len - conn->consumed_content);
  3043. }
  3044. nread = pull(NULL, conn, buf, to_read);
  3045. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  3046. break;
  3047. }
  3048. conn->consumed_content += nread;
  3049. }
  3050. if (conn->consumed_content == conn->content_len) {
  3051. success = nread >= 0;
  3052. }
  3053. /* Each error code path in this function must send an error */
  3054. if (!success) {
  3055. send_http_error(conn, 577, http_500_error, "%s", "");
  3056. }
  3057. }
  3058. return success;
  3059. }
  3060. #if !defined(NO_CGI)
  3061. /* This structure helps to create an environment for the spawned CGI program.
  3062. Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  3063. last element must be NULL.
  3064. However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  3065. strings must reside in a contiguous buffer. The end of the buffer is
  3066. marked by two '\0' characters.
  3067. We satisfy both worlds: we create an envp array (which is vars), all
  3068. entries are actually pointers inside buf. */
  3069. struct cgi_env_block {
  3070. struct mg_connection *conn;
  3071. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  3072. int len; /* Space taken */
  3073. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  3074. int nvars; /* Number of variables */
  3075. };
  3076. static char *addenv(struct cgi_env_block *block,
  3077. PRINTF_FORMAT_STRING(const char *fmt), ...)
  3078. PRINTF_ARGS(2, 3);
  3079. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  3080. pointer into the vars array. */
  3081. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  3082. {
  3083. int n, space;
  3084. char *added;
  3085. va_list ap;
  3086. /* Calculate how much space is left in the buffer */
  3087. space = sizeof(block->buf) - block->len - 2;
  3088. assert(space >= 0);
  3089. /* Make a pointer to the free space int the buffer */
  3090. added = block->buf + block->len;
  3091. /* Copy VARIABLE=VALUE\0 string into the free space */
  3092. va_start(ap, fmt);
  3093. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  3094. va_end(ap);
  3095. /* Make sure we do not overflow buffer and the envp array */
  3096. if (n > 0 && n + 1 < space &&
  3097. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  3098. /* Append a pointer to the added string into the envp array */
  3099. block->vars[block->nvars++] = added;
  3100. /* Bump up used length counter. Include \0 terminator */
  3101. block->len += n + 1;
  3102. } else {
  3103. mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  3104. }
  3105. return added;
  3106. }
  3107. static void prepare_cgi_environment(struct mg_connection *conn,
  3108. const char *prog,
  3109. struct cgi_env_block *blk)
  3110. {
  3111. const char *s, *slash;
  3112. struct vec var_vec;
  3113. char *p, src_addr[IP_ADDR_STR_LEN];
  3114. int i;
  3115. blk->len = blk->nvars = 0;
  3116. blk->conn = conn;
  3117. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3118. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  3119. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3120. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3121. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  3122. /* Prepare the environment block */
  3123. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  3124. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  3125. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  3126. /* TODO(lsm): fix this for IPv6 case */
  3127. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  3128. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  3129. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  3130. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  3131. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  3132. /* SCRIPT_NAME */
  3133. assert(conn->request_info.uri[0] == '/');
  3134. slash = strrchr(conn->request_info.uri, '/');
  3135. if ((s = strrchr(prog, '/')) == NULL)
  3136. s = prog;
  3137. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  3138. conn->request_info.uri, s);
  3139. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  3140. addenv(blk, "PATH_TRANSLATED=%s", prog);
  3141. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  3142. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  3143. addenv(blk, "CONTENT_TYPE=%s", s);
  3144. if (conn->request_info.query_string != NULL)
  3145. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  3146. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  3147. addenv(blk, "CONTENT_LENGTH=%s", s);
  3148. if ((s = getenv("PATH")) != NULL)
  3149. addenv(blk, "PATH=%s", s);
  3150. if (conn->path_info != NULL) {
  3151. addenv(blk, "PATH_INFO=%s", conn->path_info);
  3152. }
  3153. #if defined(_WIN32)
  3154. if ((s = getenv("COMSPEC")) != NULL) {
  3155. addenv(blk, "COMSPEC=%s", s);
  3156. }
  3157. if ((s = getenv("SYSTEMROOT")) != NULL) {
  3158. addenv(blk, "SYSTEMROOT=%s", s);
  3159. }
  3160. if ((s = getenv("SystemDrive")) != NULL) {
  3161. addenv(blk, "SystemDrive=%s", s);
  3162. }
  3163. if ((s = getenv("ProgramFiles")) != NULL) {
  3164. addenv(blk, "ProgramFiles=%s", s);
  3165. }
  3166. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  3167. addenv(blk, "ProgramFiles(x86)=%s", s);
  3168. }
  3169. #else
  3170. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  3171. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  3172. #endif /* _WIN32 */
  3173. if ((s = getenv("PERLLIB")) != NULL)
  3174. addenv(blk, "PERLLIB=%s", s);
  3175. if (conn->request_info.remote_user != NULL) {
  3176. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  3177. addenv(blk, "%s", "AUTH_TYPE=Digest");
  3178. }
  3179. /* Add all headers as HTTP_* variables */
  3180. for (i = 0; i < conn->request_info.num_headers; i++) {
  3181. p = addenv(blk, "HTTP_%s=%s",
  3182. conn->request_info.http_headers[i].name,
  3183. conn->request_info.http_headers[i].value);
  3184. /* Convert variable name into uppercase, and change - to _ */
  3185. for (; *p != '=' && *p != '\0'; p++) {
  3186. if (*p == '-')
  3187. *p = '_';
  3188. *p = (char) toupper(* (unsigned char *) p);
  3189. }
  3190. }
  3191. /* Add user-specified variables */
  3192. s = conn->ctx->config[CGI_ENVIRONMENT];
  3193. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  3194. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  3195. }
  3196. blk->vars[blk->nvars++] = NULL;
  3197. blk->buf[blk->len++] = '\0';
  3198. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  3199. assert(blk->len > 0);
  3200. assert(blk->len < (int) sizeof(blk->buf));
  3201. }
  3202. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  3203. {
  3204. char *buf;
  3205. size_t buflen;
  3206. int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
  3207. const char *status, *status_text, *connection_state;
  3208. char *pbuf, dir[PATH_MAX], *p;
  3209. struct mg_request_info ri;
  3210. struct cgi_env_block blk;
  3211. FILE *in = NULL, *out = NULL;
  3212. struct file fout = STRUCT_FILE_INITIALIZER;
  3213. pid_t pid = (pid_t) -1;
  3214. buf = NULL;
  3215. buflen = 16384;
  3216. prepare_cgi_environment(conn, prog, &blk);
  3217. /* CGI must be executed in its own directory. 'dir' must point to the
  3218. directory containing executable program, 'p' must point to the
  3219. executable program name relative to 'dir'. */
  3220. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  3221. if ((p = strrchr(dir, '/')) != NULL) {
  3222. *p++ = '\0';
  3223. } else {
  3224. dir[0] = '.', dir[1] = '\0';
  3225. p = (char *) prog;
  3226. }
  3227. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  3228. send_http_error(conn, 500, http_500_error,
  3229. "Cannot create CGI pipe: %s", strerror(ERRNO));
  3230. goto done;
  3231. }
  3232. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  3233. if (pid == (pid_t) -1) {
  3234. send_http_error(conn, 500, http_500_error,
  3235. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  3236. goto done;
  3237. }
  3238. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  3239. set_close_on_exec(fdin[0], conn);
  3240. set_close_on_exec(fdin[1], conn);
  3241. set_close_on_exec(fdout[0], conn);
  3242. set_close_on_exec(fdout[1], conn);
  3243. /* Parent closes only one side of the pipes.
  3244. If we don't mark them as closed, close() attempt before
  3245. return from this function throws an exception on Windows.
  3246. Windows does not like when closed descriptor is closed again. */
  3247. (void) close(fdin[0]);
  3248. (void) close(fdout[1]);
  3249. fdin[0] = fdout[1] = -1;
  3250. if ((in = fdopen(fdin[1], "wb")) == NULL ||
  3251. (out = fdopen(fdout[0], "rb")) == NULL) {
  3252. send_http_error(conn, 500, http_500_error,
  3253. "fopen: %s", strerror(ERRNO));
  3254. goto done;
  3255. }
  3256. setbuf(in, NULL);
  3257. setbuf(out, NULL);
  3258. fout.fp = out;
  3259. /* Send POST data to the CGI process if needed */
  3260. if (!strcmp(conn->request_info.request_method, "POST") &&
  3261. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  3262. goto done;
  3263. }
  3264. /* Close so child gets an EOF. */
  3265. fclose(in);
  3266. in = NULL;
  3267. fdin[1] = -1;
  3268. /* Now read CGI reply into a buffer. We need to set correct
  3269. status code, thus we need to see all HTTP headers first.
  3270. Do not send anything back to client, until we buffer in all
  3271. HTTP headers. */
  3272. data_len = 0;
  3273. buf = malloc(buflen);
  3274. if (buf == NULL) {
  3275. send_http_error(conn, 500, http_500_error,
  3276. "Not enough memory for buffer (%u bytes)",
  3277. (unsigned int) buflen);
  3278. goto done;
  3279. }
  3280. headers_len = read_request(out, conn, buf, (int) buflen, &data_len);
  3281. if (headers_len <= 0) {
  3282. send_http_error(conn, 500, http_500_error,
  3283. "CGI program sent malformed or too big (>%u bytes) "
  3284. "HTTP headers: [%.*s]",
  3285. (unsigned) buflen, data_len, buf);
  3286. goto done;
  3287. }
  3288. pbuf = buf;
  3289. buf[headers_len - 1] = '\0';
  3290. parse_http_headers(&pbuf, &ri);
  3291. /* Make up and send the status line */
  3292. status_text = "OK";
  3293. if ((status = get_header(&ri, "Status")) != NULL) {
  3294. conn->status_code = atoi(status);
  3295. status_text = status;
  3296. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  3297. status_text++;
  3298. }
  3299. } else if (get_header(&ri, "Location") != NULL) {
  3300. conn->status_code = 302;
  3301. } else {
  3302. conn->status_code = 200;
  3303. }
  3304. connection_state = get_header(&ri, "Connection");
  3305. if (connection_state == NULL ||
  3306. mg_strcasecmp(connection_state, "keep-alive")) {
  3307. conn->must_close = 1;
  3308. }
  3309. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
  3310. status_text);
  3311. /* Send headers */
  3312. for (i = 0; i < ri.num_headers; i++) {
  3313. mg_printf(conn, "%s: %s\r\n",
  3314. ri.http_headers[i].name, ri.http_headers[i].value);
  3315. }
  3316. mg_write(conn, "\r\n", 2);
  3317. /* Send chunk of data that may have been read after the headers */
  3318. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  3319. (size_t)(data_len - headers_len));
  3320. /* Read the rest of CGI output and send to the client */
  3321. send_file_data(conn, &fout, 0, INT64_MAX);
  3322. done:
  3323. if (pid != (pid_t) -1) {
  3324. kill(pid, SIGKILL);
  3325. #if !defined(_WIN32)
  3326. {
  3327. int st;
  3328. while (waitpid(pid, &st, 0) != -1); /* clean zombies */
  3329. }
  3330. #endif
  3331. }
  3332. if (fdin[0] != -1) {
  3333. close(fdin[0]);
  3334. }
  3335. if (fdout[1] != -1) {
  3336. close(fdout[1]);
  3337. }
  3338. if (in != NULL) {
  3339. fclose(in);
  3340. } else if (fdin[1] != -1) {
  3341. close(fdin[1]);
  3342. }
  3343. if (out != NULL) {
  3344. fclose(out);
  3345. } else if (fdout[0] != -1) {
  3346. close(fdout[0]);
  3347. }
  3348. if (buf != NULL) {
  3349. free(buf);
  3350. }
  3351. }
  3352. #endif /* !NO_CGI */
  3353. /* For a given PUT path, create all intermediate subdirectories
  3354. for given path. Return 0 if the path itself is a directory,
  3355. or -1 on error, 1 if OK. */
  3356. static int put_dir(struct mg_connection *conn, const char *path)
  3357. {
  3358. char buf[PATH_MAX];
  3359. const char *s, *p;
  3360. struct file file = STRUCT_FILE_INITIALIZER;
  3361. int len, res = 1;
  3362. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  3363. len = (int)(p - path);
  3364. if (len >= (int) sizeof(buf)) {
  3365. res = -1;
  3366. break;
  3367. }
  3368. memcpy(buf, path, len);
  3369. buf[len] = '\0';
  3370. /* Try to create intermediate directory */
  3371. DEBUG_TRACE(("mkdir(%s)", buf));
  3372. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  3373. res = -1;
  3374. break;
  3375. }
  3376. /* Is path itself a directory? */
  3377. if (p[1] == '\0') {
  3378. res = 0;
  3379. }
  3380. }
  3381. return res;
  3382. }
  3383. static void mkcol(struct mg_connection *conn, const char *path)
  3384. {
  3385. int rc, body_len;
  3386. struct de de;
  3387. memset(&de.file, 0, sizeof(de.file));
  3388. if (!mg_stat(conn, path, &de.file)) {
  3389. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  3390. __func__, path, strerror(ERRNO));
  3391. }
  3392. if(de.file.modification_time) {
  3393. send_http_error(conn, 405, "Method Not Allowed",
  3394. "mkcol(%s): %s", path, strerror(ERRNO));
  3395. return;
  3396. }
  3397. body_len = conn->data_len - conn->request_len;
  3398. if(body_len > 0) {
  3399. send_http_error(conn, 415, "Unsupported media type",
  3400. "mkcol(%s): %s", path, strerror(ERRNO));
  3401. return;
  3402. }
  3403. rc = mg_mkdir(path, 0755);
  3404. if (rc == 0) {
  3405. conn->status_code = 201;
  3406. mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code);
  3407. } else if (rc == -1) {
  3408. if(errno == EEXIST)
  3409. send_http_error(conn, 405, "Method Not Allowed",
  3410. "mkcol(%s): %s", path, strerror(ERRNO));
  3411. else if(errno == EACCES)
  3412. send_http_error(conn, 403, "Forbidden",
  3413. "mkcol(%s): %s", path, strerror(ERRNO));
  3414. else if(errno == ENOENT)
  3415. send_http_error(conn, 409, "Conflict",
  3416. "mkcol(%s): %s", path, strerror(ERRNO));
  3417. else
  3418. send_http_error(conn, 500, http_500_error,
  3419. "fopen(%s): %s", path, strerror(ERRNO));
  3420. }
  3421. }
  3422. static void put_file(struct mg_connection *conn, const char *path)
  3423. {
  3424. struct file file = STRUCT_FILE_INITIALIZER;
  3425. const char *range;
  3426. int64_t r1, r2;
  3427. int rc;
  3428. conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
  3429. if ((rc = put_dir(conn, path)) == 0) {
  3430. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
  3431. } else if (rc == -1) {
  3432. send_http_error(conn, 500, http_500_error,
  3433. "put_dir(%s): %s", path, strerror(ERRNO));
  3434. } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  3435. mg_fclose(&file);
  3436. send_http_error(conn, 500, http_500_error,
  3437. "fopen(%s): %s", path, strerror(ERRNO));
  3438. } else {
  3439. fclose_on_exec(&file, conn);
  3440. range = mg_get_header(conn, "Content-Range");
  3441. r1 = r2 = 0;
  3442. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3443. conn->status_code = 206;
  3444. fseeko(file.fp, r1, SEEK_SET);
  3445. }
  3446. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  3447. conn->status_code = 500;
  3448. }
  3449. mg_printf(conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
  3450. conn->status_code);
  3451. mg_fclose(&file);
  3452. }
  3453. }
  3454. static void send_ssi_file(struct mg_connection *, const char *,
  3455. struct file *, int);
  3456. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3457. char *tag, int include_level)
  3458. {
  3459. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  3460. struct file file = STRUCT_FILE_INITIALIZER;
  3461. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  3462. of size MG_BUF_LEN to get the tag. So strlen(tag) is
  3463. always < MG_BUF_LEN. */
  3464. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  3465. /* File name is relative to the webserver root */
  3466. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  3467. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  3468. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  3469. /* File name is relative to the webserver working directory
  3470. or it is absolute system path */
  3471. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  3472. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  3473. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  3474. /* File name is relative to the currect document */
  3475. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3476. if ((p = strrchr(path, '/')) != NULL) {
  3477. p[1] = '\0';
  3478. }
  3479. (void) mg_snprintf(conn, path + strlen(path),
  3480. sizeof(path) - strlen(path), "%s", file_name);
  3481. } else {
  3482. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  3483. return;
  3484. }
  3485. if (!mg_fopen(conn, path, "rb", &file)) {
  3486. mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3487. tag, path, strerror(ERRNO));
  3488. } else {
  3489. fclose_on_exec(&file, conn);
  3490. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3491. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3492. send_ssi_file(conn, path, &file, include_level + 1);
  3493. } else {
  3494. send_file_data(conn, &file, 0, INT64_MAX);
  3495. }
  3496. mg_fclose(&file);
  3497. }
  3498. }
  3499. #if !defined(NO_POPEN)
  3500. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  3501. {
  3502. char cmd[MG_BUF_LEN] = "";
  3503. struct file file = STRUCT_FILE_INITIALIZER;
  3504. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3505. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  3506. } else if ((file.fp = popen(cmd, "r")) == NULL) {
  3507. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3508. } else {
  3509. send_file_data(conn, &file, 0, INT64_MAX);
  3510. pclose(file.fp);
  3511. }
  3512. }
  3513. #endif /* !NO_POPEN */
  3514. static int mg_fgetc(struct file *filep, int offset)
  3515. {
  3516. if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
  3517. return ((unsigned char *) filep->membuf)[offset];
  3518. } else if (filep->fp != NULL) {
  3519. return fgetc(filep->fp);
  3520. } else {
  3521. return EOF;
  3522. }
  3523. }
  3524. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3525. struct file *filep, int include_level)
  3526. {
  3527. char buf[MG_BUF_LEN];
  3528. int ch, offset, len, in_ssi_tag;
  3529. if (include_level > 10) {
  3530. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  3531. return;
  3532. }
  3533. in_ssi_tag = len = offset = 0;
  3534. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  3535. if (in_ssi_tag && ch == '>') {
  3536. in_ssi_tag = 0;
  3537. buf[len++] = (char) ch;
  3538. buf[len] = '\0';
  3539. assert(len <= (int) sizeof(buf));
  3540. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3541. /* Not an SSI tag, pass it */
  3542. (void) mg_write(conn, buf, (size_t) len);
  3543. } else {
  3544. if (!memcmp(buf + 5, "include", 7)) {
  3545. do_ssi_include(conn, path, buf + 12, include_level);
  3546. #if !defined(NO_POPEN)
  3547. } else if (!memcmp(buf + 5, "exec", 4)) {
  3548. do_ssi_exec(conn, buf + 9);
  3549. #endif /* !NO_POPEN */
  3550. } else {
  3551. mg_cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3552. }
  3553. }
  3554. len = 0;
  3555. } else if (in_ssi_tag) {
  3556. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3557. /* Not an SSI tag */
  3558. in_ssi_tag = 0;
  3559. } else if (len == (int) sizeof(buf) - 2) {
  3560. mg_cry(conn, "%s: SSI tag is too large", path);
  3561. len = 0;
  3562. }
  3563. buf[len++] = ch & 0xff;
  3564. } else if (ch == '<') {
  3565. in_ssi_tag = 1;
  3566. if (len > 0) {
  3567. mg_write(conn, buf, (size_t) len);
  3568. }
  3569. len = 0;
  3570. buf[len++] = ch & 0xff;
  3571. } else {
  3572. buf[len++] = ch & 0xff;
  3573. if (len == (int) sizeof(buf)) {
  3574. mg_write(conn, buf, (size_t) len);
  3575. len = 0;
  3576. }
  3577. }
  3578. }
  3579. /* Send the rest of buffered data */
  3580. if (len > 0) {
  3581. mg_write(conn, buf, (size_t) len);
  3582. }
  3583. }
  3584. static void handle_ssi_file_request(struct mg_connection *conn,
  3585. const char *path)
  3586. {
  3587. struct file file = STRUCT_FILE_INITIALIZER;
  3588. if (!mg_fopen(conn, path, "rb", &file)) {
  3589. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  3590. strerror(ERRNO));
  3591. } else {
  3592. conn->must_close = 1;
  3593. fclose_on_exec(&file, conn);
  3594. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3595. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  3596. suggest_connection_header(conn));
  3597. send_ssi_file(conn, path, &file, 0);
  3598. mg_fclose(&file);
  3599. }
  3600. }
  3601. static void send_options(struct mg_connection *conn)
  3602. {
  3603. conn->status_code = 200;
  3604. mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  3605. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
  3606. "DAV: 1\r\n\r\n");
  3607. }
  3608. /* Writes PROPFIND properties for a collection element */
  3609. static void print_props(struct mg_connection *conn, const char* uri,
  3610. struct file *filep)
  3611. {
  3612. char mtime[64];
  3613. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  3614. conn->num_bytes_sent += mg_printf(conn,
  3615. "<d:response>"
  3616. "<d:href>%s</d:href>"
  3617. "<d:propstat>"
  3618. "<d:prop>"
  3619. "<d:resourcetype>%s</d:resourcetype>"
  3620. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3621. "<d:getlastmodified>%s</d:getlastmodified>"
  3622. "</d:prop>"
  3623. "<d:status>HTTP/1.1 200 OK</d:status>"
  3624. "</d:propstat>"
  3625. "</d:response>\n",
  3626. uri,
  3627. filep->is_directory ? "<d:collection/>" : "",
  3628. filep->size,
  3629. mtime);
  3630. }
  3631. static void print_dav_dir_entry(struct de *de, void *data)
  3632. {
  3633. char href[PATH_MAX];
  3634. char href_encoded[PATH_MAX];
  3635. struct mg_connection *conn = (struct mg_connection *) data;
  3636. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3637. conn->request_info.uri, de->file_name);
  3638. mg_url_encode(href, href_encoded, PATH_MAX-1);
  3639. print_props(conn, href_encoded, &de->file);
  3640. }
  3641. static void handle_propfind(struct mg_connection *conn, const char *path,
  3642. struct file *filep)
  3643. {
  3644. const char *depth = mg_get_header(conn, "Depth");
  3645. conn->must_close = 1;
  3646. conn->status_code = 207;
  3647. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3648. "Connection: close\r\n"
  3649. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3650. conn->num_bytes_sent += mg_printf(conn,
  3651. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3652. "<d:multistatus xmlns:d='DAV:'>\n");
  3653. /* Print properties for the requested resource itself */
  3654. print_props(conn, conn->request_info.uri, filep);
  3655. /* If it is a directory, print directory entries too if Depth is not 0 */
  3656. if (filep->is_directory &&
  3657. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3658. (depth == NULL || strcmp(depth, "0") != 0)) {
  3659. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3660. }
  3661. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3662. }
  3663. void mg_lock(struct mg_connection* conn)
  3664. {
  3665. (void) pthread_mutex_lock(&conn->mutex);
  3666. }
  3667. void mg_unlock(struct mg_connection* conn)
  3668. {
  3669. (void) pthread_mutex_unlock(&conn->mutex);
  3670. }
  3671. #if defined(USE_WEBSOCKET)
  3672. /* START OF SHA-1 code
  3673. Copyright(c) By Steve Reid <steve@edmweb.com> */
  3674. #define SHA1HANDSOFF
  3675. #if defined(__sun)
  3676. #include "solarisfixes.h"
  3677. #endif
  3678. static int is_big_endian(void)
  3679. {
  3680. static const int n = 1;
  3681. return ((char *) &n)[0] == 0;
  3682. }
  3683. union char64long16 {
  3684. unsigned char c[64];
  3685. uint32_t l[16];
  3686. };
  3687. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3688. static uint32_t blk0(union char64long16 *block, int i)
  3689. {
  3690. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  3691. if (!is_big_endian()) {
  3692. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  3693. (rol(block->l[i], 8) & 0x00FF00FF);
  3694. }
  3695. return block->l[i];
  3696. }
  3697. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3698. ^block->l[(i+2)&15]^block->l[i&15],1))
  3699. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  3700. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3701. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3702. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3703. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3704. typedef struct {
  3705. uint32_t state[5];
  3706. uint32_t count[2];
  3707. unsigned char buffer[64];
  3708. } SHA1_CTX;
  3709. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  3710. {
  3711. uint32_t a, b, c, d, e;
  3712. union char64long16 block[1];
  3713. memcpy(block, buffer, 64);
  3714. a = state[0];
  3715. b = state[1];
  3716. c = state[2];
  3717. d = state[3];
  3718. e = state[4];
  3719. R0(a,b,c,d,e, 0);
  3720. R0(e,a,b,c,d, 1);
  3721. R0(d,e,a,b,c, 2);
  3722. R0(c,d,e,a,b, 3);
  3723. R0(b,c,d,e,a, 4);
  3724. R0(a,b,c,d,e, 5);
  3725. R0(e,a,b,c,d, 6);
  3726. R0(d,e,a,b,c, 7);
  3727. R0(c,d,e,a,b, 8);
  3728. R0(b,c,d,e,a, 9);
  3729. R0(a,b,c,d,e,10);
  3730. R0(e,a,b,c,d,11);
  3731. R0(d,e,a,b,c,12);
  3732. R0(c,d,e,a,b,13);
  3733. R0(b,c,d,e,a,14);
  3734. R0(a,b,c,d,e,15);
  3735. R1(e,a,b,c,d,16);
  3736. R1(d,e,a,b,c,17);
  3737. R1(c,d,e,a,b,18);
  3738. R1(b,c,d,e,a,19);
  3739. R2(a,b,c,d,e,20);
  3740. R2(e,a,b,c,d,21);
  3741. R2(d,e,a,b,c,22);
  3742. R2(c,d,e,a,b,23);
  3743. R2(b,c,d,e,a,24);
  3744. R2(a,b,c,d,e,25);
  3745. R2(e,a,b,c,d,26);
  3746. R2(d,e,a,b,c,27);
  3747. R2(c,d,e,a,b,28);
  3748. R2(b,c,d,e,a,29);
  3749. R2(a,b,c,d,e,30);
  3750. R2(e,a,b,c,d,31);
  3751. R2(d,e,a,b,c,32);
  3752. R2(c,d,e,a,b,33);
  3753. R2(b,c,d,e,a,34);
  3754. R2(a,b,c,d,e,35);
  3755. R2(e,a,b,c,d,36);
  3756. R2(d,e,a,b,c,37);
  3757. R2(c,d,e,a,b,38);
  3758. R2(b,c,d,e,a,39);
  3759. R3(a,b,c,d,e,40);
  3760. R3(e,a,b,c,d,41);
  3761. R3(d,e,a,b,c,42);
  3762. R3(c,d,e,a,b,43);
  3763. R3(b,c,d,e,a,44);
  3764. R3(a,b,c,d,e,45);
  3765. R3(e,a,b,c,d,46);
  3766. R3(d,e,a,b,c,47);
  3767. R3(c,d,e,a,b,48);
  3768. R3(b,c,d,e,a,49);
  3769. R3(a,b,c,d,e,50);
  3770. R3(e,a,b,c,d,51);
  3771. R3(d,e,a,b,c,52);
  3772. R3(c,d,e,a,b,53);
  3773. R3(b,c,d,e,a,54);
  3774. R3(a,b,c,d,e,55);
  3775. R3(e,a,b,c,d,56);
  3776. R3(d,e,a,b,c,57);
  3777. R3(c,d,e,a,b,58);
  3778. R3(b,c,d,e,a,59);
  3779. R4(a,b,c,d,e,60);
  3780. R4(e,a,b,c,d,61);
  3781. R4(d,e,a,b,c,62);
  3782. R4(c,d,e,a,b,63);
  3783. R4(b,c,d,e,a,64);
  3784. R4(a,b,c,d,e,65);
  3785. R4(e,a,b,c,d,66);
  3786. R4(d,e,a,b,c,67);
  3787. R4(c,d,e,a,b,68);
  3788. R4(b,c,d,e,a,69);
  3789. R4(a,b,c,d,e,70);
  3790. R4(e,a,b,c,d,71);
  3791. R4(d,e,a,b,c,72);
  3792. R4(c,d,e,a,b,73);
  3793. R4(b,c,d,e,a,74);
  3794. R4(a,b,c,d,e,75);
  3795. R4(e,a,b,c,d,76);
  3796. R4(d,e,a,b,c,77);
  3797. R4(c,d,e,a,b,78);
  3798. R4(b,c,d,e,a,79);
  3799. state[0] += a;
  3800. state[1] += b;
  3801. state[2] += c;
  3802. state[3] += d;
  3803. state[4] += e;
  3804. a = b = c = d = e = 0;
  3805. memset(block, '\0', sizeof(block));
  3806. }
  3807. static void SHA1Init(SHA1_CTX* context)
  3808. {
  3809. context->state[0] = 0x67452301;
  3810. context->state[1] = 0xEFCDAB89;
  3811. context->state[2] = 0x98BADCFE;
  3812. context->state[3] = 0x10325476;
  3813. context->state[4] = 0xC3D2E1F0;
  3814. context->count[0] = context->count[1] = 0;
  3815. }
  3816. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3817. uint32_t len)
  3818. {
  3819. uint32_t i, j;
  3820. j = context->count[0];
  3821. if ((context->count[0] += len << 3) < j)
  3822. context->count[1]++;
  3823. context->count[1] += (len>>29);
  3824. j = (j >> 3) & 63;
  3825. if ((j + len) > 63) {
  3826. memcpy(&context->buffer[j], data, (i = 64-j));
  3827. SHA1Transform(context->state, context->buffer);
  3828. for ( ; i + 63 < len; i += 64) {
  3829. SHA1Transform(context->state, &data[i]);
  3830. }
  3831. j = 0;
  3832. } else i = 0;
  3833. memcpy(&context->buffer[j], &data[i], len - i);
  3834. }
  3835. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
  3836. {
  3837. unsigned i;
  3838. unsigned char finalcount[8], c;
  3839. for (i = 0; i < 8; i++) {
  3840. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3841. >> ((3-(i & 3)) * 8) ) & 255);
  3842. }
  3843. c = 0200;
  3844. SHA1Update(context, &c, 1);
  3845. while ((context->count[0] & 504) != 448) {
  3846. c = 0000;
  3847. SHA1Update(context, &c, 1);
  3848. }
  3849. SHA1Update(context, finalcount, 8);
  3850. for (i = 0; i < 20; i++) {
  3851. digest[i] = (unsigned char)
  3852. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3853. }
  3854. memset(context, '\0', sizeof(*context));
  3855. memset(&finalcount, '\0', sizeof(finalcount));
  3856. }
  3857. /* END OF SHA1 CODE */
  3858. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3859. {
  3860. static const char *b64 =
  3861. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3862. int i, j, a, b, c;
  3863. for (i = j = 0; i < src_len; i += 3) {
  3864. a = src[i];
  3865. b = i + 1 >= src_len ? 0 : src[i + 1];
  3866. c = i + 2 >= src_len ? 0 : src[i + 2];
  3867. dst[j++] = b64[a >> 2];
  3868. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3869. if (i + 1 < src_len) {
  3870. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3871. }
  3872. if (i + 2 < src_len) {
  3873. dst[j++] = b64[c & 63];
  3874. }
  3875. }
  3876. while (j % 4 != 0) {
  3877. dst[j++] = '=';
  3878. }
  3879. dst[j++] = '\0';
  3880. }
  3881. static void send_websocket_handshake(struct mg_connection *conn)
  3882. {
  3883. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3884. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3885. SHA1_CTX sha_ctx;
  3886. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3887. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3888. SHA1Init(&sha_ctx);
  3889. SHA1Update(&sha_ctx, (unsigned char *) buf, (uint32_t)strlen(buf));
  3890. SHA1Final((unsigned char *) sha, &sha_ctx);
  3891. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3892. mg_printf(conn, "%s%s%s",
  3893. "HTTP/1.1 101 Switching Protocols\r\n"
  3894. "Upgrade: websocket\r\n"
  3895. "Connection: Upgrade\r\n"
  3896. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3897. }
  3898. static void read_websocket(struct mg_connection *conn)
  3899. {
  3900. /* Pointer to the beginning of the portion of the incoming websocket
  3901. message queue.
  3902. The original websocket upgrade request is never removed, so the queue
  3903. begins after it. */
  3904. unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
  3905. int n;
  3906. /* body_len is the length of the entire queue in bytes
  3907. len is the length of the current message
  3908. data_len is the length of the current message's data payload
  3909. header_len is the length of the current message's header */
  3910. size_t i, len, mask_len, data_len, header_len, body_len;
  3911. /* "The masking key is a 32-bit value chosen at random by the client."
  3912. http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5 */
  3913. unsigned char mask[4];
  3914. /* data points to the place where the message is stored when passed to the
  3915. websocket_data callback. This is either mem on the stack, or a
  3916. dynamically allocated buffer if it is too large. */
  3917. char mem[4096];
  3918. char *data = mem;
  3919. unsigned char mop; /* mask flag and opcode */
  3920. /* Loop continuously, reading messages from the socket, invoking the
  3921. callback, and waiting repeatedly until an error occurs. */
  3922. assert(conn->content_len == 0);
  3923. for (;;) {
  3924. header_len = 0;
  3925. assert(conn->data_len >= conn->request_len);
  3926. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3927. len = buf[1] & 127;
  3928. mask_len = buf[1] & 128 ? 4 : 0;
  3929. if (len < 126 && body_len >= mask_len) {
  3930. data_len = len;
  3931. header_len = 2 + mask_len;
  3932. } else if (len == 126 && body_len >= 4 + mask_len) {
  3933. header_len = 4 + mask_len;
  3934. data_len = ((((int) buf[2]) << 8) + buf[3]);
  3935. } else if (body_len >= 10 + mask_len) {
  3936. header_len = 10 + mask_len;
  3937. data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
  3938. ntohl(* (uint32_t *) &buf[6]);
  3939. }
  3940. }
  3941. if (header_len > 0) {
  3942. /* Allocate space to hold websocket payload */
  3943. data = mem;
  3944. if (data_len > sizeof(mem)) {
  3945. data = (char *)malloc(data_len);
  3946. if (data == NULL) {
  3947. /* Allocation failed, exit the loop and then close the
  3948. connection */
  3949. mg_cry(conn, "websocket malloc() failed; closing connection");
  3950. break;
  3951. }
  3952. }
  3953. /* Copy the mask before we shift the queue and destroy it */
  3954. if (mask_len > 0) {
  3955. *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
  3956. } else {
  3957. *(uint32_t*)mask = 0;
  3958. }
  3959. /* Read frame payload from the first message in the queue into
  3960. data and advance the queue by moving the memory in place. */
  3961. assert(body_len >= header_len);
  3962. if (data_len + header_len > body_len) {
  3963. mop = buf[0]; /* current mask and opcode */
  3964. /* Overflow case */
  3965. len = body_len - header_len;
  3966. memcpy(data, buf + header_len, len);
  3967. int error = 0;
  3968. while (len < data_len) {
  3969. int n = pull(NULL, conn, data + len, (int)(data_len - len));
  3970. if (n < 0) {
  3971. error = 1;
  3972. break;
  3973. }
  3974. len += n;
  3975. }
  3976. if (error) {
  3977. mg_cry(conn, "Websocket pull failed; closing connection");
  3978. break;
  3979. }
  3980. conn->data_len = conn->request_len;
  3981. } else {
  3982. mop = buf[0]; /* current mask and opcode, overwritten by memmove() */
  3983. /* Length of the message being read at the front of the
  3984. queue */
  3985. len = data_len + header_len;
  3986. /* Copy the data payload into the data pointer for the
  3987. callback */
  3988. memcpy(data, buf + header_len, data_len);
  3989. /* Move the queue forward len bytes */
  3990. memmove(buf, buf + len, body_len - len);
  3991. /* Mark the queue as advanced */
  3992. conn->data_len -= (int)len;
  3993. }
  3994. /* Apply mask if necessary */
  3995. if (mask_len > 0) {
  3996. for (i = 0; i < data_len; ++i) {
  3997. data[i] ^= mask[i & 3];
  3998. }
  3999. }
  4000. /* Exit the loop if callback signalled to exit,
  4001. or "connection close" opcode received. */
  4002. if ((conn->ctx->callbacks.websocket_data != NULL &&
  4003. !conn->ctx->callbacks.websocket_data(conn, mop, data, data_len)) ||
  4004. (buf[0] & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) { /* Opcode == 8, connection close */
  4005. break;
  4006. }
  4007. if (data != mem) {
  4008. free(data);
  4009. }
  4010. /* Not breaking the loop, process next websocket frame. */
  4011. } else {
  4012. /* Read from the socket into the next available location in the
  4013. message queue. */
  4014. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  4015. conn->buf_size - conn->data_len)) <= 0) {
  4016. /* Error, no bytes read */
  4017. break;
  4018. }
  4019. conn->data_len += n;
  4020. }
  4021. }
  4022. }
  4023. int mg_websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen)
  4024. {
  4025. unsigned char header[10];
  4026. size_t headerLen = 1;
  4027. int retval = -1;
  4028. header[0] = 0x80 + (opcode & 0xF);
  4029. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  4030. if (dataLen < 126) {
  4031. /* inline 7-bit length field */
  4032. header[1] = (unsigned char)dataLen;
  4033. headerLen = 2;
  4034. } else if (dataLen <= 0xFFFF) {
  4035. /* 16-bit length field */
  4036. header[1] = 126;
  4037. *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
  4038. headerLen = 4;
  4039. } else {
  4040. /* 64-bit length field */
  4041. header[1] = 127;
  4042. *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
  4043. *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  4044. headerLen = 10;
  4045. }
  4046. /* Note that POSIX/Winsock's send() is threadsafe
  4047. http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  4048. but mongoose's mg_printf/mg_write is not (because of the loop in
  4049. push(), although that is only a problem if the packet is large or
  4050. outgoing buffer is full). */
  4051. (void) mg_lock(conn);
  4052. retval = mg_write(conn, header, headerLen);
  4053. retval = mg_write(conn, data, dataLen);
  4054. mg_unlock(conn);
  4055. return retval;
  4056. }
  4057. static void handle_websocket_request(struct mg_connection *conn)
  4058. {
  4059. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  4060. if (version == NULL || strcmp(version, "13") != 0) {
  4061. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  4062. } else if (conn->ctx->callbacks.websocket_connect != NULL &&
  4063. conn->ctx->callbacks.websocket_connect(conn) != 0) {
  4064. /* Callback has returned non-zero, do not proceed with handshake */
  4065. } else {
  4066. send_websocket_handshake(conn);
  4067. if (conn->ctx->callbacks.websocket_ready != NULL) {
  4068. conn->ctx->callbacks.websocket_ready(conn);
  4069. }
  4070. read_websocket(conn);
  4071. }
  4072. }
  4073. static int is_websocket_request(const struct mg_connection *conn)
  4074. {
  4075. const char *host, *upgrade, *connection, *version, *key;
  4076. host = mg_get_header(conn, "Host");
  4077. upgrade = mg_get_header(conn, "Upgrade");
  4078. connection = mg_get_header(conn, "Connection");
  4079. key = mg_get_header(conn, "Sec-WebSocket-Key");
  4080. version = mg_get_header(conn, "Sec-WebSocket-Version");
  4081. return host != NULL && upgrade != NULL && connection != NULL &&
  4082. key != NULL && version != NULL &&
  4083. mg_strcasestr(upgrade, "websocket") != NULL &&
  4084. mg_strcasestr(connection, "Upgrade") != NULL;
  4085. }
  4086. #endif /* !USE_WEBSOCKET */
  4087. static int isbyte(int n)
  4088. {
  4089. return n >= 0 && n <= 255;
  4090. }
  4091. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  4092. {
  4093. int n, a, b, c, d, slash = 32, len = 0;
  4094. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  4095. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  4096. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  4097. slash >= 0 && slash < 33) {
  4098. len = n;
  4099. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  4100. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  4101. }
  4102. return len;
  4103. }
  4104. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  4105. {
  4106. int throttle = 0;
  4107. struct vec vec, val;
  4108. uint32_t net, mask;
  4109. char mult;
  4110. double v;
  4111. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  4112. mult = ',';
  4113. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  4114. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  4115. continue;
  4116. }
  4117. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  4118. if (vec.len == 1 && vec.ptr[0] == '*') {
  4119. throttle = (int) v;
  4120. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  4121. if ((remote_ip & mask) == net) {
  4122. throttle = (int) v;
  4123. }
  4124. } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
  4125. throttle = (int) v;
  4126. }
  4127. }
  4128. return throttle;
  4129. }
  4130. static uint32_t get_remote_ip(const struct mg_connection *conn)
  4131. {
  4132. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  4133. }
  4134. #ifdef USE_LUA
  4135. #include "mod_lua.inl"
  4136. #endif /* USE_LUA */
  4137. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  4138. {
  4139. const char *content_type_header, *boundary_start;
  4140. char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
  4141. FILE *fp;
  4142. int bl, n, i, j, headers_len, boundary_len, eof,
  4143. len = 0, num_uploaded_files = 0;
  4144. /* Request looks like this:
  4145. POST /upload HTTP/1.1
  4146. Host: 127.0.0.1:8080
  4147. Content-Length: 244894
  4148. Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  4149. ------WebKitFormBoundaryRVr
  4150. Content-Disposition: form-data; name="file"; filename="accum.png"
  4151. Content-Type: image/png
  4152. <89>PNG
  4153. <PNG DATA>
  4154. ------WebKitFormBoundaryRVr */
  4155. /* Extract boundary string from the Content-Type header */
  4156. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  4157. (boundary_start = mg_strcasestr(content_type_header,
  4158. "boundary=")) == NULL ||
  4159. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  4160. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  4161. boundary[0] == '\0') {
  4162. return num_uploaded_files;
  4163. }
  4164. boundary_len = (int)strlen(boundary);
  4165. bl = boundary_len + 4; /* \r\n--<boundary> */
  4166. for (;;) {
  4167. /* Pull in headers */
  4168. assert(len >= 0 && len <= (int) sizeof(buf));
  4169. while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
  4170. len += n;
  4171. }
  4172. if ((headers_len = get_request_len(buf, len)) <= 0) {
  4173. break;
  4174. }
  4175. /* Fetch file name. */
  4176. fname[0] = '\0';
  4177. for (i = j = 0; i < headers_len; i++) {
  4178. if (buf[i] == '\r' && buf[i + 1] == '\n') {
  4179. buf[i] = buf[i + 1] = '\0';
  4180. /* TODO(lsm): don't expect filename to be the 3rd field,
  4181. parse the header properly instead. */
  4182. IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
  4183. fname));
  4184. j = i + 2;
  4185. }
  4186. }
  4187. /* Give up if the headers are not what we expect */
  4188. if (fname[0] == '\0') {
  4189. break;
  4190. }
  4191. /* Move data to the beginning of the buffer */
  4192. assert(len >= headers_len);
  4193. memmove(buf, &buf[headers_len], len - headers_len);
  4194. len -= headers_len;
  4195. /* We open the file with exclusive lock held. This guarantee us
  4196. there is no other thread can save into the same file
  4197. simultaneously. */
  4198. fp = NULL;
  4199. /* Construct destination file name. Do not allow paths to have
  4200. slashes. */
  4201. if ((s = strrchr(fname, '/')) == NULL &&
  4202. (s = strrchr(fname, '\\')) == NULL) {
  4203. s = fname;
  4204. }
  4205. /* Open file in binary mode. TODO: set an exclusive lock. */
  4206. snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
  4207. if ((fp = fopen(path, "wb")) == NULL) {
  4208. break;
  4209. }
  4210. /* Read POST data, write into file until boundary is found. */
  4211. eof = n = 0;
  4212. do {
  4213. len += n;
  4214. for (i = 0; i < len - bl; i++) {
  4215. if (!memcmp(&buf[i], "\r\n--", 4) &&
  4216. !memcmp(&buf[i + 4], boundary, boundary_len)) {
  4217. /* Found boundary, that's the end of file data. */
  4218. fwrite(buf, 1, i, fp);
  4219. eof = 1;
  4220. memmove(buf, &buf[i + bl], len - (i + bl));
  4221. len -= i + bl;
  4222. break;
  4223. }
  4224. }
  4225. if (!eof && len > bl) {
  4226. fwrite(buf, 1, len - bl, fp);
  4227. memmove(buf, &buf[len - bl], bl);
  4228. len = bl;
  4229. }
  4230. } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
  4231. fclose(fp);
  4232. if (eof) {
  4233. num_uploaded_files++;
  4234. if (conn->ctx->callbacks.upload != NULL) {
  4235. conn->ctx->callbacks.upload(conn, path);
  4236. }
  4237. }
  4238. }
  4239. return num_uploaded_files;
  4240. }
  4241. static int is_put_or_delete_request(const struct mg_connection *conn)
  4242. {
  4243. const char *s = conn->request_info.request_method;
  4244. return s != NULL && (!strcmp(s, "PUT") ||
  4245. !strcmp(s, "DELETE") ||
  4246. !strcmp(s, "MKCOL"));
  4247. }
  4248. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  4249. {
  4250. int i, idx = -1;
  4251. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  4252. idx = ctx->listening_sockets[i].is_ssl ? i : -1;
  4253. }
  4254. return idx;
  4255. }
  4256. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  4257. {
  4258. char host[1025];
  4259. const char *host_header;
  4260. size_t hostlen;
  4261. host_header = mg_get_header(conn, "Host");
  4262. hostlen = sizeof(host);
  4263. if (host_header != NULL) {
  4264. char *pos;
  4265. strncpy(host, host_header, hostlen);
  4266. host[hostlen - 1] = '\0';
  4267. pos = strchr(host, ':');
  4268. if (pos != NULL) {
  4269. *pos = '\0';
  4270. }
  4271. } else {
  4272. /* Cannot get host from the Host: header.
  4273. Fallback to our IP address. */
  4274. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  4275. }
  4276. mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
  4277. host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
  4278. lsa.sin.sin_port), conn->request_info.uri);
  4279. }
  4280. void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
  4281. {
  4282. struct mg_request_handler_info *tmp_rh, *lastref = 0;
  4283. size_t urilen = strlen(uri);
  4284. /* first see it the uri exists */
  4285. for (tmp_rh = ctx->request_handlers;
  4286. tmp_rh != NULL && strcmp(uri, tmp_rh->uri);
  4287. lastref = tmp_rh, tmp_rh = tmp_rh->next) {
  4288. /* first try for an exact match */
  4289. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4290. /* already there... */
  4291. if (handler != NULL) {
  4292. /* change this entry */
  4293. tmp_rh->handler = handler;
  4294. tmp_rh->cbdata = cbdata;
  4295. } else {
  4296. /* remove this entry */
  4297. if (lastref != NULL)
  4298. lastref->next = tmp_rh->next;
  4299. else
  4300. ctx->request_handlers = tmp_rh->next;
  4301. free(tmp_rh->uri);
  4302. free(tmp_rh);
  4303. }
  4304. return;
  4305. }
  4306. /* next try for a partial match, we will accept uri/something */
  4307. if (tmp_rh->uri_len < urilen
  4308. && uri[tmp_rh->uri_len] == '/'
  4309. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4310. /* if there is a partical match this new entry MUST go BEFORE
  4311. the current position otherwise it will never be matched. */
  4312. break;
  4313. }
  4314. }
  4315. if (handler == NULL) {
  4316. /* no handler to set, this was a remove request */
  4317. return;
  4318. }
  4319. tmp_rh = (struct mg_request_handler_info *)malloc(sizeof(struct mg_request_handler_info));
  4320. if (tmp_rh == NULL) {
  4321. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  4322. return;
  4323. }
  4324. tmp_rh->uri = mg_strdup(uri);
  4325. tmp_rh->uri_len = strlen(uri);
  4326. tmp_rh->handler = handler;
  4327. tmp_rh->cbdata = cbdata;
  4328. if (lastref == NULL) {
  4329. tmp_rh->next = ctx->request_handlers;
  4330. ctx->request_handlers = tmp_rh;
  4331. } else {
  4332. tmp_rh->next = lastref->next;
  4333. lastref->next = tmp_rh;
  4334. }
  4335. }
  4336. static int use_request_handler(struct mg_connection *conn)
  4337. {
  4338. struct mg_request_info *request_info = mg_get_request_info(conn);
  4339. const char *uri = request_info->uri;
  4340. size_t urilen = strlen(uri);
  4341. struct mg_request_handler_info *tmp_rh = conn->ctx->request_handlers;
  4342. for (; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  4343. /* first try for an exact match */
  4344. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4345. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4346. }
  4347. /* next try for a partial match */
  4348. /* we will accept uri/something */
  4349. if (tmp_rh->uri_len < urilen
  4350. && uri[tmp_rh->uri_len] == '/'
  4351. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4352. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4353. }
  4354. }
  4355. return 0; /* none found */
  4356. }
  4357. /* This is the heart of the Civetweb's logic.
  4358. This function is called when the request is read, parsed and validated,
  4359. and Civetweb must decide what action to take: serve a file, or
  4360. a directory, or call embedded function, etcetera. */
  4361. static void handle_request(struct mg_connection *conn)
  4362. {
  4363. struct mg_request_info *ri = &conn->request_info;
  4364. char path[PATH_MAX];
  4365. int uri_len, ssl_index;
  4366. struct file file = STRUCT_FILE_INITIALIZER;
  4367. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  4368. * ((char *) conn->request_info.query_string++) = '\0';
  4369. }
  4370. uri_len = (int) strlen(ri->uri);
  4371. mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
  4372. remove_double_dots_and_double_slashes((char *) ri->uri);
  4373. path[0] = '\0';
  4374. convert_uri_to_file_name(conn, path, sizeof(path), &file);
  4375. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  4376. get_remote_ip(conn), ri->uri);
  4377. DEBUG_TRACE(("%s", ri->uri));
  4378. /* Perform redirect and auth checks before calling begin_request() handler.
  4379. Otherwise, begin_request() would need to perform auth checks and
  4380. redirects. */
  4381. if (!conn->client.is_ssl && conn->client.ssl_redir &&
  4382. (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
  4383. redirect_to_https_port(conn, ssl_index);
  4384. } else if (!is_put_or_delete_request(conn) &&
  4385. !check_authorization(conn, path)) {
  4386. send_authorization_request(conn);
  4387. } else if (conn->ctx->callbacks.begin_request != NULL &&
  4388. conn->ctx->callbacks.begin_request(conn)) {
  4389. /* Do nothing, callback has served the request */
  4390. } else if (conn->ctx->request_handlers != NULL &&
  4391. use_request_handler(conn)) {
  4392. /* Do nothing, callback has served the request */
  4393. #if defined(USE_WEBSOCKET)
  4394. } else if (is_websocket_request(conn)) {
  4395. handle_websocket_request(conn);
  4396. #endif
  4397. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  4398. send_options(conn);
  4399. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  4400. send_http_error(conn, 404, "Not Found", "Not Found");
  4401. } else if (is_put_or_delete_request(conn) &&
  4402. (is_authorized_for_put(conn) != 1)) {
  4403. send_authorization_request(conn);
  4404. } else if (!strcmp(ri->request_method, "PUT")) {
  4405. put_file(conn, path);
  4406. } else if (!strcmp(ri->request_method, "MKCOL")) {
  4407. mkcol(conn, path);
  4408. } else if (!strcmp(ri->request_method, "DELETE")) {
  4409. struct de de;
  4410. memset(&de.file, 0, sizeof(de.file));
  4411. if(!mg_stat(conn, path, &de.file)) {
  4412. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4413. } else {
  4414. if(de.file.modification_time) {
  4415. if(de.file.is_directory) {
  4416. remove_directory(conn, path);
  4417. send_http_error(conn, 204, "No Content", "%s", "");
  4418. } else if (mg_remove(path) == 0) {
  4419. send_http_error(conn, 204, "No Content", "%s", "");
  4420. } else {
  4421. send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
  4422. strerror(ERRNO));
  4423. }
  4424. } else {
  4425. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  4426. strerror(ERRNO));
  4427. }
  4428. }
  4429. } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
  4430. must_hide_file(conn, path)) {
  4431. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4432. } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  4433. mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  4434. "Location: %s/\r\n\r\n", ri->uri);
  4435. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  4436. handle_propfind(conn, path, &file);
  4437. } else if (file.is_directory &&
  4438. !substitute_index_file(conn, path, sizeof(path), &file)) {
  4439. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  4440. handle_directory_request(conn, path);
  4441. } else {
  4442. send_http_error(conn, 403, "Directory Listing Denied",
  4443. "Directory listing denied");
  4444. }
  4445. #ifdef USE_LUA
  4446. } else if (match_prefix("**.lp$", 6, path) > 0) {
  4447. handle_lsp_request(conn, path, &file, NULL);
  4448. #endif
  4449. #if !defined(NO_CGI)
  4450. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4451. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4452. path) > 0) {
  4453. if (strcmp(ri->request_method, "POST") &&
  4454. strcmp(ri->request_method, "HEAD") &&
  4455. strcmp(ri->request_method, "GET")) {
  4456. send_http_error(conn, 501, "Not Implemented",
  4457. "Method %s is not implemented", ri->request_method);
  4458. } else {
  4459. handle_cgi_request(conn, path);
  4460. }
  4461. #endif /* !NO_CGI */
  4462. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  4463. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  4464. path) > 0) {
  4465. handle_ssi_file_request(conn, path);
  4466. } else if (is_not_modified(conn, &file)) {
  4467. send_http_error(conn, 304, "Not Modified", "%s", "");
  4468. } else {
  4469. handle_file_request(conn, path, &file);
  4470. }
  4471. }
  4472. static void close_all_listening_sockets(struct mg_context *ctx)
  4473. {
  4474. int i;
  4475. for (i = 0; i < ctx->num_listening_sockets; i++) {
  4476. closesocket(ctx->listening_sockets[i].sock);
  4477. }
  4478. free(ctx->listening_sockets);
  4479. }
  4480. static int is_valid_port(unsigned int port)
  4481. {
  4482. return port < 0xffff;
  4483. }
  4484. /* Valid listening port specification is: [ip_address:]port[s]
  4485. Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  4486. TODO(lsm): add parsing of the IPv6 address */
  4487. static int parse_port_string(const struct vec *vec, struct socket *so)
  4488. {
  4489. unsigned int a, b, c, d, ch, len, port;
  4490. #if defined(USE_IPV6)
  4491. char buf[100];
  4492. #endif
  4493. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  4494. Also, all-zeroes in the socket address means binding to all addresses
  4495. for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  4496. memset(so, 0, sizeof(*so));
  4497. so->lsa.sin.sin_family = AF_INET;
  4498. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  4499. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  4500. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  4501. so->lsa.sin.sin_port = htons((uint16_t) port);
  4502. #if defined(USE_IPV6)
  4503. } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
  4504. inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
  4505. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  4506. so->lsa.sin6.sin6_family = AF_INET6;
  4507. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  4508. #endif
  4509. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  4510. /* If only port is specified, bind to IPv4, INADDR_ANY */
  4511. so->lsa.sin.sin_port = htons((uint16_t) port);
  4512. } else {
  4513. port = len = 0; /* Parsing failure. Make port invalid. */
  4514. }
  4515. ch = vec->ptr[len]; /* Next character after the port number */
  4516. so->is_ssl = ch == 's';
  4517. so->ssl_redir = ch == 'r';
  4518. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  4519. return is_valid_port(port) &&
  4520. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  4521. }
  4522. static int set_ports_option(struct mg_context *ctx)
  4523. {
  4524. const char *list = ctx->config[LISTENING_PORTS];
  4525. int on = 1, success = 1;
  4526. #if defined(USE_IPV6)
  4527. int off = 0;
  4528. #endif
  4529. struct vec vec;
  4530. struct socket so, *ptr;
  4531. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  4532. if (!parse_port_string(&vec, &so)) {
  4533. mg_cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  4534. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|r]");
  4535. success = 0;
  4536. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  4537. mg_cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  4538. success = 0;
  4539. } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  4540. INVALID_SOCKET ||
  4541. /* On Windows, SO_REUSEADDR is recommended only for
  4542. broadcast UDP sockets */
  4543. setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
  4544. (void *) &on, sizeof(on)) != 0 ||
  4545. #if defined(USE_IPV6)
  4546. (so.lsa.sa.sa_family == AF_INET6 &&
  4547. setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
  4548. sizeof(off)) != 0) ||
  4549. #endif
  4550. bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
  4551. sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 ||
  4552. listen(so.sock, SOMAXCONN) != 0) {
  4553. mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
  4554. (int) vec.len, vec.ptr, ERRNO, strerror(errno));
  4555. if (so.sock != INVALID_SOCKET) {
  4556. closesocket(so.sock);
  4557. }
  4558. success = 0;
  4559. } else if ((ptr = (struct socket *) realloc(ctx->listening_sockets,
  4560. (ctx->num_listening_sockets + 1) *
  4561. sizeof(ctx->listening_sockets[0]))) == NULL) {
  4562. closesocket(so.sock);
  4563. success = 0;
  4564. } else {
  4565. set_close_on_exec(so.sock, fc(ctx));
  4566. ctx->listening_sockets = ptr;
  4567. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  4568. ctx->num_listening_sockets++;
  4569. }
  4570. }
  4571. if (!success) {
  4572. close_all_listening_sockets(ctx);
  4573. }
  4574. return success;
  4575. }
  4576. static void log_header(const struct mg_connection *conn, const char *header,
  4577. FILE *fp)
  4578. {
  4579. const char *header_value;
  4580. if ((header_value = mg_get_header(conn, header)) == NULL) {
  4581. (void) fprintf(fp, "%s", " -");
  4582. } else {
  4583. (void) fprintf(fp, " \"%s\"", header_value);
  4584. }
  4585. }
  4586. static void log_access(const struct mg_connection *conn)
  4587. {
  4588. const struct mg_request_info *ri;
  4589. FILE *fp;
  4590. char date[64], src_addr[IP_ADDR_STR_LEN];
  4591. struct tm *tm;
  4592. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  4593. fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  4594. if (fp == NULL)
  4595. return;
  4596. tm = localtime(&conn->birth_time);
  4597. if (tm != NULL) {
  4598. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  4599. } else {
  4600. strncpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  4601. date[sizeof(date) - 1] = '\0';
  4602. }
  4603. ri = &conn->request_info;
  4604. flockfile(fp);
  4605. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  4606. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  4607. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  4608. ri->request_method ? ri->request_method : "-",
  4609. ri->uri ? ri->uri : "-", ri->http_version,
  4610. conn->status_code, conn->num_bytes_sent);
  4611. log_header(conn, "Referer", fp);
  4612. log_header(conn, "User-Agent", fp);
  4613. fputc('\n', fp);
  4614. fflush(fp);
  4615. funlockfile(fp);
  4616. fclose(fp);
  4617. }
  4618. /* Verify given socket address against the ACL.
  4619. Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  4620. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  4621. {
  4622. int allowed, flag;
  4623. uint32_t net, mask;
  4624. struct vec vec;
  4625. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  4626. /* If any ACL is set, deny by default */
  4627. allowed = list == NULL ? '+' : '-';
  4628. while ((list = next_option(list, &vec, NULL)) != NULL) {
  4629. flag = vec.ptr[0];
  4630. if ((flag != '+' && flag != '-') ||
  4631. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  4632. mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  4633. return -1;
  4634. }
  4635. if (net == (remote_ip & mask)) {
  4636. allowed = flag;
  4637. }
  4638. }
  4639. return allowed == '+';
  4640. }
  4641. #if !defined(_WIN32)
  4642. static int set_uid_option(struct mg_context *ctx)
  4643. {
  4644. struct passwd *pw;
  4645. const char *uid = ctx->config[RUN_AS_USER];
  4646. int success = 0;
  4647. if (uid == NULL) {
  4648. success = 1;
  4649. } else {
  4650. if ((pw = getpwnam(uid)) == NULL) {
  4651. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  4652. } else if (setgid(pw->pw_gid) == -1) {
  4653. mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  4654. } else if (setuid(pw->pw_uid) == -1) {
  4655. mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  4656. } else {
  4657. success = 1;
  4658. }
  4659. }
  4660. return success;
  4661. }
  4662. #endif /* !_WIN32 */
  4663. #if !defined(NO_SSL)
  4664. static pthread_mutex_t *ssl_mutexes;
  4665. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  4666. {
  4667. return (conn->ssl = SSL_new(s)) != NULL &&
  4668. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  4669. func(conn->ssl) == 1;
  4670. }
  4671. /* Return OpenSSL error message */
  4672. static const char *ssl_error(void)
  4673. {
  4674. unsigned long err;
  4675. err = ERR_get_error();
  4676. return err == 0 ? "" : ERR_error_string(err, NULL);
  4677. }
  4678. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  4679. int line)
  4680. {
  4681. (void) line;
  4682. (void) file;
  4683. if (mode & 1) { /* 1 is CRYPTO_LOCK */
  4684. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  4685. } else {
  4686. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  4687. }
  4688. }
  4689. static unsigned long ssl_id_callback(void)
  4690. {
  4691. return (unsigned long) pthread_self();
  4692. }
  4693. #if !defined(NO_SSL_DL)
  4694. static void *load_dll(struct mg_context *ctx, const char *dll_name,
  4695. struct ssl_func *sw)
  4696. {
  4697. union {
  4698. void *p;
  4699. void (*fp)(void);
  4700. } u;
  4701. void *dll_handle;
  4702. struct ssl_func *fp;
  4703. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  4704. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  4705. return NULL;
  4706. }
  4707. for (fp = sw; fp->name != NULL; fp++) {
  4708. #ifdef _WIN32
  4709. /* GetProcAddress() returns pointer to function */
  4710. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  4711. #else
  4712. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  4713. pointers to function pointers. We need to use a union to make a
  4714. cast. */
  4715. u.p = dlsym(dll_handle, fp->name);
  4716. #endif /* _WIN32 */
  4717. if (u.fp == NULL) {
  4718. mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  4719. dlclose(dll_handle);
  4720. return NULL;
  4721. } else {
  4722. fp->ptr = u.fp;
  4723. }
  4724. }
  4725. return dll_handle;
  4726. }
  4727. #endif /* NO_SSL_DL */
  4728. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  4729. static int set_ssl_option(struct mg_context *ctx)
  4730. {
  4731. int i, size;
  4732. const char *pem;
  4733. /* If PEM file is not specified and the init_ssl callback
  4734. is not specified, skip SSL initialization. */
  4735. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  4736. ctx->callbacks.init_ssl == NULL) {
  4737. return 1;
  4738. }
  4739. #if !defined(NO_SSL_DL)
  4740. ctx->ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  4741. ctx->cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  4742. if (!ctx->ssllib_dll_handle || !ctx->cryptolib_dll_handle) {
  4743. return 0;
  4744. }
  4745. #endif /* NO_SSL_DL */
  4746. /* Initialize SSL library */
  4747. SSL_library_init();
  4748. SSL_load_error_strings();
  4749. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  4750. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  4751. return 0;
  4752. }
  4753. /* If user callback returned non-NULL, that means that user callback has
  4754. set up certificate itself. In this case, skip sertificate setting. */
  4755. if ((ctx->callbacks.init_ssl == NULL ||
  4756. !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
  4757. (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
  4758. SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  4759. mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
  4760. return 0;
  4761. }
  4762. if (pem != NULL) {
  4763. (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  4764. }
  4765. /* Initialize locking callbacks, needed for thread safety.
  4766. http://www.openssl.org/support/faq.html#PROG1 */
  4767. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  4768. if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
  4769. mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  4770. return 0;
  4771. }
  4772. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4773. pthread_mutex_init(&ssl_mutexes[i], NULL);
  4774. }
  4775. CRYPTO_set_locking_callback(&ssl_locking_callback);
  4776. CRYPTO_set_id_callback(&ssl_id_callback);
  4777. return 1;
  4778. }
  4779. static void uninitialize_ssl(struct mg_context *ctx)
  4780. {
  4781. int i;
  4782. if (ctx->ssl_ctx != NULL) {
  4783. CRYPTO_set_locking_callback(NULL);
  4784. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4785. pthread_mutex_destroy(&ssl_mutexes[i]);
  4786. }
  4787. CRYPTO_set_locking_callback(NULL);
  4788. CRYPTO_set_id_callback(NULL);
  4789. }
  4790. }
  4791. #endif /* !NO_SSL */
  4792. static int set_gpass_option(struct mg_context *ctx)
  4793. {
  4794. struct file file = STRUCT_FILE_INITIALIZER;
  4795. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  4796. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  4797. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  4798. return 0;
  4799. }
  4800. return 1;
  4801. }
  4802. static int set_acl_option(struct mg_context *ctx)
  4803. {
  4804. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  4805. }
  4806. static void reset_per_request_attributes(struct mg_connection *conn)
  4807. {
  4808. conn->path_info = NULL;
  4809. conn->num_bytes_sent = conn->consumed_content = 0;
  4810. conn->status_code = -1;
  4811. conn->must_close = conn->request_len = conn->throttle = 0;
  4812. }
  4813. static void close_socket_gracefully(struct mg_connection *conn)
  4814. {
  4815. #if defined(_WIN32)
  4816. char buf[MG_BUF_LEN];
  4817. int n;
  4818. #endif
  4819. struct linger linger;
  4820. /* Set linger option to avoid socket hanging out after close. This prevent
  4821. ephemeral port exhaust problem under high QPS. */
  4822. linger.l_onoff = 1;
  4823. linger.l_linger = 1;
  4824. if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
  4825. (char *) &linger, sizeof(linger)) != 0) {
  4826. mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  4827. __func__, strerror(ERRNO));
  4828. }
  4829. /* Send FIN to the client */
  4830. shutdown(conn->client.sock, SHUT_WR);
  4831. set_non_blocking_mode(conn->client.sock);
  4832. #if defined(_WIN32)
  4833. /* Read and discard pending incoming data. If we do not do that and close
  4834. the socket, the data in the send buffer may be discarded. This
  4835. behaviour is seen on Windows, when client keeps sending data
  4836. when server decides to close the connection; then when client
  4837. does recv() it gets no data back. */
  4838. do {
  4839. n = pull(NULL, conn, buf, sizeof(buf));
  4840. } while (n > 0);
  4841. #endif
  4842. /* Now we know that our FIN is ACK-ed, safe to close */
  4843. closesocket(conn->client.sock);
  4844. }
  4845. static void close_connection(struct mg_connection *conn)
  4846. {
  4847. /* call the connection_close callback if assigned */
  4848. if (conn->ctx->callbacks.connection_close != NULL)
  4849. conn->ctx->callbacks.connection_close(conn);
  4850. mg_lock(conn);
  4851. conn->must_close = 1;
  4852. #ifndef NO_SSL
  4853. if (conn->ssl != NULL) {
  4854. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  4855. SSL_shutdown(conn->ssl);
  4856. SSL_free(conn->ssl);
  4857. conn->ssl = NULL;
  4858. }
  4859. #endif
  4860. if (conn->client.sock != INVALID_SOCKET) {
  4861. close_socket_gracefully(conn);
  4862. conn->client.sock = INVALID_SOCKET;
  4863. }
  4864. mg_unlock(conn);
  4865. }
  4866. void mg_close_connection(struct mg_connection *conn)
  4867. {
  4868. #ifndef NO_SSL
  4869. if (conn->client_ssl_ctx != NULL) {
  4870. SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
  4871. }
  4872. #endif
  4873. close_connection(conn);
  4874. (void) pthread_mutex_destroy(&conn->mutex);
  4875. free(conn);
  4876. }
  4877. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  4878. char *ebuf, size_t ebuf_len);
  4879. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  4880. char *ebuf, size_t ebuf_len)
  4881. {
  4882. static struct mg_context fake_ctx;
  4883. struct mg_connection *conn = NULL;
  4884. SOCKET sock;
  4885. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf,
  4886. ebuf_len)) == INVALID_SOCKET) {
  4887. } else if ((conn = (struct mg_connection *)
  4888. calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  4889. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  4890. closesocket(sock);
  4891. #ifndef NO_SSL
  4892. } else if (use_ssl && (conn->client_ssl_ctx =
  4893. SSL_CTX_new(SSLv23_client_method())) == NULL) {
  4894. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  4895. closesocket(sock);
  4896. free(conn);
  4897. conn = NULL;
  4898. #endif /* NO_SSL */
  4899. } else {
  4900. socklen_t len = sizeof(struct sockaddr);
  4901. conn->buf_size = MAX_REQUEST_SIZE;
  4902. conn->buf = (char *) (conn + 1);
  4903. conn->ctx = &fake_ctx;
  4904. conn->client.sock = sock;
  4905. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  4906. mg_cry(conn, "%s: getsockname() failed: %s",
  4907. __func__, strerror(ERRNO));
  4908. }
  4909. conn->client.is_ssl = use_ssl;
  4910. (void) pthread_mutex_init(&conn->mutex, NULL);
  4911. #ifndef NO_SSL
  4912. if (use_ssl) {
  4913. /* SSL_CTX_set_verify call is needed to switch off server
  4914. certificate checking, which is off by default in OpenSSL and on
  4915. in yaSSL. */
  4916. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  4917. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  4918. }
  4919. #endif
  4920. }
  4921. return conn;
  4922. }
  4923. static int is_valid_uri(const char *uri)
  4924. {
  4925. /* Conform to
  4926. http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4927. URI can be an asterisk (*) or should start with slash. */
  4928. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  4929. }
  4930. static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len)
  4931. {
  4932. const char *cl;
  4933. ebuf[0] = '\0';
  4934. reset_per_request_attributes(conn);
  4935. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  4936. &conn->data_len);
  4937. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  4938. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  4939. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  4940. } else if (conn->request_len <= 0) {
  4941. snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
  4942. } else if (parse_http_message(conn->buf, conn->buf_size,
  4943. &conn->request_info) <= 0) {
  4944. snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
  4945. } else {
  4946. /* Request is valid */
  4947. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  4948. conn->content_len = strtoll(cl, NULL, 10);
  4949. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  4950. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  4951. conn->content_len = -1;
  4952. } else {
  4953. conn->content_len = 0;
  4954. }
  4955. conn->birth_time = time(NULL);
  4956. }
  4957. return ebuf[0] == '\0';
  4958. }
  4959. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  4960. char *ebuf, size_t ebuf_len,
  4961. const char *fmt, ...)
  4962. {
  4963. struct mg_connection *conn;
  4964. va_list ap;
  4965. va_start(ap, fmt);
  4966. ebuf[0] = '\0';
  4967. if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
  4968. } else if (mg_vprintf(conn, fmt, ap) <= 0) {
  4969. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  4970. } else {
  4971. getreq(conn, ebuf, ebuf_len);
  4972. }
  4973. if (ebuf[0] != '\0' && conn != NULL) {
  4974. mg_close_connection(conn);
  4975. conn = NULL;
  4976. }
  4977. va_end(ap);
  4978. return conn;
  4979. }
  4980. static void process_new_connection(struct mg_connection *conn)
  4981. {
  4982. struct mg_request_info *ri = &conn->request_info;
  4983. int keep_alive_enabled, keep_alive, discard_len;
  4984. char ebuf[100];
  4985. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  4986. keep_alive = 0;
  4987. /* Important: on new connection, reset the receiving buffer. Credit goes
  4988. to crule42. */
  4989. conn->data_len = 0;
  4990. do {
  4991. if (!getreq(conn, ebuf, sizeof(ebuf))) {
  4992. send_http_error(conn, 500, "Server Error", "%s", ebuf);
  4993. conn->must_close = 1;
  4994. } else if (!is_valid_uri(conn->request_info.uri)) {
  4995. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  4996. send_http_error(conn, 400, "Bad Request", "%s", ebuf);
  4997. } else if (strcmp(ri->http_version, "1.0") &&
  4998. strcmp(ri->http_version, "1.1")) {
  4999. snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
  5000. send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
  5001. }
  5002. if (ebuf[0] == '\0') {
  5003. handle_request(conn);
  5004. if (conn->ctx->callbacks.end_request != NULL) {
  5005. conn->ctx->callbacks.end_request(conn, conn->status_code);
  5006. }
  5007. log_access(conn);
  5008. }
  5009. if (ri->remote_user != NULL) {
  5010. free((void *) ri->remote_user);
  5011. /* Important! When having connections with and without auth
  5012. would cause double free and then crash */
  5013. ri->remote_user = NULL;
  5014. }
  5015. /* NOTE(lsm): order is important here. should_keep_alive() call is
  5016. using parsed request, which will be invalid after memmove's below.
  5017. Therefore, memorize should_keep_alive() result now for later use
  5018. in loop exit condition. */
  5019. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  5020. conn->content_len >= 0 && should_keep_alive(conn);
  5021. /* Discard all buffered data for this request */
  5022. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  5023. conn->request_len + conn->content_len < (int64_t) conn->data_len ?
  5024. (int) (conn->request_len + conn->content_len) : conn->data_len;
  5025. assert(discard_len >= 0);
  5026. memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
  5027. conn->data_len -= discard_len;
  5028. assert(conn->data_len >= 0);
  5029. assert(conn->data_len <= conn->buf_size);
  5030. } while (keep_alive);
  5031. }
  5032. /* Worker threads take accepted socket from the queue */
  5033. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  5034. {
  5035. (void) pthread_mutex_lock(&ctx->mutex);
  5036. DEBUG_TRACE(("going idle"));
  5037. /* If the queue is empty, wait. We're idle at this point. */
  5038. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  5039. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  5040. }
  5041. /* If we're stopping, sq_head may be equal to sq_tail. */
  5042. if (ctx->sq_head > ctx->sq_tail) {
  5043. /* Copy socket from the queue and increment tail */
  5044. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  5045. ctx->sq_tail++;
  5046. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  5047. /* Wrap pointers if needed */
  5048. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  5049. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  5050. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  5051. }
  5052. }
  5053. (void) pthread_cond_signal(&ctx->sq_empty);
  5054. (void) pthread_mutex_unlock(&ctx->mutex);
  5055. return !ctx->stop_flag;
  5056. }
  5057. static void *worker_thread_run(void *thread_func_param)
  5058. {
  5059. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  5060. struct mg_connection *conn;
  5061. struct mg_workerTLS tls;
  5062. tls.is_master = 0;
  5063. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5064. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  5065. #endif
  5066. conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  5067. if (conn == NULL) {
  5068. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  5069. } else {
  5070. pthread_setspecific(sTlsKey, &tls);
  5071. conn->buf_size = MAX_REQUEST_SIZE;
  5072. conn->buf = (char *) (conn + 1);
  5073. conn->ctx = ctx;
  5074. conn->request_info.user_data = ctx->user_data;
  5075. /* Allocate a mutex for this connection to allow communication both
  5076. within the request handler and from elsewhere in the application */
  5077. (void) pthread_mutex_init(&conn->mutex, NULL);
  5078. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  5079. signal sq_empty condvar to wake up the master waiting in
  5080. produce_socket() */
  5081. while (consume_socket(ctx, &conn->client)) {
  5082. conn->birth_time = time(NULL);
  5083. /* Fill in IP, port info early so even if SSL setup below fails,
  5084. error handler would have the corresponding info.
  5085. Thanks to Johannes Winkelmann for the patch.
  5086. TODO(lsm): Fix IPv6 case */
  5087. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  5088. memcpy(&conn->request_info.remote_ip,
  5089. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  5090. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  5091. conn->request_info.is_ssl = conn->client.is_ssl;
  5092. if (!conn->client.is_ssl
  5093. #ifndef NO_SSL
  5094. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  5095. #endif
  5096. ) {
  5097. process_new_connection(conn);
  5098. }
  5099. close_connection(conn);
  5100. }
  5101. }
  5102. /* Signal master that we're done with connection and exiting */
  5103. (void) pthread_mutex_lock(&ctx->mutex);
  5104. ctx->num_threads--;
  5105. (void) pthread_cond_signal(&ctx->cond);
  5106. assert(ctx->num_threads >= 0);
  5107. (void) pthread_mutex_unlock(&ctx->mutex);
  5108. pthread_setspecific(sTlsKey, 0);
  5109. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5110. CloseHandle(tls.pthread_cond_helper_mutex);
  5111. #endif
  5112. free(conn);
  5113. DEBUG_TRACE(("exiting"));
  5114. return NULL;
  5115. }
  5116. /* Threads have different return types on Windows and Unix. */
  5117. #ifdef _WIN32
  5118. static unsigned __stdcall worker_thread(void *thread_func_param)
  5119. {
  5120. worker_thread_run(thread_func_param);
  5121. return 0;
  5122. }
  5123. #else
  5124. static void *worker_thread(void *thread_func_param)
  5125. {
  5126. worker_thread_run(thread_func_param);
  5127. return NULL;
  5128. }
  5129. #endif /* _WIN32 */
  5130. /* Master thread adds accepted socket to a queue */
  5131. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  5132. {
  5133. (void) pthread_mutex_lock(&ctx->mutex);
  5134. /* If the queue is full, wait */
  5135. while (ctx->stop_flag == 0 &&
  5136. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  5137. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  5138. }
  5139. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  5140. /* Copy socket to the queue and increment head */
  5141. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  5142. ctx->sq_head++;
  5143. DEBUG_TRACE(("queued socket %d", sp->sock));
  5144. }
  5145. (void) pthread_cond_signal(&ctx->sq_full);
  5146. (void) pthread_mutex_unlock(&ctx->mutex);
  5147. }
  5148. static int set_sock_timeout(SOCKET sock, int milliseconds)
  5149. {
  5150. #ifdef _WIN32
  5151. DWORD t = milliseconds;
  5152. #else
  5153. struct timeval t;
  5154. t.tv_sec = milliseconds / 1000;
  5155. t.tv_usec = (milliseconds * 1000) % 1000000;
  5156. #endif
  5157. return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
  5158. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
  5159. }
  5160. static void accept_new_connection(const struct socket *listener,
  5161. struct mg_context *ctx)
  5162. {
  5163. struct socket so;
  5164. char src_addr[IP_ADDR_STR_LEN];
  5165. socklen_t len = sizeof(so.rsa);
  5166. int on = 1;
  5167. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
  5168. } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
  5169. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  5170. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  5171. closesocket(so.sock);
  5172. } else {
  5173. /* Put so socket structure into the queue */
  5174. DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
  5175. set_close_on_exec(so.sock, fc(ctx));
  5176. so.is_ssl = listener->is_ssl;
  5177. so.ssl_redir = listener->ssl_redir;
  5178. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  5179. mg_cry(fc(ctx), "%s: getsockname() failed: %s",
  5180. __func__, strerror(ERRNO));
  5181. }
  5182. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  5183. is enabled, and client resets the connection, server won't get
  5184. TCP FIN or RST and will keep the connection open forever. With TCP
  5185. keep-alive, next keep-alive handshake will figure out that the
  5186. client is down and will close the server end.
  5187. Thanks to Igor Klopov who suggested the patch. */
  5188. if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
  5189. sizeof(on)) != 0) {
  5190. mg_cry(fc(ctx),
  5191. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  5192. __func__, strerror(ERRNO));
  5193. }
  5194. set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
  5195. produce_socket(ctx, &so);
  5196. }
  5197. }
  5198. static void master_thread_run(void *thread_func_param)
  5199. {
  5200. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  5201. struct mg_workerTLS tls;
  5202. struct pollfd *pfd;
  5203. int i;
  5204. int workerthreadcount;
  5205. /* Increase priority of the master thread */
  5206. #if defined(_WIN32)
  5207. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  5208. #elif defined(USE_MASTER_THREAD_PRIORITY)
  5209. int min_prio = sched_get_priority_min(SCHED_RR);
  5210. int max_prio = sched_get_priority_max(SCHED_RR);
  5211. if ((min_prio >=0) && (max_prio >= 0) &&
  5212. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  5213. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)
  5214. ) {
  5215. struct sched_param sched_param = {0};
  5216. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  5217. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  5218. }
  5219. #endif
  5220. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5221. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  5222. #endif
  5223. tls.is_master = 1;
  5224. pthread_setspecific(sTlsKey, &tls);
  5225. pfd = (struct pollfd *) calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  5226. while (pfd != NULL && ctx->stop_flag == 0) {
  5227. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5228. pfd[i].fd = ctx->listening_sockets[i].sock;
  5229. pfd[i].events = POLLIN;
  5230. }
  5231. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  5232. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5233. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  5234. successful poll, and POLLIN is defined as
  5235. (POLLRDNORM | POLLRDBAND)
  5236. Therefore, we're checking pfd[i].revents & POLLIN, not
  5237. pfd[i].revents == POLLIN. */
  5238. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  5239. accept_new_connection(&ctx->listening_sockets[i], ctx);
  5240. }
  5241. }
  5242. }
  5243. }
  5244. free(pfd);
  5245. DEBUG_TRACE(("stopping workers"));
  5246. /* Stop signal received: somebody called mg_stop. Quit. */
  5247. close_all_listening_sockets(ctx);
  5248. /* Wakeup workers that are waiting for connections to handle. */
  5249. pthread_cond_broadcast(&ctx->sq_full);
  5250. /* Wait until all threads finish */
  5251. (void) pthread_mutex_lock(&ctx->mutex);
  5252. while (ctx->num_threads > 0) {
  5253. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  5254. }
  5255. (void) pthread_mutex_unlock(&ctx->mutex);
  5256. /* Join all worker threads to avoid leaking threads. */
  5257. workerthreadcount = ctx->workerthreadcount;
  5258. for (i = 0; i < workerthreadcount; i++) {
  5259. mg_join_thread(ctx->workerthreadids[i]);
  5260. }
  5261. /* All threads exited, no sync is needed. Destroy mutex and condvars */
  5262. (void) pthread_mutex_destroy(&ctx->mutex);
  5263. (void) pthread_cond_destroy(&ctx->cond);
  5264. (void) pthread_cond_destroy(&ctx->sq_empty);
  5265. (void) pthread_cond_destroy(&ctx->sq_full);
  5266. #if !defined(NO_SSL)
  5267. uninitialize_ssl(ctx);
  5268. #endif
  5269. DEBUG_TRACE(("exiting"));
  5270. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5271. CloseHandle(tls.pthread_cond_helper_mutex);
  5272. #endif
  5273. pthread_setspecific(sTlsKey, 0);
  5274. /* Signal mg_stop() that we're done.
  5275. WARNING: This must be the very last thing this
  5276. thread does, as ctx becomes invalid after this line. */
  5277. ctx->stop_flag = 2;
  5278. }
  5279. /* Threads have different return types on Windows and Unix. */
  5280. #ifdef _WIN32
  5281. static unsigned __stdcall master_thread(void *thread_func_param)
  5282. {
  5283. master_thread_run(thread_func_param);
  5284. return 0;
  5285. }
  5286. #else
  5287. static void *master_thread(void *thread_func_param)
  5288. {
  5289. master_thread_run(thread_func_param);
  5290. return NULL;
  5291. }
  5292. #endif /* _WIN32 */
  5293. static void free_context(struct mg_context *ctx)
  5294. {
  5295. int i;
  5296. struct mg_request_handler_info *tmp_rh;
  5297. if (ctx == NULL)
  5298. return;
  5299. /* Deallocate config parameters */
  5300. for (i = 0; i < NUM_OPTIONS; i++) {
  5301. if (ctx->config[i] != NULL)
  5302. #ifdef WIN32
  5303. #pragma warning(suppress: 6001)
  5304. #endif
  5305. free(ctx->config[i]);
  5306. }
  5307. /* Deallocate request handlers */
  5308. while (ctx->request_handlers) {
  5309. tmp_rh = ctx->request_handlers;
  5310. ctx->request_handlers = tmp_rh->next;
  5311. free(tmp_rh->uri);
  5312. free(tmp_rh);
  5313. }
  5314. #ifndef NO_SSL
  5315. /* Deallocate SSL context */
  5316. if (ctx->ssl_ctx != NULL) {
  5317. SSL_CTX_free(ctx->ssl_ctx);
  5318. }
  5319. if (ssl_mutexes != NULL) {
  5320. free(ssl_mutexes);
  5321. ssl_mutexes = NULL;
  5322. }
  5323. #endif /* !NO_SSL */
  5324. /* Deallocate worker thread ID array */
  5325. if (ctx->workerthreadids != NULL) {
  5326. free(ctx->workerthreadids);
  5327. }
  5328. /* Deallocate the tls variable */
  5329. sTlsInit--;
  5330. if (sTlsInit==0) {
  5331. pthread_key_delete(sTlsKey);
  5332. }
  5333. /* Deallocate context itself */
  5334. free(ctx);
  5335. }
  5336. void mg_stop(struct mg_context *ctx)
  5337. {
  5338. ctx->stop_flag = 1;
  5339. /* Wait until mg_fini() stops */
  5340. while (ctx->stop_flag != 2) {
  5341. (void) mg_sleep(10);
  5342. }
  5343. mg_join_thread(ctx->masterthreadid);
  5344. free_context(ctx);
  5345. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5346. (void) WSACleanup();
  5347. #endif /* _WIN32 && !__SYMBIAN32__ */
  5348. }
  5349. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  5350. void *user_data,
  5351. const char **options)
  5352. {
  5353. struct mg_context *ctx;
  5354. const char *name, *value, *default_value;
  5355. int i;
  5356. int workerthreadcount;
  5357. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5358. WSADATA data;
  5359. WSAStartup(MAKEWORD(2,2), &data);
  5360. #pragma warning(suppress: 28125)
  5361. InitializeCriticalSection(&global_log_file_lock);
  5362. #endif /* _WIN32 && !__SYMBIAN32__ */
  5363. /* Allocate context and initialize reasonable general case defaults.
  5364. TODO(lsm): do proper error handling here. */
  5365. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  5366. return NULL;
  5367. }
  5368. if (sTlsInit==0) {
  5369. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  5370. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  5371. return NULL;
  5372. }
  5373. sTlsInit++;
  5374. }
  5375. ctx->callbacks = *callbacks;
  5376. ctx->user_data = user_data;
  5377. ctx->request_handlers = 0;
  5378. while (options && (name = *options++) != NULL) {
  5379. if ((i = get_option_index(name)) == -1) {
  5380. mg_cry(fc(ctx), "Invalid option: %s", name);
  5381. free_context(ctx);
  5382. return NULL;
  5383. } else if ((value = *options++) == NULL) {
  5384. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  5385. free_context(ctx);
  5386. return NULL;
  5387. }
  5388. if (ctx->config[i] != NULL) {
  5389. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  5390. free(ctx->config[i]);
  5391. }
  5392. ctx->config[i] = mg_strdup(value);
  5393. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  5394. }
  5395. /* Set default value if needed */
  5396. for (i = 0; config_options[i * 2] != NULL; i++) {
  5397. default_value = config_options[i * 2 + 1];
  5398. if (ctx->config[i] == NULL && default_value != NULL) {
  5399. ctx->config[i] = mg_strdup(default_value);
  5400. }
  5401. }
  5402. /* NOTE(lsm): order is important here. SSL certificates must
  5403. be initialized before listening ports. UID must be set last. */
  5404. if (!set_gpass_option(ctx) ||
  5405. #if !defined(NO_SSL)
  5406. !set_ssl_option(ctx) ||
  5407. #endif
  5408. !set_ports_option(ctx) ||
  5409. #if !defined(_WIN32)
  5410. !set_uid_option(ctx) ||
  5411. #endif
  5412. !set_acl_option(ctx)) {
  5413. free_context(ctx);
  5414. return NULL;
  5415. }
  5416. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  5417. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  5418. won't kill the whole process. */
  5419. (void) signal(SIGPIPE, SIG_IGN);
  5420. #endif /* !_WIN32 && !__SYMBIAN32__ */
  5421. (void) pthread_mutex_init(&ctx->mutex, NULL);
  5422. (void) pthread_cond_init(&ctx->cond, NULL);
  5423. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  5424. (void) pthread_cond_init(&ctx->sq_full, NULL);
  5425. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  5426. if (workerthreadcount > MAX_WORKER_THREADS) {
  5427. mg_cry(fc(ctx), "Too many worker threads");
  5428. free_context(ctx);
  5429. return NULL;
  5430. }
  5431. if (workerthreadcount > 0) {
  5432. ctx->workerthreadcount = workerthreadcount;
  5433. ctx->workerthreadids = calloc(workerthreadcount, sizeof(pthread_t));
  5434. if (ctx->workerthreadids == NULL) {
  5435. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  5436. free_context(ctx);
  5437. return NULL;
  5438. }
  5439. }
  5440. /* Start master (listening) thread */
  5441. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  5442. /* Start worker threads */
  5443. for (i = 0; i < workerthreadcount; i++) {
  5444. (void) pthread_mutex_lock(&ctx->mutex);
  5445. ctx->num_threads++;
  5446. (void) pthread_mutex_unlock(&ctx->mutex);
  5447. if (mg_start_thread_with_id(worker_thread, ctx,
  5448. &ctx->workerthreadids[i]) != 0) {
  5449. (void) pthread_mutex_lock(&ctx->mutex);
  5450. ctx->num_threads--;
  5451. (void) pthread_mutex_unlock(&ctx->mutex);
  5452. mg_cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
  5453. }
  5454. }
  5455. return ctx;
  5456. }