civetweb.c 193 KB

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