civetweb.c 287 KB

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