civetweb.c 189 KB

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