civetweb.c 270 KB

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