civetweb.c 375 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. int _civet_clock_gettime(int clk_id, struct timespec *t);
  135. int
  136. _civet_clock_gettime(int clk_id, struct timespec *t)
  137. {
  138. memset(t, 0, sizeof(*t));
  139. if (clk_id == CLOCK_REALTIME) {
  140. struct timeval now;
  141. int rv = gettimeofday(&now, NULL);
  142. if (rv) {
  143. return rv;
  144. }
  145. t->tv_sec = now.tv_sec;
  146. t->tv_nsec = now.tv_usec * 1000;
  147. return 0;
  148. } else if (clk_id == CLOCK_MONOTONIC) {
  149. static uint64_t clock_start_time = 0;
  150. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  151. uint64_t now = mach_absolute_time();
  152. if (clock_start_time == 0) {
  153. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  154. #if defined(DEBUG)
  155. assert(mach_status == KERN_SUCCESS);
  156. #else
  157. /* appease "unused variable" warning for release builds */
  158. (void)mach_status;
  159. #endif
  160. clock_start_time = now;
  161. }
  162. now = (uint64_t)((double)(now - clock_start_time)
  163. * (double)timebase_ifo.numer
  164. / (double)timebase_ifo.denom);
  165. t->tv_sec = now / 1000000000;
  166. t->tv_nsec = now % 1000000000;
  167. return 0;
  168. }
  169. return -1; /* EINVAL - Clock ID is unknown */
  170. }
  171. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  172. #ifdef __CLOCK_AVAILABILITY
  173. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  174. * declared
  175. * but it may be NULL at runtime. So we need to check before using it. */
  176. int _civet_safe_clock_gettime(int clk_id, struct timespec *t);
  177. int
  178. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  179. {
  180. if (clock_gettime) {
  181. return clock_gettime(clk_id, t);
  182. }
  183. return _civet_clock_gettime(clk_id, t);
  184. }
  185. #define clock_gettime _civet_safe_clock_gettime
  186. #else
  187. #define clock_gettime _civet_clock_gettime
  188. #endif
  189. #endif
  190. #include <time.h>
  191. #include <stdlib.h>
  192. #include <stdarg.h>
  193. #include <assert.h>
  194. #include <string.h>
  195. #include <ctype.h>
  196. #include <limits.h>
  197. #include <stddef.h>
  198. #include <stdio.h>
  199. #include <stdint.h>
  200. #ifndef INT64_MAX
  201. #define INT64_MAX (9223372036854775807)
  202. #endif
  203. #ifndef MAX_WORKER_THREADS
  204. #define MAX_WORKER_THREADS (1024 * 64)
  205. #endif
  206. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  207. #define SOCKET_TIMEOUT_QUANTUM (2000)
  208. #endif
  209. #define SHUTDOWN_RD (0)
  210. #define SHUTDOWN_WR (1)
  211. #define SHUTDOWN_BOTH (2)
  212. mg_static_assert(MAX_WORKER_THREADS >= 1,
  213. "worker threads must be a positive number");
  214. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  215. "size_t data type size check");
  216. #if defined(_WIN32) \
  217. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  218. #include <windows.h>
  219. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  220. #include <ws2tcpip.h>
  221. typedef const char *SOCK_OPT_TYPE;
  222. #if !defined(PATH_MAX)
  223. #define PATH_MAX (MAX_PATH)
  224. #endif
  225. #if !defined(PATH_MAX)
  226. #define PATH_MAX (4096)
  227. #endif
  228. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  229. #ifndef _IN_PORT_T
  230. #ifndef in_port_t
  231. #define in_port_t u_short
  232. #endif
  233. #endif
  234. #ifndef _WIN32_WCE
  235. #include <process.h>
  236. #include <direct.h>
  237. #include <io.h>
  238. #else /* _WIN32_WCE */
  239. #define NO_CGI /* WinCE has no pipes */
  240. #define NO_POPEN /* WinCE has no popen */
  241. typedef long off_t;
  242. #define errno ((int)(GetLastError()))
  243. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  244. #endif /* _WIN32_WCE */
  245. #define MAKEUQUAD(lo, hi) \
  246. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  247. #define RATE_DIFF (10000000) /* 100 nsecs */
  248. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  249. #define SYS2UNIX_TIME(lo, hi) \
  250. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  251. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  252. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  253. * Also use _strtoui64 on modern M$ compilers */
  254. #if defined(_MSC_VER)
  255. #if (_MSC_VER < 1300)
  256. #define STRX(x) #x
  257. #define STR(x) STRX(x)
  258. #define __func__ __FILE__ ":" STR(__LINE__)
  259. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  260. #define strtoll(x, y, z) (_atoi64(x))
  261. #else
  262. #define __func__ __FUNCTION__
  263. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  264. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  265. #endif
  266. #endif /* _MSC_VER */
  267. #define ERRNO ((int)(GetLastError()))
  268. #define NO_SOCKLEN_T
  269. #if defined(_WIN64) || defined(__MINGW64__)
  270. #define SSL_LIB "ssleay64.dll"
  271. #define CRYPTO_LIB "libeay64.dll"
  272. #else
  273. #define SSL_LIB "ssleay32.dll"
  274. #define CRYPTO_LIB "libeay32.dll"
  275. #endif
  276. #define O_NONBLOCK (0)
  277. #ifndef W_OK
  278. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  279. #endif
  280. #if !defined(EWOULDBLOCK)
  281. #define EWOULDBLOCK WSAEWOULDBLOCK
  282. #endif /* !EWOULDBLOCK */
  283. #define _POSIX_
  284. #define INT64_FMT "I64d"
  285. #define UINT64_FMT "I64u"
  286. #define WINCDECL __cdecl
  287. #define vsnprintf_impl _vsnprintf
  288. #define access _access
  289. #define mg_sleep(x) (Sleep(x))
  290. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  291. #ifndef popen
  292. #define popen(x, y) (_popen(x, y))
  293. #endif
  294. #ifndef pclose
  295. #define pclose(x) (_pclose(x))
  296. #endif
  297. #define close(x) (_close(x))
  298. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  299. #define RTLD_LAZY (0)
  300. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  301. #define fdopen(x, y) (_fdopen((x), (y)))
  302. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  303. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  304. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  305. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  306. #define sleep(x) (Sleep((x)*1000))
  307. #define rmdir(x) (_rmdir(x))
  308. #define timegm(x) (_mkgmtime(x))
  309. #if !defined(fileno)
  310. #define fileno(x) (_fileno(x))
  311. #endif /* !fileno MINGW #defines fileno */
  312. typedef HANDLE pthread_mutex_t;
  313. typedef DWORD pthread_key_t;
  314. typedef HANDLE pthread_t;
  315. typedef struct {
  316. CRITICAL_SECTION threadIdSec;
  317. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  318. } pthread_cond_t;
  319. #ifndef __clockid_t_defined
  320. typedef DWORD clockid_t;
  321. #endif
  322. #ifndef CLOCK_MONOTONIC
  323. #define CLOCK_MONOTONIC (1)
  324. #endif
  325. #ifndef CLOCK_REALTIME
  326. #define CLOCK_REALTIME (2)
  327. #endif
  328. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  329. #define _TIMESPEC_DEFINED
  330. #endif
  331. #ifndef _TIMESPEC_DEFINED
  332. struct timespec {
  333. time_t tv_sec; /* seconds */
  334. long tv_nsec; /* nanoseconds */
  335. };
  336. #endif
  337. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  338. static int pthread_mutex_lock(pthread_mutex_t *);
  339. static int pthread_mutex_unlock(pthread_mutex_t *);
  340. static void path_to_unicode(const struct mg_connection *conn,
  341. const char *path,
  342. wchar_t *wbuf,
  343. size_t wbuf_len);
  344. /* All file operations need to be rewritten to solve #246. */
  345. #include "file_ops.inl"
  346. struct mg_file;
  347. static const char *
  348. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  349. /* POSIX dirent interface */
  350. struct dirent {
  351. char d_name[PATH_MAX];
  352. };
  353. typedef struct DIR {
  354. HANDLE handle;
  355. WIN32_FIND_DATAW info;
  356. struct dirent result;
  357. } DIR;
  358. #if defined(_WIN32) && !defined(POLLIN)
  359. #ifndef HAVE_POLL
  360. struct pollfd {
  361. SOCKET fd;
  362. short events;
  363. short revents;
  364. };
  365. #define POLLIN (0x0300)
  366. #endif
  367. #endif
  368. /* Mark required libraries */
  369. #if defined(_MSC_VER)
  370. #pragma comment(lib, "Ws2_32.lib")
  371. #endif
  372. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  373. WINDOWS / UNIX include block */
  374. #include <sys/wait.h>
  375. #include <sys/socket.h>
  376. #include <sys/poll.h>
  377. #include <netinet/in.h>
  378. #include <arpa/inet.h>
  379. #include <sys/time.h>
  380. #include <sys/utsname.h>
  381. #include <stdint.h>
  382. #include <inttypes.h>
  383. #include <netdb.h>
  384. #include <netinet/tcp.h>
  385. typedef const void *SOCK_OPT_TYPE;
  386. #if defined(ANDROID)
  387. typedef unsigned short int in_port_t;
  388. #endif
  389. #include <pwd.h>
  390. #include <unistd.h>
  391. #include <grp.h>
  392. #include <dirent.h>
  393. #define vsnprintf_impl vsnprintf
  394. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  395. #include <dlfcn.h>
  396. #endif
  397. #include <pthread.h>
  398. #if defined(__MACH__)
  399. #define SSL_LIB "libssl.dylib"
  400. #define CRYPTO_LIB "libcrypto.dylib"
  401. #else
  402. #if !defined(SSL_LIB)
  403. #define SSL_LIB "libssl.so"
  404. #endif
  405. #if !defined(CRYPTO_LIB)
  406. #define CRYPTO_LIB "libcrypto.so"
  407. #endif
  408. #endif
  409. #ifndef O_BINARY
  410. #define O_BINARY (0)
  411. #endif /* O_BINARY */
  412. #define closesocket(a) (close(a))
  413. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  414. #define mg_remove(conn, x) (remove(x))
  415. #define mg_sleep(x) (usleep((x)*1000))
  416. #define mg_opendir(conn, x) (opendir(x))
  417. #define mg_closedir(x) (closedir(x))
  418. #define mg_readdir(x) (readdir(x))
  419. #define ERRNO (errno)
  420. #define INVALID_SOCKET (-1)
  421. #define INT64_FMT PRId64
  422. #define UINT64_FMT PRIu64
  423. typedef int SOCKET;
  424. #define WINCDECL
  425. #if defined(__hpux)
  426. /* HPUX 11 does not have monotonic, fall back to realtime */
  427. #ifndef CLOCK_MONOTONIC
  428. #define CLOCK_MONOTONIC CLOCK_REALTIME
  429. #endif
  430. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  431. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  432. * the prototypes use int* rather than socklen_t* which matches the
  433. * actual library expectation. When called with the wrong size arg
  434. * accept() returns a zero client inet addr and check_acl() always
  435. * fails. Since socklen_t is widely used below, just force replace
  436. * their typedef with int. - DTL
  437. */
  438. #define socklen_t int
  439. #endif /* hpux */
  440. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  441. WINDOWS / UNIX include block */
  442. /* va_copy should always be a macro, C99 and C++11 - DTL */
  443. #ifndef va_copy
  444. #define va_copy(x, y) ((x) = (y))
  445. #endif
  446. #ifdef _WIN32
  447. /* Create substitutes for POSIX functions in Win32. */
  448. #if defined(__MINGW32__)
  449. /* Show no warning in case system functions are not used. */
  450. #pragma GCC diagnostic push
  451. #pragma GCC diagnostic ignored "-Wunused-function"
  452. #endif
  453. static CRITICAL_SECTION global_log_file_lock;
  454. static DWORD
  455. pthread_self(void)
  456. {
  457. return GetCurrentThreadId();
  458. }
  459. static int
  460. pthread_key_create(
  461. pthread_key_t *key,
  462. void (*_ignored)(void *) /* destructor not supported for Windows */
  463. )
  464. {
  465. (void)_ignored;
  466. if ((key != 0)) {
  467. *key = TlsAlloc();
  468. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  469. }
  470. return -2;
  471. }
  472. static int
  473. pthread_key_delete(pthread_key_t key)
  474. {
  475. return TlsFree(key) ? 0 : 1;
  476. }
  477. static int
  478. pthread_setspecific(pthread_key_t key, void *value)
  479. {
  480. return TlsSetValue(key, value) ? 0 : 1;
  481. }
  482. static void *
  483. pthread_getspecific(pthread_key_t key)
  484. {
  485. return TlsGetValue(key);
  486. }
  487. #if defined(__MINGW32__)
  488. /* Enable unused function warning again */
  489. #pragma GCC diagnostic pop
  490. #endif
  491. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  492. #else
  493. static pthread_mutexattr_t pthread_mutex_attr;
  494. #endif /* _WIN32 */
  495. #define PASSWORDS_FILE_NAME ".htpasswd"
  496. #define CGI_ENVIRONMENT_SIZE (4096)
  497. #define MAX_CGI_ENVIR_VARS (256)
  498. #define MG_BUF_LEN (8192)
  499. #ifndef MAX_REQUEST_SIZE
  500. #define MAX_REQUEST_SIZE (16384)
  501. #endif
  502. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  503. "request size length must be a positive number");
  504. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  505. #if !defined(DEBUG_TRACE)
  506. #if defined(DEBUG)
  507. #if defined(_WIN32_WCE)
  508. /* Create substitutes for POSIX functions in Win32. */
  509. #if defined(__MINGW32__)
  510. /* Show no warning in case system functions are not used. */
  511. #pragma GCC diagnostic push
  512. #pragma GCC diagnostic ignored "-Wunused-function"
  513. #endif
  514. static time_t
  515. time(time_t *ptime)
  516. {
  517. time_t t;
  518. SYSTEMTIME st;
  519. FILETIME ft;
  520. GetSystemTime(&st);
  521. SystemTimeToFileTime(&st, &ft);
  522. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  523. if (ptime != NULL) {
  524. *ptime = t;
  525. }
  526. return t;
  527. }
  528. static struct tm *
  529. localtime_s(const time_t *ptime, struct tm *ptm)
  530. {
  531. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  532. FILETIME ft, lft;
  533. SYSTEMTIME st;
  534. TIME_ZONE_INFORMATION tzinfo;
  535. if (ptm == NULL) {
  536. return NULL;
  537. }
  538. *(int64_t *)&ft = t;
  539. FileTimeToLocalFileTime(&ft, &lft);
  540. FileTimeToSystemTime(&lft, &st);
  541. ptm->tm_year = st.wYear - 1900;
  542. ptm->tm_mon = st.wMonth - 1;
  543. ptm->tm_wday = st.wDayOfWeek;
  544. ptm->tm_mday = st.wDay;
  545. ptm->tm_hour = st.wHour;
  546. ptm->tm_min = st.wMinute;
  547. ptm->tm_sec = st.wSecond;
  548. ptm->tm_yday = 0; /* hope nobody uses this */
  549. ptm->tm_isdst =
  550. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  551. return ptm;
  552. }
  553. static struct tm *
  554. gmtime_s(const time_t *ptime, struct tm *ptm)
  555. {
  556. /* FIXME(lsm): fix this. */
  557. return localtime_s(ptime, ptm);
  558. }
  559. static int mg_atomic_inc(volatile int *addr);
  560. static struct tm tm_array[MAX_WORKER_THREADS];
  561. static int tm_index = 0;
  562. static struct tm *
  563. localtime(const time_t *ptime)
  564. {
  565. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  566. return localtime_s(ptime, tm_array + i);
  567. }
  568. static struct tm *
  569. gmtime(const time_t *ptime)
  570. {
  571. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  572. return gmtime_s(ptime, tm_array + i);
  573. }
  574. static size_t
  575. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  576. {
  577. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  578. // for WinCE");
  579. return 0;
  580. }
  581. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  582. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  583. #define remove(f) mg_remove(NULL, f)
  584. static int
  585. rename(const char *a, const char *b)
  586. {
  587. wchar_t wa[PATH_MAX];
  588. wchar_t wb[PATH_MAX];
  589. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  590. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  591. return MoveFileW(wa, wb) ? 0 : -1;
  592. }
  593. struct stat {
  594. int64_t st_size;
  595. time_t st_mtime;
  596. };
  597. static int
  598. stat(const char *name, struct stat *st)
  599. {
  600. wchar_t wbuf[PATH_MAX];
  601. WIN32_FILE_ATTRIBUTE_DATA attr;
  602. time_t creation_time, write_time;
  603. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  604. memset(&attr, 0, sizeof(attr));
  605. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  606. st->st_size =
  607. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  608. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  609. attr.ftLastWriteTime.dwHighDateTime);
  610. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  611. attr.ftCreationTime.dwHighDateTime);
  612. if (creation_time > write_time) {
  613. st->st_mtime = creation_time;
  614. } else {
  615. st->st_mtime = write_time;
  616. }
  617. return 0;
  618. }
  619. #define access(x, a) 1 /* not required anyway */
  620. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  621. #define EEXIST 1 /* TODO: See Windows error codes */
  622. #define EACCES 2 /* TODO: See Windows error codes */
  623. #define ENOENT 3 /* TODO: See Windows Error codes */
  624. #if defined(__MINGW32__)
  625. /* Enable unused function warning again */
  626. #pragma GCC diagnostic pop
  627. #endif
  628. #endif /* defined(_WIN32_WCE) */
  629. static void DEBUG_TRACE_FUNC(const char *func,
  630. unsigned line,
  631. PRINTF_FORMAT_STRING(const char *fmt),
  632. ...) PRINTF_ARGS(3, 4);
  633. static void
  634. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  635. {
  636. va_list args;
  637. flockfile(stdout);
  638. printf("*** %lu.%p.%s.%u: ",
  639. (unsigned long)time(NULL),
  640. (void *)pthread_self(),
  641. func,
  642. line);
  643. va_start(args, fmt);
  644. vprintf(fmt, args);
  645. va_end(args);
  646. putchar('\n');
  647. fflush(stdout);
  648. funlockfile(stdout);
  649. }
  650. #define DEBUG_TRACE(fmt, ...) \
  651. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  652. #else
  653. #define DEBUG_TRACE(fmt, ...) \
  654. do { \
  655. } while (0)
  656. #endif /* DEBUG */
  657. #endif /* DEBUG_TRACE */
  658. #if defined(MEMORY_DEBUGGING)
  659. unsigned long mg_memory_debug_blockCount = 0;
  660. unsigned long mg_memory_debug_totalMemUsed = 0;
  661. static void *
  662. mg_malloc_ex(size_t size, const char *file, unsigned line)
  663. {
  664. void *data = malloc(size + sizeof(size_t));
  665. void *memory = 0;
  666. char mallocStr[256];
  667. if (data) {
  668. *(size_t *)data = size;
  669. mg_memory_debug_totalMemUsed += size;
  670. mg_memory_debug_blockCount++;
  671. memory = (void *)(((char *)data) + sizeof(size_t));
  672. }
  673. sprintf(mallocStr,
  674. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  675. memory,
  676. (unsigned long)size,
  677. mg_memory_debug_totalMemUsed,
  678. mg_memory_debug_blockCount,
  679. file,
  680. line);
  681. #if defined(_WIN32)
  682. OutputDebugStringA(mallocStr);
  683. #else
  684. DEBUG_TRACE("%s", mallocStr);
  685. #endif
  686. return memory;
  687. }
  688. static void *
  689. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  690. {
  691. void *data = mg_malloc_ex(size * count, file, line);
  692. if (data) {
  693. memset(data, 0, size * count);
  694. }
  695. return data;
  696. }
  697. static void
  698. mg_free_ex(void *memory, const char *file, unsigned line)
  699. {
  700. char mallocStr[256];
  701. void *data = (void *)(((char *)memory) - sizeof(size_t));
  702. size_t size;
  703. if (memory) {
  704. size = *(size_t *)data;
  705. mg_memory_debug_totalMemUsed -= size;
  706. mg_memory_debug_blockCount--;
  707. sprintf(mallocStr,
  708. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  709. memory,
  710. (unsigned long)size,
  711. mg_memory_debug_totalMemUsed,
  712. mg_memory_debug_blockCount,
  713. file,
  714. line);
  715. #if defined(_WIN32)
  716. OutputDebugStringA(mallocStr);
  717. #else
  718. DEBUG_TRACE("%s", mallocStr);
  719. #endif
  720. free(data);
  721. }
  722. }
  723. static void *
  724. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  725. {
  726. char mallocStr[256];
  727. void *data;
  728. void *_realloc;
  729. size_t oldsize;
  730. if (newsize) {
  731. if (memory) {
  732. data = (void *)(((char *)memory) - sizeof(size_t));
  733. oldsize = *(size_t *)data;
  734. _realloc = realloc(data, newsize + sizeof(size_t));
  735. if (_realloc) {
  736. data = _realloc;
  737. mg_memory_debug_totalMemUsed -= oldsize;
  738. sprintf(mallocStr,
  739. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  740. memory,
  741. (unsigned long)oldsize,
  742. mg_memory_debug_totalMemUsed,
  743. mg_memory_debug_blockCount,
  744. file,
  745. line);
  746. #if defined(_WIN32)
  747. OutputDebugStringA(mallocStr);
  748. #else
  749. DEBUG_TRACE("%s", mallocStr);
  750. #endif
  751. mg_memory_debug_totalMemUsed += newsize;
  752. sprintf(mallocStr,
  753. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  754. memory,
  755. (unsigned long)newsize,
  756. mg_memory_debug_totalMemUsed,
  757. mg_memory_debug_blockCount,
  758. file,
  759. line);
  760. #if defined(_WIN32)
  761. OutputDebugStringA(mallocStr);
  762. #else
  763. DEBUG_TRACE("%s", mallocStr);
  764. #endif
  765. *(size_t *)data = newsize;
  766. data = (void *)(((char *)data) + sizeof(size_t));
  767. } else {
  768. #if defined(_WIN32)
  769. OutputDebugStringA("MEM: realloc failed\n");
  770. #else
  771. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  772. #endif
  773. return _realloc;
  774. }
  775. } else {
  776. data = mg_malloc_ex(newsize, file, line);
  777. }
  778. } else {
  779. data = 0;
  780. mg_free_ex(memory, file, line);
  781. }
  782. return data;
  783. }
  784. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  785. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  786. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  787. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  788. #else
  789. static __inline void *
  790. mg_malloc(size_t a)
  791. {
  792. return malloc(a);
  793. }
  794. static __inline void *
  795. mg_calloc(size_t a, size_t b)
  796. {
  797. return calloc(a, b);
  798. }
  799. static __inline void *
  800. mg_realloc(void *a, size_t b)
  801. {
  802. return realloc(a, b);
  803. }
  804. static __inline void
  805. mg_free(void *a)
  806. {
  807. free(a);
  808. }
  809. #endif
  810. static void mg_vsnprintf(const struct mg_connection *conn,
  811. int *truncated,
  812. char *buf,
  813. size_t buflen,
  814. const char *fmt,
  815. va_list ap);
  816. static void mg_snprintf(const struct mg_connection *conn,
  817. int *truncated,
  818. char *buf,
  819. size_t buflen,
  820. PRINTF_FORMAT_STRING(const char *fmt),
  821. ...) PRINTF_ARGS(5, 6);
  822. /* This following lines are just meant as a reminder to use the mg-functions
  823. * for memory management */
  824. #ifdef malloc
  825. #undef malloc
  826. #endif
  827. #ifdef calloc
  828. #undef calloc
  829. #endif
  830. #ifdef realloc
  831. #undef realloc
  832. #endif
  833. #ifdef free
  834. #undef free
  835. #endif
  836. #ifdef snprintf
  837. #undef snprintf
  838. #endif
  839. #ifdef vsnprintf
  840. #undef vsnprintf
  841. #endif
  842. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  843. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  844. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  845. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  846. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  847. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  848. * but this define only works well for Windows. */
  849. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  850. #endif
  851. #define MD5_STATIC static
  852. #include "md5.inl"
  853. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  854. #ifdef NO_SOCKLEN_T
  855. typedef int socklen_t;
  856. #endif /* NO_SOCKLEN_T */
  857. #define _DARWIN_UNLIMITED_SELECT
  858. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  859. #if !defined(MSG_NOSIGNAL)
  860. #define MSG_NOSIGNAL (0)
  861. #endif
  862. #if !defined(SOMAXCONN)
  863. #define SOMAXCONN (100)
  864. #endif
  865. /* Size of the accepted socket queue */
  866. #if !defined(MGSQLEN)
  867. #define MGSQLEN (20)
  868. #endif
  869. #if defined(NO_SSL)
  870. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  871. typedef struct SSL_CTX SSL_CTX;
  872. #else
  873. #if defined(NO_SSL_DL)
  874. #include <openssl/ssl.h>
  875. #include <openssl/err.h>
  876. #include <openssl/crypto.h>
  877. #include <openssl/x509.h>
  878. #include <openssl/pem.h>
  879. #include <openssl/engine.h>
  880. #include <openssl/conf.h>
  881. #include <openssl/dh.h>
  882. #else
  883. /* SSL loaded dynamically from DLL.
  884. * I put the prototypes here to be independent from OpenSSL source
  885. * installation. */
  886. typedef struct ssl_st SSL;
  887. typedef struct ssl_method_st SSL_METHOD;
  888. typedef struct ssl_ctx_st SSL_CTX;
  889. typedef struct x509_store_ctx_st X509_STORE_CTX;
  890. typedef struct x509_name X509_NAME;
  891. typedef struct asn1_integer ASN1_INTEGER;
  892. typedef struct evp_md EVP_MD;
  893. typedef struct x509 X509;
  894. #define SSL_CTRL_OPTIONS (32)
  895. #define SSL_CTRL_CLEAR_OPTIONS (77)
  896. #define SSL_CTRL_SET_ECDH_AUTO (94)
  897. #define SSL_VERIFY_NONE (0)
  898. #define SSL_VERIFY_PEER (1)
  899. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  900. #define SSL_VERIFY_CLIENT_ONCE (4)
  901. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  902. #define SSL_OP_NO_SSLv2 (0x01000000L)
  903. #define SSL_OP_NO_SSLv3 (0x02000000L)
  904. #define SSL_OP_NO_TLSv1 (0x04000000L)
  905. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  906. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  907. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  908. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  909. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  910. #define SSL_ERROR_NONE (0)
  911. #define SSL_ERROR_SSL (1)
  912. #define SSL_ERROR_WANT_READ (2)
  913. #define SSL_ERROR_WANT_WRITE (3)
  914. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  915. #define SSL_ERROR_SYSCALL (5) /* see errno */
  916. #define SSL_ERROR_ZERO_RETURN (6)
  917. #define SSL_ERROR_WANT_CONNECT (7)
  918. #define SSL_ERROR_WANT_ACCEPT (8)
  919. struct ssl_func {
  920. const char *name; /* SSL function name */
  921. void (*ptr)(void); /* Function pointer */
  922. };
  923. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  924. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  925. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  926. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  927. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  928. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  929. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  930. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  931. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  932. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  933. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  934. #define SSL_CTX_use_PrivateKey_file \
  935. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  936. #define SSL_CTX_use_certificate_file \
  937. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  938. #define SSL_CTX_set_default_passwd_cb \
  939. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  940. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  941. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  942. #define SSL_CTX_use_certificate_chain_file \
  943. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  944. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  945. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  946. #define SSL_CTX_set_verify \
  947. (*(void (*)(SSL_CTX *, \
  948. int, \
  949. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  950. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  951. #define SSL_CTX_load_verify_locations \
  952. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  953. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  954. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  955. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  956. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  957. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  958. #define SSL_CIPHER_get_name \
  959. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  960. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  961. #define SSL_CTX_set_session_id_context \
  962. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  963. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  964. #define SSL_CTX_set_cipher_list \
  965. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  966. #define SSL_CTX_set_options(ctx, op) \
  967. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  968. #define SSL_CTX_clear_options(ctx, op) \
  969. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  970. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  971. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  972. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  973. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  974. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  975. #define CRYPTO_set_locking_callback \
  976. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  977. #define CRYPTO_set_id_callback \
  978. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  979. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  980. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  981. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  982. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  983. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  984. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  985. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  986. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  987. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  988. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  989. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  990. #define X509_NAME_oneline \
  991. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  992. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  993. #define i2c_ASN1_INTEGER \
  994. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  995. #define EVP_get_digestbyname \
  996. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  997. #define ASN1_digest \
  998. (*(int (*)(int (*)(), \
  999. const EVP_MD *, \
  1000. char *, \
  1001. unsigned char *, \
  1002. unsigned int *))crypto_sw[18].ptr)
  1003. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1004. /* set_ssl_option() function updates this array.
  1005. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1006. * of respective functions. The macros above (like SSL_connect()) are really
  1007. * just calling these functions indirectly via the pointer. */
  1008. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1009. {"SSL_accept", NULL},
  1010. {"SSL_connect", NULL},
  1011. {"SSL_read", NULL},
  1012. {"SSL_write", NULL},
  1013. {"SSL_get_error", NULL},
  1014. {"SSL_set_fd", NULL},
  1015. {"SSL_new", NULL},
  1016. {"SSL_CTX_new", NULL},
  1017. {"SSLv23_server_method", NULL},
  1018. {"SSL_library_init", NULL},
  1019. {"SSL_CTX_use_PrivateKey_file", NULL},
  1020. {"SSL_CTX_use_certificate_file", NULL},
  1021. {"SSL_CTX_set_default_passwd_cb", NULL},
  1022. {"SSL_CTX_free", NULL},
  1023. {"SSL_load_error_strings", NULL},
  1024. {"SSL_CTX_use_certificate_chain_file", NULL},
  1025. {"SSLv23_client_method", NULL},
  1026. {"SSL_pending", NULL},
  1027. {"SSL_CTX_set_verify", NULL},
  1028. {"SSL_shutdown", NULL},
  1029. {"SSL_CTX_load_verify_locations", NULL},
  1030. {"SSL_CTX_set_default_verify_paths", NULL},
  1031. {"SSL_CTX_set_verify_depth", NULL},
  1032. {"SSL_get_peer_certificate", NULL},
  1033. {"SSL_get_version", NULL},
  1034. {"SSL_get_current_cipher", NULL},
  1035. {"SSL_CIPHER_get_name", NULL},
  1036. {"SSL_CTX_check_private_key", NULL},
  1037. {"SSL_CTX_set_session_id_context", NULL},
  1038. {"SSL_CTX_ctrl", NULL},
  1039. {"SSL_CTX_set_cipher_list", NULL},
  1040. {NULL, NULL}};
  1041. /* Similar array as ssl_sw. These functions could be located in different
  1042. * lib. */
  1043. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1044. {"CRYPTO_set_locking_callback", NULL},
  1045. {"CRYPTO_set_id_callback", NULL},
  1046. {"ERR_get_error", NULL},
  1047. {"ERR_error_string", NULL},
  1048. {"ERR_remove_state", NULL},
  1049. {"ERR_free_strings", NULL},
  1050. {"ENGINE_cleanup", NULL},
  1051. {"CONF_modules_unload", NULL},
  1052. {"CRYPTO_cleanup_all_ex_data", NULL},
  1053. {"EVP_cleanup", NULL},
  1054. {"X509_free", NULL},
  1055. {"X509_get_subject_name", NULL},
  1056. {"X509_get_issuer_name", NULL},
  1057. {"X509_NAME_oneline", NULL},
  1058. {"X509_get_serialNumber", NULL},
  1059. {"i2c_ASN1_INTEGER", NULL},
  1060. {"EVP_get_digestbyname", NULL},
  1061. {"ASN1_digest", NULL},
  1062. {"i2d_X509", NULL},
  1063. {NULL, NULL}};
  1064. #endif /* NO_SSL_DL */
  1065. #endif /* NO_SSL */
  1066. #if !defined(NO_CACHING)
  1067. static const char *month_names[] = {"Jan",
  1068. "Feb",
  1069. "Mar",
  1070. "Apr",
  1071. "May",
  1072. "Jun",
  1073. "Jul",
  1074. "Aug",
  1075. "Sep",
  1076. "Oct",
  1077. "Nov",
  1078. "Dec"};
  1079. #endif /* !NO_CACHING */
  1080. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1081. * union u. */
  1082. union usa {
  1083. struct sockaddr sa;
  1084. struct sockaddr_in sin;
  1085. #if defined(USE_IPV6)
  1086. struct sockaddr_in6 sin6;
  1087. #endif
  1088. };
  1089. /* Describes a string (chunk of memory). */
  1090. struct vec {
  1091. const char *ptr;
  1092. size_t len;
  1093. };
  1094. struct mg_file_stat {
  1095. /* File properties filled by mg_stat: */
  1096. uint64_t size;
  1097. time_t last_modified;
  1098. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1099. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1100. * case we need a "Content-Eencoding: gzip" header */
  1101. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1102. };
  1103. struct mg_file_access {
  1104. /* File properties filled by mg_fopen: */
  1105. FILE *fp;
  1106. const char *membuf;
  1107. };
  1108. struct mg_file {
  1109. struct mg_file_stat stat;
  1110. struct mg_file_access access;
  1111. };
  1112. #define STRUCT_FILE_INITIALIZER \
  1113. { \
  1114. { \
  1115. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1116. } \
  1117. , \
  1118. { \
  1119. (FILE *) NULL, (const char *)NULL \
  1120. } \
  1121. }
  1122. /* Describes listening socket, or socket which was accept()-ed by the master
  1123. * thread and queued for future handling by the worker thread. */
  1124. struct socket {
  1125. SOCKET sock; /* Listening socket */
  1126. union usa lsa; /* Local socket address */
  1127. union usa rsa; /* Remote socket address */
  1128. unsigned char is_ssl; /* Is port SSL-ed */
  1129. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1130. * port */
  1131. unsigned char in_use; /* Is valid */
  1132. };
  1133. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1134. enum {
  1135. CGI_EXTENSIONS,
  1136. CGI_ENVIRONMENT,
  1137. PUT_DELETE_PASSWORDS_FILE,
  1138. CGI_INTERPRETER,
  1139. PROTECT_URI,
  1140. AUTHENTICATION_DOMAIN,
  1141. SSI_EXTENSIONS,
  1142. THROTTLE,
  1143. ACCESS_LOG_FILE,
  1144. ENABLE_DIRECTORY_LISTING,
  1145. ERROR_LOG_FILE,
  1146. GLOBAL_PASSWORDS_FILE,
  1147. INDEX_FILES,
  1148. ENABLE_KEEP_ALIVE,
  1149. ACCESS_CONTROL_LIST,
  1150. EXTRA_MIME_TYPES,
  1151. LISTENING_PORTS,
  1152. DOCUMENT_ROOT,
  1153. SSL_CERTIFICATE,
  1154. NUM_THREADS,
  1155. RUN_AS_USER,
  1156. REWRITE,
  1157. HIDE_FILES,
  1158. REQUEST_TIMEOUT,
  1159. SSL_DO_VERIFY_PEER,
  1160. SSL_CA_PATH,
  1161. SSL_CA_FILE,
  1162. SSL_VERIFY_DEPTH,
  1163. SSL_DEFAULT_VERIFY_PATHS,
  1164. SSL_CIPHER_LIST,
  1165. SSL_PROTOCOL_VERSION,
  1166. SSL_SHORT_TRUST,
  1167. #if defined(USE_WEBSOCKET)
  1168. WEBSOCKET_TIMEOUT,
  1169. #endif
  1170. DECODE_URL,
  1171. #if defined(USE_LUA)
  1172. LUA_PRELOAD_FILE,
  1173. LUA_SCRIPT_EXTENSIONS,
  1174. LUA_SERVER_PAGE_EXTENSIONS,
  1175. #endif
  1176. #if defined(USE_DUKTAPE)
  1177. DUKTAPE_SCRIPT_EXTENSIONS,
  1178. #endif
  1179. #if defined(USE_WEBSOCKET)
  1180. WEBSOCKET_ROOT,
  1181. #endif
  1182. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1183. LUA_WEBSOCKET_EXTENSIONS,
  1184. #endif
  1185. ACCESS_CONTROL_ALLOW_ORIGIN,
  1186. ERROR_PAGES,
  1187. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1188. * socket option typedef TCP_NODELAY. */
  1189. #if !defined(NO_CACHING)
  1190. STATIC_FILE_MAX_AGE,
  1191. #endif
  1192. #if defined(__linux__)
  1193. ALLOW_SENDFILE_CALL,
  1194. #endif
  1195. #if defined(_WIN32)
  1196. CASE_SENSITIVE_FILES,
  1197. #endif
  1198. NUM_OPTIONS
  1199. };
  1200. /* Config option name, config types, default value */
  1201. static struct mg_option config_options[] = {
  1202. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1203. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1204. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1205. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1206. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1207. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1208. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1209. {"throttle", CONFIG_TYPE_STRING, NULL},
  1210. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1211. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1212. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1213. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1214. {"index_files",
  1215. CONFIG_TYPE_STRING,
  1216. #ifdef USE_LUA
  1217. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1218. "index.shtml,index.php"},
  1219. #else
  1220. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1221. #endif
  1222. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1223. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1224. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1225. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1226. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1227. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1228. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1229. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1230. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1231. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1232. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1233. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1234. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1235. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1236. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1237. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1238. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1239. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1240. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1241. #if defined(USE_WEBSOCKET)
  1242. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1243. #endif
  1244. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1245. #if defined(USE_LUA)
  1246. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1247. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1248. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1249. #endif
  1250. #if defined(USE_DUKTAPE)
  1251. /* The support for duktape is still in alpha version state.
  1252. * The name of this config option might change. */
  1253. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1254. #endif
  1255. #if defined(USE_WEBSOCKET)
  1256. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1257. #endif
  1258. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1259. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1260. #endif
  1261. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1262. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1263. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1264. #if !defined(NO_CACHING)
  1265. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1266. #endif
  1267. #if defined(__linux__)
  1268. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1269. #endif
  1270. #if defined(_WIN32)
  1271. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1272. #endif
  1273. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1274. /* Check if the config_options and the corresponding enum have compatible
  1275. * sizes. */
  1276. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1277. == (NUM_OPTIONS + 1),
  1278. "config_options and enum not sync");
  1279. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1280. struct mg_handler_info {
  1281. /* Name/Pattern of the URI. */
  1282. char *uri;
  1283. size_t uri_len;
  1284. /* handler type */
  1285. int handler_type;
  1286. /* Handler for http/https or authorization requests. */
  1287. mg_request_handler handler;
  1288. /* Handler for ws/wss (websocket) requests. */
  1289. mg_websocket_connect_handler connect_handler;
  1290. mg_websocket_ready_handler ready_handler;
  1291. mg_websocket_data_handler data_handler;
  1292. mg_websocket_close_handler close_handler;
  1293. /* accepted subprotocols for ws/wss requests. */
  1294. struct mg_websocket_subprotocols *subprotocols;
  1295. /* Handler for authorization requests */
  1296. mg_authorization_handler auth_handler;
  1297. /* User supplied argument for the handler function. */
  1298. void *cbdata;
  1299. /* next handler in a linked list */
  1300. struct mg_handler_info *next;
  1301. };
  1302. struct mg_context {
  1303. volatile int stop_flag; /* Should we stop event loop */
  1304. SSL_CTX *ssl_ctx; /* SSL context */
  1305. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1306. struct mg_callbacks callbacks; /* User-defined callback function */
  1307. void *user_data; /* User-defined data */
  1308. int context_type; /* 1 = server context,
  1309. * 2 = ws/wss client context,
  1310. */
  1311. struct socket *listening_sockets;
  1312. struct pollfd *listening_socket_fds;
  1313. unsigned int num_listening_sockets;
  1314. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1315. #ifdef ALTERNATIVE_QUEUE
  1316. struct socket *client_socks;
  1317. void **client_wait_events;
  1318. #else
  1319. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1320. volatile int sq_head; /* Head of the socket queue */
  1321. volatile int sq_tail; /* Tail of the socket queue */
  1322. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1323. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1324. #endif
  1325. pthread_t masterthreadid; /* The master thread ID */
  1326. unsigned int
  1327. cfg_worker_threads; /* The number of configured worker threads. */
  1328. pthread_t *workerthreadids; /* The worker thread IDs */
  1329. time_t start_time; /* Server start time, used for authentication */
  1330. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1331. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1332. unsigned long nonce_count; /* Used nonces, used for authentication */
  1333. char *systemName; /* What operating system is running */
  1334. /* linked list of uri handlers */
  1335. struct mg_handler_info *handlers;
  1336. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1337. /* linked list of shared lua websockets */
  1338. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1339. #endif
  1340. #ifdef USE_TIMERS
  1341. struct ttimers *timers;
  1342. #endif
  1343. };
  1344. struct mg_connection {
  1345. struct mg_request_info request_info;
  1346. struct mg_context *ctx;
  1347. SSL *ssl; /* SSL descriptor */
  1348. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1349. struct socket client; /* Connected client */
  1350. time_t conn_birth_time; /* Time (wall clock) when connection was
  1351. * established */
  1352. struct timespec req_time; /* Time (since system start) when the request
  1353. * was received */
  1354. int64_t num_bytes_sent; /* Total bytes sent to client */
  1355. int64_t content_len; /* Content-Length header value */
  1356. int64_t consumed_content; /* How many bytes of content have been read */
  1357. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1358. * data available, 2: all data read */
  1359. size_t chunk_remainder; /* Unread data from the last chunk */
  1360. char *buf; /* Buffer for received data */
  1361. char *path_info; /* PATH_INFO part of the URL */
  1362. int must_close; /* 1 if connection must be closed */
  1363. int in_error_handler; /* 1 if in handler for user defined error
  1364. * pages */
  1365. int internal_error; /* 1 if an error occured while processing the
  1366. * request */
  1367. int buf_size; /* Buffer size */
  1368. int request_len; /* Size of the request + headers in a buffer */
  1369. int data_len; /* Total size of data in a buffer */
  1370. int status_code; /* HTTP reply status code, e.g. 200 */
  1371. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1372. * throttle */
  1373. time_t last_throttle_time; /* Last time throttled data was sent */
  1374. int64_t last_throttle_bytes; /* Bytes sent this second */
  1375. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1376. * atomic transmissions for websockets */
  1377. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1378. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1379. #endif
  1380. int thread_index; /* Thread index within ctx */
  1381. };
  1382. static pthread_key_t sTlsKey; /* Thread local storage index */
  1383. static int sTlsInit = 0;
  1384. static int thread_idx_max = 0;
  1385. struct mg_workerTLS {
  1386. int is_master;
  1387. unsigned long thread_idx;
  1388. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1389. HANDLE pthread_cond_helper_mutex;
  1390. struct mg_workerTLS *next_waiting_thread;
  1391. #endif
  1392. };
  1393. /* Directory entry */
  1394. struct de {
  1395. struct mg_connection *conn;
  1396. char *file_name;
  1397. struct mg_file_stat file;
  1398. };
  1399. #if defined(USE_WEBSOCKET)
  1400. static int is_websocket_protocol(const struct mg_connection *conn);
  1401. #else
  1402. #define is_websocket_protocol(conn) (0)
  1403. #endif
  1404. static int
  1405. mg_atomic_inc(volatile int *addr)
  1406. {
  1407. int ret;
  1408. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1409. /* Depending on the SDK, this function uses either
  1410. * (volatile unsigned int *) or (volatile LONG *),
  1411. * so whatever you use, the other SDK is likely to raise a warning. */
  1412. ret = InterlockedIncrement((volatile long *)addr);
  1413. #elif defined(__GNUC__) \
  1414. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1415. ret = __sync_add_and_fetch(addr, 1);
  1416. #else
  1417. ret = (++(*addr));
  1418. #endif
  1419. return ret;
  1420. }
  1421. static int
  1422. mg_atomic_dec(volatile int *addr)
  1423. {
  1424. int ret;
  1425. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1426. /* Depending on the SDK, this function uses either
  1427. * (volatile unsigned int *) or (volatile LONG *),
  1428. * so whatever you use, the other SDK is likely to raise a warning. */
  1429. ret = InterlockedDecrement((volatile long *)addr);
  1430. #elif defined(__GNUC__) \
  1431. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1432. ret = __sync_sub_and_fetch(addr, 1);
  1433. #else
  1434. ret = (--(*addr));
  1435. #endif
  1436. return ret;
  1437. }
  1438. #if !defined(NO_THREAD_NAME)
  1439. #if defined(_WIN32) && defined(_MSC_VER)
  1440. /* Set the thread name for debugging purposes in Visual Studio
  1441. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1442. */
  1443. #pragma pack(push, 8)
  1444. typedef struct tagTHREADNAME_INFO {
  1445. DWORD dwType; /* Must be 0x1000. */
  1446. LPCSTR szName; /* Pointer to name (in user addr space). */
  1447. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1448. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1449. } THREADNAME_INFO;
  1450. #pragma pack(pop)
  1451. #elif defined(__linux__)
  1452. #include <sys/prctl.h>
  1453. #include <sys/sendfile.h>
  1454. #include <sys/eventfd.h>
  1455. #if defined(ALTERNATIVE_QUEUE)
  1456. static void *
  1457. event_create(void)
  1458. {
  1459. int ret = eventfd(0, EFD_CLOEXEC);
  1460. if (ret == -1) {
  1461. /* Linux uses -1 on error, Windows NULL. */
  1462. /* However, Linux does not return 0 on success either. */
  1463. return 0;
  1464. }
  1465. return (void *)ret;
  1466. }
  1467. static int
  1468. event_wait(void *eventhdl)
  1469. {
  1470. uint64_t u;
  1471. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1472. if (s != sizeof(uint64_t)) {
  1473. /* error */
  1474. return 0;
  1475. }
  1476. (void)u; /* the value is not required */
  1477. return 1;
  1478. }
  1479. static int
  1480. event_signal(void *eventhdl)
  1481. {
  1482. uint64_t u = 1;
  1483. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1484. if (s != sizeof(uint64_t)) {
  1485. /* error */
  1486. return 0;
  1487. }
  1488. return 1;
  1489. }
  1490. static void
  1491. event_destroy(void *eventhdl)
  1492. {
  1493. close((int)eventhdl);
  1494. }
  1495. #endif
  1496. #endif
  1497. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1498. struct posix_event {
  1499. pthread_mutex_t mutex;
  1500. pthread_cond_t cond;
  1501. };
  1502. static void *
  1503. event_create(void)
  1504. {
  1505. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1506. if (ret == 0) {
  1507. /* out of memory */
  1508. return 0;
  1509. }
  1510. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1511. /* pthread mutex not available */
  1512. mg_free(ret);
  1513. return 0;
  1514. }
  1515. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1516. /* pthread cond not available */
  1517. pthread_mutex_destroy(&(ret->mutex));
  1518. mg_free(ret);
  1519. return 0;
  1520. }
  1521. return (void *)ret;
  1522. }
  1523. static int
  1524. event_wait(void *eventhdl)
  1525. {
  1526. struct posix_event *ev = (struct posix_event *)eventhdl;
  1527. pthread_mutex_lock(&(ev->mutex));
  1528. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1529. pthread_mutex_unlock(&(ev->mutex));
  1530. return 1;
  1531. }
  1532. static int
  1533. event_signal(void *eventhdl)
  1534. {
  1535. struct posix_event *ev = (struct posix_event *)eventhdl;
  1536. pthread_mutex_lock(&(ev->mutex));
  1537. pthread_cond_signal(&(ev->cond));
  1538. pthread_mutex_unlock(&(ev->mutex));
  1539. return 1;
  1540. }
  1541. static void
  1542. event_destroy(void *eventhdl)
  1543. {
  1544. struct posix_event *ev = (struct posix_event *)eventhdl;
  1545. pthread_cond_destroy(&(ev->cond));
  1546. pthread_mutex_destroy(&(ev->mutex));
  1547. mg_free(ev);
  1548. }
  1549. #endif
  1550. static void
  1551. mg_set_thread_name(const char *name)
  1552. {
  1553. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1554. mg_snprintf(
  1555. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1556. #if defined(_WIN32)
  1557. #if defined(_MSC_VER)
  1558. /* Windows and Visual Studio Compiler */
  1559. __try
  1560. {
  1561. THREADNAME_INFO info;
  1562. info.dwType = 0x1000;
  1563. info.szName = threadName;
  1564. info.dwThreadID = ~0U;
  1565. info.dwFlags = 0;
  1566. RaiseException(0x406D1388,
  1567. 0,
  1568. sizeof(info) / sizeof(ULONG_PTR),
  1569. (ULONG_PTR *)&info);
  1570. }
  1571. __except(EXCEPTION_EXECUTE_HANDLER)
  1572. {
  1573. }
  1574. #elif defined(__MINGW32__)
  1575. /* No option known to set thread name for MinGW */
  1576. #endif
  1577. #elif defined(__GLIBC__) \
  1578. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1579. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1580. (void)pthread_setname_np(pthread_self(), threadName);
  1581. #elif defined(__linux__)
  1582. /* on linux we can use the old prctl function */
  1583. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1584. #endif
  1585. }
  1586. #else /* !defined(NO_THREAD_NAME) */
  1587. void
  1588. mg_set_thread_name(const char *threadName)
  1589. {
  1590. }
  1591. #endif
  1592. #if defined(MG_LEGACY_INTERFACE)
  1593. const char **
  1594. mg_get_valid_option_names(void)
  1595. {
  1596. /* This function is deprecated. Use mg_get_valid_options instead. */
  1597. static const char *
  1598. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1599. int i;
  1600. for (i = 0; config_options[i].name != NULL; i++) {
  1601. data[i * 2] = config_options[i].name;
  1602. data[i * 2 + 1] = config_options[i].default_value;
  1603. }
  1604. return data;
  1605. }
  1606. #endif
  1607. const struct mg_option *
  1608. mg_get_valid_options(void)
  1609. {
  1610. return config_options;
  1611. }
  1612. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1613. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1614. static int
  1615. open_file_in_memory(const struct mg_connection *conn,
  1616. const char *path,
  1617. struct mg_file *filep)
  1618. {
  1619. size_t size = 0;
  1620. const char *buf = NULL;
  1621. if (!conn) {
  1622. return 0;
  1623. }
  1624. if (conn->ctx->callbacks.open_file) {
  1625. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1626. if (buf != NULL) {
  1627. if (filep == NULL) {
  1628. /* This is a file in memory, but we cannot store the properties
  1629. * now.
  1630. * Called from "is_file_in_memory" function. */
  1631. return 1;
  1632. }
  1633. /* NOTE: override filep->size only on success. Otherwise, it might
  1634. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1635. filep->access.membuf = buf;
  1636. filep->access.fp = NULL;
  1637. /* Size was set by the callback */
  1638. filep->stat.size = size;
  1639. /* Assume the data may change during runtime by setting
  1640. * last_modified = now */
  1641. filep->stat.last_modified = time(NULL);
  1642. filep->stat.is_directory = 0;
  1643. filep->stat.is_gzipped = 0;
  1644. }
  1645. }
  1646. return (buf != NULL);
  1647. }
  1648. static int
  1649. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1650. {
  1651. return open_file_in_memory(conn, path, NULL);
  1652. }
  1653. static int
  1654. is_file_opened(const struct mg_file_access *fileacc)
  1655. {
  1656. if (!fileacc) {
  1657. return 0;
  1658. }
  1659. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1660. }
  1661. static int mg_stat(const struct mg_connection *conn,
  1662. const char *path,
  1663. struct mg_file_stat *filep);
  1664. /* mg_fopen will open a file either in memory or on the disk.
  1665. * The input parameter path is a string in UTF-8 encoding.
  1666. * The input parameter mode is the same as for fopen.
  1667. * Either fp or membuf will be set in the output struct file.
  1668. * The function returns 1 on success, 0 on error. */
  1669. static int
  1670. mg_fopen(const struct mg_connection *conn,
  1671. const char *path,
  1672. const char *mode,
  1673. struct mg_file *filep)
  1674. {
  1675. int found;
  1676. if (!filep) {
  1677. return 0;
  1678. }
  1679. if (!is_file_in_memory(conn, path)) {
  1680. /* filep is initialized in mg_stat: all fields with memset to,
  1681. * some fields like size and modification date with values */
  1682. found = mg_stat(conn, path, &(filep->stat));
  1683. /* TODO: if found=false, only call fopen if the file should
  1684. * be created. If it should only be read, fail early. */
  1685. #ifdef _WIN32
  1686. {
  1687. wchar_t wbuf[PATH_MAX], wmode[20];
  1688. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1689. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1690. filep->access.fp = _wfopen(wbuf, wmode);
  1691. }
  1692. #else
  1693. /* Linux et al already use unicode. No need to convert. */
  1694. filep->access.fp = fopen(path, mode);
  1695. #endif
  1696. if (!found) {
  1697. /* File did not exist before fopen was called.
  1698. * Maybe it has been created now. Get stat info
  1699. * like creation time now. */
  1700. found = mg_stat(conn, path, &(filep->stat));
  1701. (void)found;
  1702. }
  1703. /* file is on disk */
  1704. return (filep->access.fp != NULL);
  1705. } else {
  1706. if (open_file_in_memory(conn, path, filep)) {
  1707. /* file is in memory */
  1708. return (filep->access.membuf != NULL);
  1709. }
  1710. }
  1711. /* Open failed */
  1712. return 0;
  1713. }
  1714. /* return 0 on success, just like fclose */
  1715. static int
  1716. mg_fclose(struct mg_file_access *fileacc)
  1717. {
  1718. int ret = -1;
  1719. if (fileacc != NULL) {
  1720. if (fileacc->fp != NULL) {
  1721. ret = fclose(fileacc->fp);
  1722. } else if (fileacc->membuf != NULL) {
  1723. ret = 0;
  1724. }
  1725. /* reset all members of fileacc */
  1726. memset(fileacc, 0, sizeof(*fileacc));
  1727. }
  1728. return ret;
  1729. }
  1730. static void
  1731. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1732. {
  1733. for (; *src != '\0' && n > 1; n--) {
  1734. *dst++ = *src++;
  1735. }
  1736. *dst = '\0';
  1737. }
  1738. static int
  1739. lowercase(const char *s)
  1740. {
  1741. return tolower(*(const unsigned char *)s);
  1742. }
  1743. int
  1744. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1745. {
  1746. int diff = 0;
  1747. if (len > 0) {
  1748. do {
  1749. diff = lowercase(s1++) - lowercase(s2++);
  1750. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1751. }
  1752. return diff;
  1753. }
  1754. int
  1755. mg_strcasecmp(const char *s1, const char *s2)
  1756. {
  1757. int diff;
  1758. do {
  1759. diff = lowercase(s1++) - lowercase(s2++);
  1760. } while (diff == 0 && s1[-1] != '\0');
  1761. return diff;
  1762. }
  1763. static char *
  1764. mg_strndup(const char *ptr, size_t len)
  1765. {
  1766. char *p;
  1767. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1768. mg_strlcpy(p, ptr, len + 1);
  1769. }
  1770. return p;
  1771. }
  1772. static char *
  1773. mg_strdup(const char *str)
  1774. {
  1775. return mg_strndup(str, strlen(str));
  1776. }
  1777. static const char *
  1778. mg_strcasestr(const char *big_str, const char *small_str)
  1779. {
  1780. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1781. if (big_len >= small_len) {
  1782. for (i = 0; i <= (big_len - small_len); i++) {
  1783. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1784. return big_str + i;
  1785. }
  1786. }
  1787. }
  1788. return NULL;
  1789. }
  1790. /* Return null terminated string of given maximum length.
  1791. * Report errors if length is exceeded. */
  1792. static void
  1793. mg_vsnprintf(const struct mg_connection *conn,
  1794. int *truncated,
  1795. char *buf,
  1796. size_t buflen,
  1797. const char *fmt,
  1798. va_list ap)
  1799. {
  1800. int n, ok;
  1801. if (buflen == 0) {
  1802. return;
  1803. }
  1804. #ifdef __clang__
  1805. #pragma clang diagnostic push
  1806. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1807. /* Using fmt as a non-literal is intended here, since it is mostly called
  1808. * indirectly by mg_snprintf */
  1809. #endif
  1810. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1811. ok = (n >= 0) && ((size_t)n < buflen);
  1812. #ifdef __clang__
  1813. #pragma clang diagnostic pop
  1814. #endif
  1815. if (ok) {
  1816. if (truncated) {
  1817. *truncated = 0;
  1818. }
  1819. } else {
  1820. if (truncated) {
  1821. *truncated = 1;
  1822. }
  1823. mg_cry(conn,
  1824. "truncating vsnprintf buffer: [%.*s]",
  1825. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1826. buf);
  1827. n = (int)buflen - 1;
  1828. }
  1829. buf[n] = '\0';
  1830. }
  1831. static void
  1832. mg_snprintf(const struct mg_connection *conn,
  1833. int *truncated,
  1834. char *buf,
  1835. size_t buflen,
  1836. const char *fmt,
  1837. ...)
  1838. {
  1839. va_list ap;
  1840. va_start(ap, fmt);
  1841. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1842. va_end(ap);
  1843. }
  1844. static int
  1845. get_option_index(const char *name)
  1846. {
  1847. int i;
  1848. for (i = 0; config_options[i].name != NULL; i++) {
  1849. if (strcmp(config_options[i].name, name) == 0) {
  1850. return i;
  1851. }
  1852. }
  1853. return -1;
  1854. }
  1855. const char *
  1856. mg_get_option(const struct mg_context *ctx, const char *name)
  1857. {
  1858. int i;
  1859. if ((i = get_option_index(name)) == -1) {
  1860. return NULL;
  1861. } else if (!ctx || ctx->config[i] == NULL) {
  1862. return "";
  1863. } else {
  1864. return ctx->config[i];
  1865. }
  1866. }
  1867. struct mg_context *
  1868. mg_get_context(const struct mg_connection *conn)
  1869. {
  1870. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1871. }
  1872. void *
  1873. mg_get_user_data(const struct mg_context *ctx)
  1874. {
  1875. return (ctx == NULL) ? NULL : ctx->user_data;
  1876. }
  1877. void
  1878. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1879. {
  1880. if (conn != NULL) {
  1881. conn->request_info.conn_data = data;
  1882. }
  1883. }
  1884. void *
  1885. mg_get_user_connection_data(const struct mg_connection *conn)
  1886. {
  1887. if (conn != NULL) {
  1888. return conn->request_info.conn_data;
  1889. }
  1890. return NULL;
  1891. }
  1892. size_t
  1893. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1894. {
  1895. size_t i;
  1896. if (!ctx) {
  1897. return 0;
  1898. }
  1899. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1900. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1901. ports[i] =
  1902. #if defined(USE_IPV6)
  1903. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1904. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1905. :
  1906. #endif
  1907. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1908. }
  1909. return i;
  1910. }
  1911. int
  1912. mg_get_server_ports(const struct mg_context *ctx,
  1913. int size,
  1914. struct mg_server_ports *ports)
  1915. {
  1916. int i, cnt = 0;
  1917. if (size <= 0) {
  1918. return -1;
  1919. }
  1920. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1921. if (!ctx) {
  1922. return -1;
  1923. }
  1924. if (!ctx->listening_sockets) {
  1925. return -1;
  1926. }
  1927. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1928. ports[cnt].port =
  1929. #if defined(USE_IPV6)
  1930. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1931. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1932. :
  1933. #endif
  1934. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1935. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1936. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1937. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1938. /* IPv4 */
  1939. ports[cnt].protocol = 1;
  1940. cnt++;
  1941. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1942. /* IPv6 */
  1943. ports[cnt].protocol = 3;
  1944. cnt++;
  1945. }
  1946. }
  1947. return cnt;
  1948. }
  1949. static void
  1950. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1951. {
  1952. buf[0] = '\0';
  1953. if (!usa) {
  1954. return;
  1955. }
  1956. if (usa->sa.sa_family == AF_INET) {
  1957. getnameinfo(&usa->sa,
  1958. sizeof(usa->sin),
  1959. buf,
  1960. (unsigned)len,
  1961. NULL,
  1962. 0,
  1963. NI_NUMERICHOST);
  1964. }
  1965. #if defined(USE_IPV6)
  1966. else if (usa->sa.sa_family == AF_INET6) {
  1967. getnameinfo(&usa->sa,
  1968. sizeof(usa->sin6),
  1969. buf,
  1970. (unsigned)len,
  1971. NULL,
  1972. 0,
  1973. NI_NUMERICHOST);
  1974. }
  1975. #endif
  1976. }
  1977. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1978. * included in all responses other than 100, 101, 5xx. */
  1979. static void
  1980. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1981. {
  1982. struct tm *tm;
  1983. tm = ((t != NULL) ? gmtime(t) : NULL);
  1984. if (tm != NULL) {
  1985. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1986. } else {
  1987. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1988. buf[buf_len - 1] = '\0';
  1989. }
  1990. }
  1991. /* difftime for struct timespec. Return value is in seconds. */
  1992. static double
  1993. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1994. {
  1995. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1996. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1997. }
  1998. /* Print error message to the opened error log stream. */
  1999. void
  2000. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2001. {
  2002. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2003. va_list ap;
  2004. struct mg_file fi;
  2005. time_t timestamp;
  2006. va_start(ap, fmt);
  2007. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2008. va_end(ap);
  2009. buf[sizeof(buf) - 1] = 0;
  2010. if (!conn) {
  2011. puts(buf);
  2012. return;
  2013. }
  2014. /* Do not lock when getting the callback value, here and below.
  2015. * I suppose this is fine, since function cannot disappear in the
  2016. * same way string option can. */
  2017. if ((conn->ctx->callbacks.log_message == NULL)
  2018. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2019. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2020. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  2021. == 0) {
  2022. fi.access.fp = NULL;
  2023. }
  2024. } else {
  2025. fi.access.fp = NULL;
  2026. }
  2027. if (fi.access.fp != NULL) {
  2028. flockfile(fi.access.fp);
  2029. timestamp = time(NULL);
  2030. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2031. fprintf(fi.access.fp,
  2032. "[%010lu] [error] [client %s] ",
  2033. (unsigned long)timestamp,
  2034. src_addr);
  2035. if (conn->request_info.request_method != NULL) {
  2036. fprintf(fi.access.fp,
  2037. "%s %s: ",
  2038. conn->request_info.request_method,
  2039. conn->request_info.request_uri);
  2040. }
  2041. fprintf(fi.access.fp, "%s", buf);
  2042. fputc('\n', fi.access.fp);
  2043. fflush(fi.access.fp);
  2044. funlockfile(fi.access.fp);
  2045. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2046. * mg_cry here anyway ;-) */
  2047. }
  2048. }
  2049. }
  2050. /* Return fake connection structure. Used for logging, if connection
  2051. * is not applicable at the moment of logging. */
  2052. static struct mg_connection *
  2053. fc(struct mg_context *ctx)
  2054. {
  2055. static struct mg_connection fake_connection;
  2056. fake_connection.ctx = ctx;
  2057. return &fake_connection;
  2058. }
  2059. const char *
  2060. mg_version(void)
  2061. {
  2062. return CIVETWEB_VERSION;
  2063. }
  2064. const struct mg_request_info *
  2065. mg_get_request_info(const struct mg_connection *conn)
  2066. {
  2067. if (!conn) {
  2068. return NULL;
  2069. }
  2070. return &conn->request_info;
  2071. }
  2072. /* Skip the characters until one of the delimiters characters found.
  2073. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2074. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2075. * Delimiters can be quoted with quotechar. */
  2076. static char *
  2077. skip_quoted(char **buf,
  2078. const char *delimiters,
  2079. const char *whitespace,
  2080. char quotechar)
  2081. {
  2082. char *p, *begin_word, *end_word, *end_whitespace;
  2083. begin_word = *buf;
  2084. end_word = begin_word + strcspn(begin_word, delimiters);
  2085. /* Check for quotechar */
  2086. if (end_word > begin_word) {
  2087. p = end_word - 1;
  2088. while (*p == quotechar) {
  2089. /* While the delimiter is quoted, look for the next delimiter. */
  2090. /* This happens, e.g., in calls from parse_auth_header,
  2091. * if the user name contains a " character. */
  2092. /* If there is anything beyond end_word, copy it. */
  2093. if (*end_word != '\0') {
  2094. size_t end_off = strcspn(end_word + 1, delimiters);
  2095. memmove(p, end_word, end_off + 1);
  2096. p += end_off; /* p must correspond to end_word - 1 */
  2097. end_word += end_off + 1;
  2098. } else {
  2099. *p = '\0';
  2100. break;
  2101. }
  2102. }
  2103. for (p++; p < end_word; p++) {
  2104. *p = '\0';
  2105. }
  2106. }
  2107. if (*end_word == '\0') {
  2108. *buf = end_word;
  2109. } else {
  2110. #if defined(__GNUC__) || defined(__MINGW32__)
  2111. /* Disable spurious conversion warning for GCC */
  2112. #pragma GCC diagnostic push
  2113. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2114. #endif
  2115. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2116. #if defined(__GNUC__) || defined(__MINGW32__)
  2117. #pragma GCC diagnostic pop
  2118. #endif
  2119. for (p = end_word; p < end_whitespace; p++) {
  2120. *p = '\0';
  2121. }
  2122. *buf = end_whitespace;
  2123. }
  2124. return begin_word;
  2125. }
  2126. /* Simplified version of skip_quoted without quote char
  2127. * and whitespace == delimiters */
  2128. static char *
  2129. skip(char **buf, const char *delimiters)
  2130. {
  2131. return skip_quoted(buf, delimiters, delimiters, 0);
  2132. }
  2133. /* Return HTTP header value, or NULL if not found. */
  2134. static const char *
  2135. get_header(const struct mg_request_info *ri, const char *name)
  2136. {
  2137. int i;
  2138. if (ri) {
  2139. for (i = 0; i < ri->num_headers; i++) {
  2140. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2141. return ri->http_headers[i].value;
  2142. }
  2143. }
  2144. }
  2145. return NULL;
  2146. }
  2147. const char *
  2148. mg_get_header(const struct mg_connection *conn, const char *name)
  2149. {
  2150. if (!conn) {
  2151. return NULL;
  2152. }
  2153. return get_header(&conn->request_info, name);
  2154. }
  2155. /* A helper function for traversing a comma separated list of values.
  2156. * It returns a list pointer shifted to the next value, or NULL if the end
  2157. * of the list found.
  2158. * Value is stored in val vector. If value has form "x=y", then eq_val
  2159. * vector is initialized to point to the "y" part, and val vector length
  2160. * is adjusted to point only to "x". */
  2161. static const char *
  2162. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2163. {
  2164. int end;
  2165. reparse:
  2166. if (val == NULL || list == NULL || *list == '\0') {
  2167. /* End of the list */
  2168. list = NULL;
  2169. } else {
  2170. /* Skip over leading LWS */
  2171. while (*list == ' ' || *list == '\t')
  2172. list++;
  2173. val->ptr = list;
  2174. if ((list = strchr(val->ptr, ',')) != NULL) {
  2175. /* Comma found. Store length and shift the list ptr */
  2176. val->len = ((size_t)(list - val->ptr));
  2177. list++;
  2178. } else {
  2179. /* This value is the last one */
  2180. list = val->ptr + strlen(val->ptr);
  2181. val->len = ((size_t)(list - val->ptr));
  2182. }
  2183. /* Adjust length for trailing LWS */
  2184. end = (int)val->len - 1;
  2185. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2186. end--;
  2187. val->len = (size_t)(end + 1);
  2188. if (val->len == 0) {
  2189. /* Ignore any empty entries. */
  2190. goto reparse;
  2191. }
  2192. if (eq_val != NULL) {
  2193. /* Value has form "x=y", adjust pointers and lengths
  2194. * so that val points to "x", and eq_val points to "y". */
  2195. eq_val->len = 0;
  2196. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2197. if (eq_val->ptr != NULL) {
  2198. eq_val->ptr++; /* Skip over '=' character */
  2199. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2200. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2201. }
  2202. }
  2203. }
  2204. return list;
  2205. }
  2206. /* A helper function for checking if a comma separated list of values contains
  2207. * the given option (case insensitvely).
  2208. * 'header' can be NULL, in which case false is returned. */
  2209. static int
  2210. header_has_option(const char *header, const char *option)
  2211. {
  2212. struct vec opt_vec;
  2213. struct vec eq_vec;
  2214. assert(option != NULL);
  2215. assert(option[0] != '\0');
  2216. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2217. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2218. return 1;
  2219. }
  2220. return 0;
  2221. }
  2222. /* Perform case-insensitive match of string against pattern */
  2223. static int
  2224. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2225. {
  2226. const char *or_str;
  2227. size_t i;
  2228. int j, len, res;
  2229. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2230. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2231. return (res > 0) ? res : match_prefix(or_str + 1,
  2232. (size_t)((pattern + pattern_len)
  2233. - (or_str + 1)),
  2234. str);
  2235. }
  2236. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2237. if (pattern[i] == '?' && str[j] != '\0') {
  2238. continue;
  2239. } else if (pattern[i] == '$') {
  2240. return (str[j] == '\0') ? j : -1;
  2241. } else if (pattern[i] == '*') {
  2242. i++;
  2243. if (pattern[i] == '*') {
  2244. i++;
  2245. len = (int)strlen(str + j);
  2246. } else {
  2247. len = (int)strcspn(str + j, "/");
  2248. }
  2249. if (i == pattern_len) {
  2250. return j + len;
  2251. }
  2252. do {
  2253. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2254. } while (res == -1 && len-- > 0);
  2255. return (res == -1) ? -1 : j + res + len;
  2256. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2257. return -1;
  2258. }
  2259. }
  2260. return j;
  2261. }
  2262. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2263. * This function must tolerate situations when connection info is not
  2264. * set up, for example if request parsing failed. */
  2265. static int
  2266. should_keep_alive(const struct mg_connection *conn)
  2267. {
  2268. if (conn != NULL) {
  2269. const char *http_version = conn->request_info.http_version;
  2270. const char *header = mg_get_header(conn, "Connection");
  2271. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2272. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2273. || (header != NULL && !header_has_option(header, "keep-alive"))
  2274. || (header == NULL && http_version
  2275. && 0 != strcmp(http_version, "1.1"))) {
  2276. return 0;
  2277. }
  2278. return 1;
  2279. }
  2280. return 0;
  2281. }
  2282. static int
  2283. should_decode_url(const struct mg_connection *conn)
  2284. {
  2285. if (!conn || !conn->ctx) {
  2286. return 0;
  2287. }
  2288. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2289. }
  2290. static const char *
  2291. suggest_connection_header(const struct mg_connection *conn)
  2292. {
  2293. return should_keep_alive(conn) ? "keep-alive" : "close";
  2294. }
  2295. static int
  2296. send_no_cache_header(struct mg_connection *conn)
  2297. {
  2298. /* Send all current and obsolete cache opt-out directives. */
  2299. return mg_printf(conn,
  2300. "Cache-Control: no-cache, no-store, "
  2301. "must-revalidate, private, max-age=0\r\n"
  2302. "Pragma: no-cache\r\n"
  2303. "Expires: 0\r\n");
  2304. }
  2305. static int
  2306. send_static_cache_header(struct mg_connection *conn)
  2307. {
  2308. #if !defined(NO_CACHING)
  2309. /* Read the server config to check how long a file may be cached.
  2310. * The configuration is in seconds. */
  2311. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2312. if (max_age <= 0) {
  2313. /* 0 means "do not cache". All values <0 are reserved
  2314. * and may be used differently in the future. */
  2315. /* If a file should not be cached, do not only send
  2316. * max-age=0, but also pragmas and Expires headers. */
  2317. return send_no_cache_header(conn);
  2318. }
  2319. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2320. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2321. /* See also https://www.mnot.net/cache_docs/ */
  2322. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2323. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2324. * year to 31622400 seconds. For the moment, we just send whatever has
  2325. * been configured, still the behavior for >1 year should be considered
  2326. * as undefined. */
  2327. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2328. #else /* NO_CACHING */
  2329. return send_no_cache_header(conn);
  2330. #endif /* !NO_CACHING */
  2331. }
  2332. static void handle_file_based_request(struct mg_connection *conn,
  2333. const char *path,
  2334. struct mg_file *filep);
  2335. const char *
  2336. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2337. {
  2338. /* See IANA HTTP status code assignment:
  2339. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2340. */
  2341. switch (response_code) {
  2342. /* RFC2616 Section 10.1 - Informational 1xx */
  2343. case 100:
  2344. return "Continue"; /* RFC2616 Section 10.1.1 */
  2345. case 101:
  2346. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2347. case 102:
  2348. return "Processing"; /* RFC2518 Section 10.1 */
  2349. /* RFC2616 Section 10.2 - Successful 2xx */
  2350. case 200:
  2351. return "OK"; /* RFC2616 Section 10.2.1 */
  2352. case 201:
  2353. return "Created"; /* RFC2616 Section 10.2.2 */
  2354. case 202:
  2355. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2356. case 203:
  2357. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2358. case 204:
  2359. return "No Content"; /* RFC2616 Section 10.2.5 */
  2360. case 205:
  2361. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2362. case 206:
  2363. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2364. case 207:
  2365. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2366. case 208:
  2367. return "Already Reported"; /* RFC5842 Section 7.1 */
  2368. case 226:
  2369. return "IM used"; /* RFC3229 Section 10.4.1 */
  2370. /* RFC2616 Section 10.3 - Redirection 3xx */
  2371. case 300:
  2372. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2373. case 301:
  2374. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2375. case 302:
  2376. return "Found"; /* RFC2616 Section 10.3.3 */
  2377. case 303:
  2378. return "See Other"; /* RFC2616 Section 10.3.4 */
  2379. case 304:
  2380. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2381. case 305:
  2382. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2383. case 307:
  2384. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2385. case 308:
  2386. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2387. /* RFC2616 Section 10.4 - Client Error 4xx */
  2388. case 400:
  2389. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2390. case 401:
  2391. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2392. case 402:
  2393. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2394. case 403:
  2395. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2396. case 404:
  2397. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2398. case 405:
  2399. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2400. case 406:
  2401. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2402. case 407:
  2403. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2404. case 408:
  2405. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2406. case 409:
  2407. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2408. case 410:
  2409. return "Gone"; /* RFC2616 Section 10.4.11 */
  2410. case 411:
  2411. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2412. case 412:
  2413. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2414. case 413:
  2415. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2416. case 414:
  2417. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2418. case 415:
  2419. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2420. case 416:
  2421. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2422. case 417:
  2423. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2424. case 421:
  2425. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2426. case 422:
  2427. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2428. * Section 11.2 */
  2429. case 423:
  2430. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2431. case 424:
  2432. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2433. * Section 11.4 */
  2434. case 426:
  2435. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2436. case 428:
  2437. return "Precondition Required"; /* RFC 6585, Section 3 */
  2438. case 429:
  2439. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2440. case 431:
  2441. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2442. case 451:
  2443. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2444. * Section 3 */
  2445. /* RFC2616 Section 10.5 - Server Error 5xx */
  2446. case 500:
  2447. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2448. case 501:
  2449. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2450. case 502:
  2451. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2452. case 503:
  2453. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2454. case 504:
  2455. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2456. case 505:
  2457. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2458. case 506:
  2459. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2460. case 507:
  2461. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2462. * Section 11.5 */
  2463. case 508:
  2464. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2465. case 510:
  2466. return "Not Extended"; /* RFC 2774, Section 7 */
  2467. case 511:
  2468. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2469. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2470. * E.g., "de facto" standards due to common use, ... */
  2471. case 418:
  2472. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2473. case 419:
  2474. return "Authentication Timeout"; /* common use */
  2475. case 420:
  2476. return "Enhance Your Calm"; /* common use */
  2477. case 440:
  2478. return "Login Timeout"; /* common use */
  2479. case 509:
  2480. return "Bandwidth Limit Exceeded"; /* common use */
  2481. default:
  2482. /* This error code is unknown. This should not happen. */
  2483. if (conn) {
  2484. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2485. }
  2486. /* Return at least a category according to RFC 2616 Section 10. */
  2487. if (response_code >= 100 && response_code < 200) {
  2488. /* Unknown informational status code */
  2489. return "Information";
  2490. }
  2491. if (response_code >= 200 && response_code < 300) {
  2492. /* Unknown success code */
  2493. return "Success";
  2494. }
  2495. if (response_code >= 300 && response_code < 400) {
  2496. /* Unknown redirection code */
  2497. return "Redirection";
  2498. }
  2499. if (response_code >= 400 && response_code < 500) {
  2500. /* Unknown request error code */
  2501. return "Client Error";
  2502. }
  2503. if (response_code >= 500 && response_code < 600) {
  2504. /* Unknown server error code */
  2505. return "Server Error";
  2506. }
  2507. /* Response code not even within reasonable range */
  2508. return "";
  2509. }
  2510. }
  2511. static void send_http_error(struct mg_connection *,
  2512. int,
  2513. PRINTF_FORMAT_STRING(const char *fmt),
  2514. ...) PRINTF_ARGS(3, 4);
  2515. static void
  2516. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2517. {
  2518. char buf[MG_BUF_LEN];
  2519. va_list ap;
  2520. int len, i, page_handler_found, scope, truncated, has_body;
  2521. char date[64];
  2522. time_t curtime = time(NULL);
  2523. const char *error_handler = NULL;
  2524. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2525. const char *error_page_file_ext, *tstr;
  2526. const char *status_text = mg_get_response_code_text(conn, status);
  2527. if (conn == NULL) {
  2528. return;
  2529. }
  2530. conn->status_code = status;
  2531. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2532. || conn->ctx->callbacks.http_error(conn, status)) {
  2533. if (!conn->in_error_handler) {
  2534. /* Send user defined error pages, if defined */
  2535. error_handler = conn->ctx->config[ERROR_PAGES];
  2536. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2537. page_handler_found = 0;
  2538. if (error_handler != NULL) {
  2539. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2540. switch (scope) {
  2541. case 1: /* Handler for specific error, e.g. 404 error */
  2542. mg_snprintf(conn,
  2543. &truncated,
  2544. buf,
  2545. sizeof(buf) - 32,
  2546. "%serror%03u.",
  2547. error_handler,
  2548. status);
  2549. break;
  2550. case 2: /* Handler for error group, e.g., 5xx error handler
  2551. * for all server errors (500-599) */
  2552. mg_snprintf(conn,
  2553. &truncated,
  2554. buf,
  2555. sizeof(buf) - 32,
  2556. "%serror%01uxx.",
  2557. error_handler,
  2558. status / 100);
  2559. break;
  2560. default: /* Handler for all errors */
  2561. mg_snprintf(conn,
  2562. &truncated,
  2563. buf,
  2564. sizeof(buf) - 32,
  2565. "%serror.",
  2566. error_handler);
  2567. break;
  2568. }
  2569. /* String truncation in buf may only occur if error_handler
  2570. * is too long. This string is from the config, not from a
  2571. * client. */
  2572. (void)truncated;
  2573. len = (int)strlen(buf);
  2574. tstr = strchr(error_page_file_ext, '.');
  2575. while (tstr) {
  2576. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2577. i++)
  2578. buf[len + i - 1] = tstr[i];
  2579. buf[len + i - 1] = 0;
  2580. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2581. page_handler_found = 1;
  2582. break;
  2583. }
  2584. tstr = strchr(tstr + i, '.');
  2585. }
  2586. }
  2587. }
  2588. if (page_handler_found) {
  2589. conn->in_error_handler = 1;
  2590. handle_file_based_request(conn, buf, &error_page_file);
  2591. conn->in_error_handler = 0;
  2592. return;
  2593. }
  2594. }
  2595. /* No custom error page. Send default error page. */
  2596. gmt_time_string(date, sizeof(date), &curtime);
  2597. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2598. has_body = (status > 199 && status != 204 && status != 304);
  2599. conn->must_close = 1;
  2600. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2601. send_no_cache_header(conn);
  2602. if (has_body) {
  2603. mg_printf(conn,
  2604. "%s",
  2605. "Content-Type: text/plain; charset=utf-8\r\n");
  2606. }
  2607. mg_printf(conn,
  2608. "Date: %s\r\n"
  2609. "Connection: close\r\n\r\n",
  2610. date);
  2611. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2612. if (has_body) {
  2613. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2614. if (fmt != NULL) {
  2615. va_start(ap, fmt);
  2616. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2617. va_end(ap);
  2618. mg_write(conn, buf, strlen(buf));
  2619. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2620. }
  2621. } else {
  2622. /* No body allowed. Close the connection. */
  2623. DEBUG_TRACE("Error %i", status);
  2624. }
  2625. }
  2626. }
  2627. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2628. /* Create substitutes for POSIX functions in Win32. */
  2629. #if defined(__MINGW32__)
  2630. /* Show no warning in case system functions are not used. */
  2631. #pragma GCC diagnostic push
  2632. #pragma GCC diagnostic ignored "-Wunused-function"
  2633. #endif
  2634. static int
  2635. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2636. {
  2637. (void)unused;
  2638. *mutex = CreateMutex(NULL, FALSE, NULL);
  2639. return (*mutex == NULL) ? -1 : 0;
  2640. }
  2641. static int
  2642. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2643. {
  2644. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2645. }
  2646. static int
  2647. pthread_mutex_lock(pthread_mutex_t *mutex)
  2648. {
  2649. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2650. }
  2651. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2652. static int
  2653. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2654. {
  2655. switch (WaitForSingleObject(*mutex, 0)) {
  2656. case WAIT_OBJECT_0:
  2657. return 0;
  2658. case WAIT_TIMEOUT:
  2659. return -2; /* EBUSY */
  2660. }
  2661. return -1;
  2662. }
  2663. #endif
  2664. static int
  2665. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2666. {
  2667. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2668. }
  2669. #ifndef WIN_PTHREADS_TIME_H
  2670. static int
  2671. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2672. {
  2673. FILETIME ft;
  2674. ULARGE_INTEGER li;
  2675. BOOL ok = FALSE;
  2676. double d;
  2677. static double perfcnt_per_sec = 0.0;
  2678. if (tp) {
  2679. memset(tp, 0, sizeof(*tp));
  2680. if (clk_id == CLOCK_REALTIME) {
  2681. GetSystemTimeAsFileTime(&ft);
  2682. li.LowPart = ft.dwLowDateTime;
  2683. li.HighPart = ft.dwHighDateTime;
  2684. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2685. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2686. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2687. ok = TRUE;
  2688. } else if (clk_id == CLOCK_MONOTONIC) {
  2689. if (perfcnt_per_sec == 0.0) {
  2690. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2691. perfcnt_per_sec = 1.0 / li.QuadPart;
  2692. }
  2693. if (perfcnt_per_sec != 0.0) {
  2694. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2695. d = li.QuadPart * perfcnt_per_sec;
  2696. tp->tv_sec = (time_t)d;
  2697. d -= tp->tv_sec;
  2698. tp->tv_nsec = (long)(d * 1.0E9);
  2699. ok = TRUE;
  2700. }
  2701. }
  2702. }
  2703. return ok ? 0 : -1;
  2704. }
  2705. #endif
  2706. static int
  2707. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2708. {
  2709. (void)unused;
  2710. InitializeCriticalSection(&cv->threadIdSec);
  2711. cv->waiting_thread = NULL;
  2712. return 0;
  2713. }
  2714. static int
  2715. pthread_cond_timedwait(pthread_cond_t *cv,
  2716. pthread_mutex_t *mutex,
  2717. const struct timespec *abstime)
  2718. {
  2719. struct mg_workerTLS **ptls,
  2720. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2721. int ok;
  2722. struct timespec tsnow;
  2723. int64_t nsnow, nswaitabs, nswaitrel;
  2724. DWORD mswaitrel;
  2725. EnterCriticalSection(&cv->threadIdSec);
  2726. /* Add this thread to cv's waiting list */
  2727. ptls = &cv->waiting_thread;
  2728. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2729. ;
  2730. tls->next_waiting_thread = NULL;
  2731. *ptls = tls;
  2732. LeaveCriticalSection(&cv->threadIdSec);
  2733. if (abstime) {
  2734. clock_gettime(CLOCK_REALTIME, &tsnow);
  2735. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2736. nswaitabs =
  2737. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2738. nswaitrel = nswaitabs - nsnow;
  2739. if (nswaitrel < 0) {
  2740. nswaitrel = 0;
  2741. }
  2742. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2743. } else {
  2744. mswaitrel = INFINITE;
  2745. }
  2746. pthread_mutex_unlock(mutex);
  2747. ok = (WAIT_OBJECT_0
  2748. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2749. if (!ok) {
  2750. ok = 1;
  2751. EnterCriticalSection(&cv->threadIdSec);
  2752. ptls = &cv->waiting_thread;
  2753. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2754. if (*ptls == tls) {
  2755. *ptls = tls->next_waiting_thread;
  2756. ok = 0;
  2757. break;
  2758. }
  2759. }
  2760. LeaveCriticalSection(&cv->threadIdSec);
  2761. if (ok) {
  2762. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2763. }
  2764. }
  2765. /* This thread has been removed from cv's waiting list */
  2766. pthread_mutex_lock(mutex);
  2767. return ok ? 0 : -1;
  2768. }
  2769. static int
  2770. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2771. {
  2772. return pthread_cond_timedwait(cv, mutex, NULL);
  2773. }
  2774. static int
  2775. pthread_cond_signal(pthread_cond_t *cv)
  2776. {
  2777. HANDLE wkup = NULL;
  2778. BOOL ok = FALSE;
  2779. EnterCriticalSection(&cv->threadIdSec);
  2780. if (cv->waiting_thread) {
  2781. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2782. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2783. ok = SetEvent(wkup);
  2784. assert(ok);
  2785. }
  2786. LeaveCriticalSection(&cv->threadIdSec);
  2787. return ok ? 0 : 1;
  2788. }
  2789. static int
  2790. pthread_cond_broadcast(pthread_cond_t *cv)
  2791. {
  2792. EnterCriticalSection(&cv->threadIdSec);
  2793. while (cv->waiting_thread) {
  2794. pthread_cond_signal(cv);
  2795. }
  2796. LeaveCriticalSection(&cv->threadIdSec);
  2797. return 0;
  2798. }
  2799. static int
  2800. pthread_cond_destroy(pthread_cond_t *cv)
  2801. {
  2802. EnterCriticalSection(&cv->threadIdSec);
  2803. assert(cv->waiting_thread == NULL);
  2804. LeaveCriticalSection(&cv->threadIdSec);
  2805. DeleteCriticalSection(&cv->threadIdSec);
  2806. return 0;
  2807. }
  2808. #ifdef ALTERNATIVE_QUEUE
  2809. static void *
  2810. event_create(void)
  2811. {
  2812. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2813. }
  2814. static int
  2815. event_wait(void *eventhdl)
  2816. {
  2817. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2818. return (res == WAIT_OBJECT_0);
  2819. }
  2820. static int
  2821. event_signal(void *eventhdl)
  2822. {
  2823. return (int)SetEvent((HANDLE)eventhdl);
  2824. }
  2825. static void
  2826. event_destroy(void *eventhdl)
  2827. {
  2828. CloseHandle((HANDLE)eventhdl);
  2829. }
  2830. #endif
  2831. #if defined(__MINGW32__)
  2832. /* Enable unused function warning again */
  2833. #pragma GCC diagnostic pop
  2834. #endif
  2835. /* For Windows, change all slashes to backslashes in path names. */
  2836. static void
  2837. change_slashes_to_backslashes(char *path)
  2838. {
  2839. int i;
  2840. for (i = 0; path[i] != '\0'; i++) {
  2841. if (path[i] == '/') {
  2842. path[i] = '\\';
  2843. }
  2844. /* remove double backslash (check i > 0 to preserve UNC paths,
  2845. * like \\server\file.txt) */
  2846. if ((path[i] == '\\') && (i > 0)) {
  2847. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2848. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2849. }
  2850. }
  2851. }
  2852. }
  2853. static int
  2854. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2855. {
  2856. int diff;
  2857. do {
  2858. diff = tolower(*s1) - tolower(*s2);
  2859. s1++;
  2860. s2++;
  2861. } while (diff == 0 && s1[-1] != '\0');
  2862. return diff;
  2863. }
  2864. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2865. * wbuf and wbuf_len is a target buffer and its length. */
  2866. static void
  2867. path_to_unicode(const struct mg_connection *conn,
  2868. const char *path,
  2869. wchar_t *wbuf,
  2870. size_t wbuf_len)
  2871. {
  2872. char buf[PATH_MAX], buf2[PATH_MAX];
  2873. wchar_t wbuf2[MAX_PATH + 1];
  2874. DWORD long_len, err;
  2875. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2876. mg_strlcpy(buf, path, sizeof(buf));
  2877. change_slashes_to_backslashes(buf);
  2878. /* Convert to Unicode and back. If doubly-converted string does not
  2879. * match the original, something is fishy, reject. */
  2880. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2881. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2882. WideCharToMultiByte(
  2883. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2884. if (strcmp(buf, buf2) != 0) {
  2885. wbuf[0] = L'\0';
  2886. }
  2887. /* Windows file systems are not case sensitive, but you can still use
  2888. * uppercase and lowercase letters (on all modern file systems).
  2889. * The server can check if the URI uses the same upper/lowercase
  2890. * letters an the file system, effectively making Windows servers
  2891. * case sensitive (like Linux servers are). It is still not possible
  2892. * to use two files with the same name in different cases on Windows
  2893. * (like /a and /A) - this would be possible in Linux.
  2894. * As a default, Windows is not case sensitive, but the case sensitive
  2895. * file name check can be activated by an additional configuration. */
  2896. if (conn) {
  2897. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  2898. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  2899. /* Use case sensitive compare function */
  2900. fcompare = wcscmp;
  2901. }
  2902. }
  2903. (void)conn; /* conn is currently unused */
  2904. #if !defined(_WIN32_WCE)
  2905. /* Only accept a full file path, not a Windows short (8.3) path. */
  2906. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2907. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2908. if (long_len == 0) {
  2909. err = GetLastError();
  2910. if (err == ERROR_FILE_NOT_FOUND) {
  2911. /* File does not exist. This is not always a problem here. */
  2912. return;
  2913. }
  2914. }
  2915. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2916. /* Short name is used. */
  2917. wbuf[0] = L'\0';
  2918. }
  2919. #else
  2920. (void)long_len;
  2921. (void)wbuf2;
  2922. (void)err;
  2923. if (strchr(path, '~')) {
  2924. wbuf[0] = L'\0';
  2925. }
  2926. #endif
  2927. }
  2928. /* Windows happily opens files with some garbage at the end of file name.
  2929. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2930. * "a.cgi", despite one would expect an error back.
  2931. * This function returns non-0 if path ends with some garbage. */
  2932. static int
  2933. path_cannot_disclose_cgi(const char *path)
  2934. {
  2935. static const char *allowed_last_characters = "_-";
  2936. int last = path[strlen(path) - 1];
  2937. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2938. }
  2939. static int
  2940. mg_stat(const struct mg_connection *conn,
  2941. const char *path,
  2942. struct mg_file_stat *filep)
  2943. {
  2944. wchar_t wbuf[PATH_MAX];
  2945. WIN32_FILE_ATTRIBUTE_DATA info;
  2946. time_t creation_time;
  2947. if (!filep) {
  2948. return 0;
  2949. }
  2950. memset(filep, 0, sizeof(*filep));
  2951. if (conn && is_file_in_memory(conn, path)) {
  2952. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2953. * memset */
  2954. filep->last_modified = time(NULL); /* xxxxxxxx */
  2955. /* last_modified = now ... assumes the file may change during runtime,
  2956. * so every mg_fopen call may return different data */
  2957. /* last_modified = conn->ctx.start_time;
  2958. * May be used it the data does not change during runtime. This allows
  2959. * browser caching. Since we do not know, we have to assume the file
  2960. * in memory may change. */
  2961. return 1;
  2962. }
  2963. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2964. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2965. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2966. filep->last_modified =
  2967. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2968. info.ftLastWriteTime.dwHighDateTime);
  2969. /* On Windows, the file creation time can be higher than the
  2970. * modification time, e.g. when a file is copied.
  2971. * Since the Last-Modified timestamp is used for caching
  2972. * it should be based on the most recent timestamp. */
  2973. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2974. info.ftCreationTime.dwHighDateTime);
  2975. if (creation_time > filep->last_modified) {
  2976. filep->last_modified = creation_time;
  2977. }
  2978. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2979. /* If file name is fishy, reset the file structure and return
  2980. * error.
  2981. * Note it is important to reset, not just return the error, cause
  2982. * functions like is_file_opened() check the struct. */
  2983. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2984. memset(filep, 0, sizeof(*filep));
  2985. return 0;
  2986. }
  2987. return 1;
  2988. }
  2989. return 0;
  2990. }
  2991. static int
  2992. mg_remove(const struct mg_connection *conn, const char *path)
  2993. {
  2994. wchar_t wbuf[PATH_MAX];
  2995. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2996. return DeleteFileW(wbuf) ? 0 : -1;
  2997. }
  2998. static int
  2999. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3000. {
  3001. wchar_t wbuf[PATH_MAX];
  3002. (void)mode;
  3003. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3004. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3005. }
  3006. /* Create substitutes for POSIX functions in Win32. */
  3007. #if defined(__MINGW32__)
  3008. /* Show no warning in case system functions are not used. */
  3009. #pragma GCC diagnostic push
  3010. #pragma GCC diagnostic ignored "-Wunused-function"
  3011. #endif
  3012. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3013. static DIR *
  3014. mg_opendir(const struct mg_connection *conn, const char *name)
  3015. {
  3016. DIR *dir = NULL;
  3017. wchar_t wpath[PATH_MAX];
  3018. DWORD attrs;
  3019. if (name == NULL) {
  3020. SetLastError(ERROR_BAD_ARGUMENTS);
  3021. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3022. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3023. } else {
  3024. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3025. attrs = GetFileAttributesW(wpath);
  3026. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3027. == FILE_ATTRIBUTE_DIRECTORY)) {
  3028. (void)wcscat(wpath, L"\\*");
  3029. dir->handle = FindFirstFileW(wpath, &dir->info);
  3030. dir->result.d_name[0] = '\0';
  3031. } else {
  3032. mg_free(dir);
  3033. dir = NULL;
  3034. }
  3035. }
  3036. return dir;
  3037. }
  3038. static int
  3039. mg_closedir(DIR *dir)
  3040. {
  3041. int result = 0;
  3042. if (dir != NULL) {
  3043. if (dir->handle != INVALID_HANDLE_VALUE)
  3044. result = FindClose(dir->handle) ? 0 : -1;
  3045. mg_free(dir);
  3046. } else {
  3047. result = -1;
  3048. SetLastError(ERROR_BAD_ARGUMENTS);
  3049. }
  3050. return result;
  3051. }
  3052. static struct dirent *
  3053. mg_readdir(DIR *dir)
  3054. {
  3055. struct dirent *result = 0;
  3056. if (dir) {
  3057. if (dir->handle != INVALID_HANDLE_VALUE) {
  3058. result = &dir->result;
  3059. (void)WideCharToMultiByte(CP_UTF8,
  3060. 0,
  3061. dir->info.cFileName,
  3062. -1,
  3063. result->d_name,
  3064. sizeof(result->d_name),
  3065. NULL,
  3066. NULL);
  3067. if (!FindNextFileW(dir->handle, &dir->info)) {
  3068. (void)FindClose(dir->handle);
  3069. dir->handle = INVALID_HANDLE_VALUE;
  3070. }
  3071. } else {
  3072. SetLastError(ERROR_FILE_NOT_FOUND);
  3073. }
  3074. } else {
  3075. SetLastError(ERROR_BAD_ARGUMENTS);
  3076. }
  3077. return result;
  3078. }
  3079. #ifndef HAVE_POLL
  3080. static int
  3081. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3082. {
  3083. struct timeval tv;
  3084. fd_set set;
  3085. unsigned int i;
  3086. int result;
  3087. SOCKET maxfd = 0;
  3088. memset(&tv, 0, sizeof(tv));
  3089. tv.tv_sec = milliseconds / 1000;
  3090. tv.tv_usec = (milliseconds % 1000) * 1000;
  3091. FD_ZERO(&set);
  3092. for (i = 0; i < n; i++) {
  3093. FD_SET((SOCKET)pfd[i].fd, &set);
  3094. pfd[i].revents = 0;
  3095. if (pfd[i].fd > maxfd) {
  3096. maxfd = pfd[i].fd;
  3097. }
  3098. }
  3099. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3100. for (i = 0; i < n; i++) {
  3101. if (FD_ISSET(pfd[i].fd, &set)) {
  3102. pfd[i].revents = POLLIN;
  3103. }
  3104. }
  3105. }
  3106. /* We should subtract the time used in select from remaining
  3107. * "milliseconds", in particular if called from mg_poll with a
  3108. * timeout quantum.
  3109. * Unfortunately, the remaining time is not stored in "tv" in all
  3110. * implementations, so the result in "tv" must be considered undefined.
  3111. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3112. return result;
  3113. }
  3114. #endif /* HAVE_POLL */
  3115. #if defined(__MINGW32__)
  3116. /* Enable unused function warning again */
  3117. #pragma GCC diagnostic pop
  3118. #endif
  3119. static void
  3120. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3121. {
  3122. (void)conn; /* Unused. */
  3123. #if defined(_WIN32_WCE)
  3124. (void)sock;
  3125. #else
  3126. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3127. #endif
  3128. }
  3129. int
  3130. mg_start_thread(mg_thread_func_t f, void *p)
  3131. {
  3132. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3133. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3134. */
  3135. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3136. == ((uintptr_t)(-1L)))
  3137. ? -1
  3138. : 0);
  3139. #else
  3140. return (
  3141. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3142. ? -1
  3143. : 0);
  3144. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3145. }
  3146. /* Start a thread storing the thread context. */
  3147. static int
  3148. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3149. void *p,
  3150. pthread_t *threadidptr)
  3151. {
  3152. uintptr_t uip;
  3153. HANDLE threadhandle;
  3154. int result = -1;
  3155. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3156. threadhandle = (HANDLE)uip;
  3157. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3158. *threadidptr = threadhandle;
  3159. result = 0;
  3160. }
  3161. return result;
  3162. }
  3163. /* Wait for a thread to finish. */
  3164. static int
  3165. mg_join_thread(pthread_t threadid)
  3166. {
  3167. int result;
  3168. DWORD dwevent;
  3169. result = -1;
  3170. dwevent = WaitForSingleObject(threadid, INFINITE);
  3171. if (dwevent == WAIT_FAILED) {
  3172. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3173. } else {
  3174. if (dwevent == WAIT_OBJECT_0) {
  3175. CloseHandle(threadid);
  3176. result = 0;
  3177. }
  3178. }
  3179. return result;
  3180. }
  3181. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3182. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3183. /* Create substitutes for POSIX functions in Win32. */
  3184. #if defined(__MINGW32__)
  3185. /* Show no warning in case system functions are not used. */
  3186. #pragma GCC diagnostic push
  3187. #pragma GCC diagnostic ignored "-Wunused-function"
  3188. #endif
  3189. static HANDLE
  3190. dlopen(const char *dll_name, int flags)
  3191. {
  3192. wchar_t wbuf[PATH_MAX];
  3193. (void)flags;
  3194. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3195. return LoadLibraryW(wbuf);
  3196. }
  3197. static int
  3198. dlclose(void *handle)
  3199. {
  3200. int result;
  3201. if (FreeLibrary((HMODULE)handle) != 0) {
  3202. result = 0;
  3203. } else {
  3204. result = -1;
  3205. }
  3206. return result;
  3207. }
  3208. #if defined(__MINGW32__)
  3209. /* Enable unused function warning again */
  3210. #pragma GCC diagnostic pop
  3211. #endif
  3212. #endif
  3213. #if !defined(NO_CGI)
  3214. #define SIGKILL (0)
  3215. static int
  3216. kill(pid_t pid, int sig_num)
  3217. {
  3218. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3219. (void)CloseHandle((HANDLE)pid);
  3220. return 0;
  3221. }
  3222. static void
  3223. trim_trailing_whitespaces(char *s)
  3224. {
  3225. char *e = s + strlen(s) - 1;
  3226. while (e > s && isspace(*(unsigned char *)e)) {
  3227. *e-- = '\0';
  3228. }
  3229. }
  3230. static pid_t
  3231. spawn_process(struct mg_connection *conn,
  3232. const char *prog,
  3233. char *envblk,
  3234. char *envp[],
  3235. int fdin[2],
  3236. int fdout[2],
  3237. int fderr[2],
  3238. const char *dir)
  3239. {
  3240. HANDLE me;
  3241. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3242. cmdline[PATH_MAX], buf[PATH_MAX];
  3243. int truncated;
  3244. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3245. STARTUPINFOA si;
  3246. PROCESS_INFORMATION pi = {0};
  3247. (void)envp;
  3248. memset(&si, 0, sizeof(si));
  3249. si.cb = sizeof(si);
  3250. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3251. si.wShowWindow = SW_HIDE;
  3252. me = GetCurrentProcess();
  3253. DuplicateHandle(me,
  3254. (HANDLE)_get_osfhandle(fdin[0]),
  3255. me,
  3256. &si.hStdInput,
  3257. 0,
  3258. TRUE,
  3259. DUPLICATE_SAME_ACCESS);
  3260. DuplicateHandle(me,
  3261. (HANDLE)_get_osfhandle(fdout[1]),
  3262. me,
  3263. &si.hStdOutput,
  3264. 0,
  3265. TRUE,
  3266. DUPLICATE_SAME_ACCESS);
  3267. DuplicateHandle(me,
  3268. (HANDLE)_get_osfhandle(fderr[1]),
  3269. me,
  3270. &si.hStdError,
  3271. 0,
  3272. TRUE,
  3273. DUPLICATE_SAME_ACCESS);
  3274. /* Mark handles that should not be inherited. See
  3275. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3276. */
  3277. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3278. HANDLE_FLAG_INHERIT,
  3279. 0);
  3280. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3281. HANDLE_FLAG_INHERIT,
  3282. 0);
  3283. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3284. HANDLE_FLAG_INHERIT,
  3285. 0);
  3286. /* If CGI file is a script, try to read the interpreter line */
  3287. interp = conn->ctx->config[CGI_INTERPRETER];
  3288. if (interp == NULL) {
  3289. buf[0] = buf[1] = '\0';
  3290. /* Read the first line of the script into the buffer */
  3291. mg_snprintf(
  3292. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3293. if (truncated) {
  3294. pi.hProcess = (pid_t)-1;
  3295. goto spawn_cleanup;
  3296. }
  3297. if (mg_fopen(conn, cmdline, "r", &file)) {
  3298. p = (char *)file.access.membuf;
  3299. mg_fgets(buf, sizeof(buf), &file, &p);
  3300. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3301. buf[sizeof(buf) - 1] = '\0';
  3302. }
  3303. if (buf[0] == '#' && buf[1] == '!') {
  3304. trim_trailing_whitespaces(buf + 2);
  3305. } else {
  3306. buf[2] = '\0';
  3307. }
  3308. interp = buf + 2;
  3309. }
  3310. if (interp[0] != '\0') {
  3311. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3312. interp = full_interp;
  3313. }
  3314. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3315. if (interp[0] != '\0') {
  3316. mg_snprintf(conn,
  3317. &truncated,
  3318. cmdline,
  3319. sizeof(cmdline),
  3320. "\"%s\" \"%s\\%s\"",
  3321. interp,
  3322. full_dir,
  3323. prog);
  3324. } else {
  3325. mg_snprintf(conn,
  3326. &truncated,
  3327. cmdline,
  3328. sizeof(cmdline),
  3329. "\"%s\\%s\"",
  3330. full_dir,
  3331. prog);
  3332. }
  3333. if (truncated) {
  3334. pi.hProcess = (pid_t)-1;
  3335. goto spawn_cleanup;
  3336. }
  3337. DEBUG_TRACE("Running [%s]", cmdline);
  3338. if (CreateProcessA(NULL,
  3339. cmdline,
  3340. NULL,
  3341. NULL,
  3342. TRUE,
  3343. CREATE_NEW_PROCESS_GROUP,
  3344. envblk,
  3345. NULL,
  3346. &si,
  3347. &pi) == 0) {
  3348. mg_cry(
  3349. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3350. pi.hProcess = (pid_t)-1;
  3351. /* goto spawn_cleanup; */
  3352. }
  3353. spawn_cleanup:
  3354. (void)CloseHandle(si.hStdOutput);
  3355. (void)CloseHandle(si.hStdError);
  3356. (void)CloseHandle(si.hStdInput);
  3357. if (pi.hThread != NULL) {
  3358. (void)CloseHandle(pi.hThread);
  3359. }
  3360. return (pid_t)pi.hProcess;
  3361. }
  3362. #endif /* !NO_CGI */
  3363. static int
  3364. set_non_blocking_mode(SOCKET sock)
  3365. {
  3366. unsigned long on = 1;
  3367. return ioctlsocket(sock, (long)FIONBIO, &on);
  3368. }
  3369. #else
  3370. static int
  3371. mg_stat(const struct mg_connection *conn,
  3372. const char *path,
  3373. struct mg_file_stat *filep)
  3374. {
  3375. struct stat st;
  3376. if (!filep) {
  3377. return 0;
  3378. }
  3379. memset(filep, 0, sizeof(*filep));
  3380. if (conn && is_file_in_memory(conn, path)) {
  3381. return 1;
  3382. }
  3383. if (0 == stat(path, &st)) {
  3384. filep->size = (uint64_t)(st.st_size);
  3385. filep->last_modified = st.st_mtime;
  3386. filep->is_directory = S_ISDIR(st.st_mode);
  3387. return 1;
  3388. }
  3389. return 0;
  3390. }
  3391. static void
  3392. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3393. {
  3394. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3395. if (conn) {
  3396. mg_cry(conn,
  3397. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3398. __func__,
  3399. strerror(ERRNO));
  3400. }
  3401. }
  3402. }
  3403. int
  3404. mg_start_thread(mg_thread_func_t func, void *param)
  3405. {
  3406. pthread_t thread_id;
  3407. pthread_attr_t attr;
  3408. int result;
  3409. (void)pthread_attr_init(&attr);
  3410. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3411. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3412. /* Compile-time option to control stack size,
  3413. * e.g. -DUSE_STACK_SIZE=16384 */
  3414. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3415. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3416. result = pthread_create(&thread_id, &attr, func, param);
  3417. pthread_attr_destroy(&attr);
  3418. return result;
  3419. }
  3420. /* Start a thread storing the thread context. */
  3421. static int
  3422. mg_start_thread_with_id(mg_thread_func_t func,
  3423. void *param,
  3424. pthread_t *threadidptr)
  3425. {
  3426. pthread_t thread_id;
  3427. pthread_attr_t attr;
  3428. int result;
  3429. (void)pthread_attr_init(&attr);
  3430. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3431. /* Compile-time option to control stack size,
  3432. * e.g. -DUSE_STACK_SIZE=16384 */
  3433. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3434. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3435. result = pthread_create(&thread_id, &attr, func, param);
  3436. pthread_attr_destroy(&attr);
  3437. if ((result == 0) && (threadidptr != NULL)) {
  3438. *threadidptr = thread_id;
  3439. }
  3440. return result;
  3441. }
  3442. /* Wait for a thread to finish. */
  3443. static int
  3444. mg_join_thread(pthread_t threadid)
  3445. {
  3446. int result;
  3447. result = pthread_join(threadid, NULL);
  3448. return result;
  3449. }
  3450. #ifndef NO_CGI
  3451. static pid_t
  3452. spawn_process(struct mg_connection *conn,
  3453. const char *prog,
  3454. char *envblk,
  3455. char *envp[],
  3456. int fdin[2],
  3457. int fdout[2],
  3458. int fderr[2],
  3459. const char *dir)
  3460. {
  3461. pid_t pid;
  3462. const char *interp;
  3463. (void)envblk;
  3464. if (conn == NULL) {
  3465. return 0;
  3466. }
  3467. if ((pid = fork()) == -1) {
  3468. /* Parent */
  3469. send_http_error(conn,
  3470. 500,
  3471. "Error: Creating CGI process\nfork(): %s",
  3472. strerror(ERRNO));
  3473. } else if (pid == 0) {
  3474. /* Child */
  3475. if (chdir(dir) != 0) {
  3476. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3477. } else if (dup2(fdin[0], 0) == -1) {
  3478. mg_cry(conn,
  3479. "%s: dup2(%d, 0): %s",
  3480. __func__,
  3481. fdin[0],
  3482. strerror(ERRNO));
  3483. } else if (dup2(fdout[1], 1) == -1) {
  3484. mg_cry(conn,
  3485. "%s: dup2(%d, 1): %s",
  3486. __func__,
  3487. fdout[1],
  3488. strerror(ERRNO));
  3489. } else if (dup2(fderr[1], 2) == -1) {
  3490. mg_cry(conn,
  3491. "%s: dup2(%d, 2): %s",
  3492. __func__,
  3493. fderr[1],
  3494. strerror(ERRNO));
  3495. } else {
  3496. /* Keep stderr and stdout in two different pipes.
  3497. * Stdout will be sent back to the client,
  3498. * stderr should go into a server error log. */
  3499. (void)close(fdin[0]);
  3500. (void)close(fdout[1]);
  3501. (void)close(fderr[1]);
  3502. /* Close write end fdin and read end fdout and fderr */
  3503. (void)close(fdin[1]);
  3504. (void)close(fdout[0]);
  3505. (void)close(fderr[0]);
  3506. /* After exec, all signal handlers are restored to their default
  3507. * values, with one exception of SIGCHLD. According to
  3508. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3509. * leave unchanged after exec if it was set to be ignored. Restore
  3510. * it to default action. */
  3511. signal(SIGCHLD, SIG_DFL);
  3512. interp = conn->ctx->config[CGI_INTERPRETER];
  3513. if (interp == NULL) {
  3514. (void)execle(prog, prog, NULL, envp);
  3515. mg_cry(conn,
  3516. "%s: execle(%s): %s",
  3517. __func__,
  3518. prog,
  3519. strerror(ERRNO));
  3520. } else {
  3521. (void)execle(interp, interp, prog, NULL, envp);
  3522. mg_cry(conn,
  3523. "%s: execle(%s %s): %s",
  3524. __func__,
  3525. interp,
  3526. prog,
  3527. strerror(ERRNO));
  3528. }
  3529. }
  3530. exit(EXIT_FAILURE);
  3531. }
  3532. return pid;
  3533. }
  3534. #endif /* !NO_CGI */
  3535. static int
  3536. set_non_blocking_mode(SOCKET sock)
  3537. {
  3538. int flags;
  3539. flags = fcntl(sock, F_GETFL, 0);
  3540. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3541. return 0;
  3542. }
  3543. #endif /* _WIN32 */
  3544. /* End of initial operating system specific define block. */
  3545. /* Get a random number (independent of C rand function) */
  3546. static uint64_t
  3547. get_random(void)
  3548. {
  3549. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3550. static uint64_t lcg = 0; /* Linear congruential generator */
  3551. struct timespec now;
  3552. memset(&now, 0, sizeof(now));
  3553. clock_gettime(CLOCK_MONOTONIC, &now);
  3554. if (lfsr == 0) {
  3555. /* lfsr will be only 0 if has not been initialized,
  3556. * so this code is called only once. */
  3557. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3558. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3559. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3560. + (uint64_t)(ptrdiff_t)&now;
  3561. } else {
  3562. /* Get the next step of both random number generators. */
  3563. lfsr = (lfsr >> 1)
  3564. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3565. << 63);
  3566. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3567. }
  3568. /* Combining two pseudo-random number generators and a high resolution part
  3569. * of the current server time will make it hard (impossible?) to guess the
  3570. * next number. */
  3571. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3572. }
  3573. static int
  3574. mg_poll(struct pollfd *pfd,
  3575. unsigned int n,
  3576. int milliseconds,
  3577. volatile int *stop_server)
  3578. {
  3579. int ms_now, result;
  3580. /* Call poll, but only for a maximum time of a few seconds.
  3581. * This will allow to stop the server after some seconds, instead
  3582. * of having to wait for a long socket timeout. */
  3583. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3584. do {
  3585. if (*stop_server) {
  3586. /* Shut down signal */
  3587. return -2;
  3588. }
  3589. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3590. ms_now = milliseconds;
  3591. }
  3592. result = poll(pfd, n, ms_now);
  3593. if (result != 0) {
  3594. /* Poll returned either success (1) or error (-1).
  3595. * Forward both to the caller. */
  3596. return result;
  3597. }
  3598. /* Poll returned timeout (0). */
  3599. if (milliseconds > 0) {
  3600. milliseconds -= ms_now;
  3601. }
  3602. } while (milliseconds != 0);
  3603. return result;
  3604. }
  3605. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3606. * descriptor. Return number of bytes written. */
  3607. static int
  3608. push(struct mg_context *ctx,
  3609. FILE *fp,
  3610. SOCKET sock,
  3611. SSL *ssl,
  3612. const char *buf,
  3613. int len,
  3614. double timeout)
  3615. {
  3616. struct timespec start, now;
  3617. int n, err;
  3618. #ifdef _WIN32
  3619. typedef int len_t;
  3620. #else
  3621. typedef size_t len_t;
  3622. #endif
  3623. if (timeout > 0) {
  3624. memset(&start, 0, sizeof(start));
  3625. memset(&now, 0, sizeof(now));
  3626. clock_gettime(CLOCK_MONOTONIC, &start);
  3627. }
  3628. if (ctx == NULL) {
  3629. return -1;
  3630. }
  3631. #ifdef NO_SSL
  3632. if (ssl) {
  3633. return -1;
  3634. }
  3635. #endif
  3636. do {
  3637. #ifndef NO_SSL
  3638. if (ssl != NULL) {
  3639. n = SSL_write(ssl, buf, len);
  3640. if (n <= 0) {
  3641. err = SSL_get_error(ssl, n);
  3642. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3643. err = ERRNO;
  3644. } else if ((err == SSL_ERROR_WANT_READ)
  3645. || (err == SSL_ERROR_WANT_WRITE)) {
  3646. n = 0;
  3647. } else {
  3648. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3649. return -1;
  3650. }
  3651. } else {
  3652. err = 0;
  3653. }
  3654. } else
  3655. #endif
  3656. if (fp != NULL) {
  3657. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3658. if (ferror(fp)) {
  3659. n = -1;
  3660. err = ERRNO;
  3661. } else {
  3662. err = 0;
  3663. }
  3664. } else {
  3665. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3666. err = (n < 0) ? ERRNO : 0;
  3667. if (n <= 0) {
  3668. /* shutdown of the socket at client side */
  3669. return -1;
  3670. }
  3671. #if defined(TEMPORARY_INSTRUMENTATION)
  3672. {
  3673. FILE *f = fopen("r:\\all.txt", "ab");
  3674. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3675. fwrite(buf, 1, n, f);
  3676. fclose(f);
  3677. }
  3678. #endif
  3679. }
  3680. if (ctx->stop_flag) {
  3681. return -1;
  3682. }
  3683. if ((n > 0) || (n == 0 && len == 0)) {
  3684. /* some data has been read, or no data was requested */
  3685. return n;
  3686. }
  3687. if (n < 0) {
  3688. /* socket error - check errno */
  3689. DEBUG_TRACE("send() failed, error %d", err);
  3690. /* TODO: error handling depending on the error code.
  3691. * These codes are different between Windows and Linux.
  3692. */
  3693. return -1;
  3694. }
  3695. /* This code is not reached in the moment.
  3696. * ==> Fix the TODOs above first. */
  3697. if (timeout > 0) {
  3698. clock_gettime(CLOCK_MONOTONIC, &now);
  3699. }
  3700. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3701. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3702. used */
  3703. return -1;
  3704. }
  3705. static int64_t
  3706. push_all(struct mg_context *ctx,
  3707. FILE *fp,
  3708. SOCKET sock,
  3709. SSL *ssl,
  3710. const char *buf,
  3711. int64_t len)
  3712. {
  3713. double timeout = -1.0;
  3714. int64_t n, nwritten = 0;
  3715. if (ctx == NULL) {
  3716. return -1;
  3717. }
  3718. if (ctx->config[REQUEST_TIMEOUT]) {
  3719. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3720. }
  3721. while (len > 0 && ctx->stop_flag == 0) {
  3722. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3723. if (n < 0) {
  3724. if (nwritten == 0) {
  3725. nwritten = n; /* Propagate the error */
  3726. }
  3727. break;
  3728. } else if (n == 0) {
  3729. break; /* No more data to write */
  3730. } else {
  3731. nwritten += n;
  3732. len -= n;
  3733. }
  3734. }
  3735. return nwritten;
  3736. }
  3737. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3738. * Return negative value on error, or number of bytes read on success. */
  3739. static int
  3740. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3741. {
  3742. int nread, err = 0;
  3743. #ifdef _WIN32
  3744. typedef int len_t;
  3745. #else
  3746. typedef size_t len_t;
  3747. #endif
  3748. if (fp != NULL) {
  3749. #if !defined(_WIN32_WCE)
  3750. /* Use read() instead of fread(), because if we're reading from the
  3751. * CGI pipe, fread() may block until IO buffer is filled up. We
  3752. * cannot afford to block and must pass all read bytes immediately
  3753. * to the client. */
  3754. nread = (int)read(fileno(fp), buf, (size_t)len);
  3755. #else
  3756. /* WinCE does not support CGI pipes */
  3757. nread = (int)fread(buf, 1, (size_t)len, fp);
  3758. #endif
  3759. err = (nread < 0) ? ERRNO : 0;
  3760. #ifndef NO_SSL
  3761. } else if (conn->ssl != NULL) {
  3762. struct pollfd pfd[1];
  3763. int pollres;
  3764. pfd[0].fd = conn->client.sock;
  3765. pfd[0].events = POLLIN;
  3766. pollres =
  3767. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3768. if (conn->ctx->stop_flag) {
  3769. return -1;
  3770. }
  3771. if (pollres > 0) {
  3772. nread = SSL_read(conn->ssl, buf, len);
  3773. if (nread <= 0) {
  3774. err = SSL_get_error(conn->ssl, nread);
  3775. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3776. err = ERRNO;
  3777. } else if ((err == SSL_ERROR_WANT_READ)
  3778. || (err == SSL_ERROR_WANT_WRITE)) {
  3779. nread = 0;
  3780. } else {
  3781. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3782. return -1;
  3783. }
  3784. } else {
  3785. err = 0;
  3786. }
  3787. } else if (pollres < 0) {
  3788. /* Error */
  3789. return -1;
  3790. } else {
  3791. /* pollres = 0 means timeout */
  3792. nread = 0;
  3793. }
  3794. #endif
  3795. } else {
  3796. struct pollfd pfd[1];
  3797. int pollres;
  3798. pfd[0].fd = conn->client.sock;
  3799. pfd[0].events = POLLIN;
  3800. pollres =
  3801. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3802. if (conn->ctx->stop_flag) {
  3803. return -1;
  3804. }
  3805. if (pollres > 0) {
  3806. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3807. err = (nread < 0) ? ERRNO : 0;
  3808. if (nread <= 0) {
  3809. /* shutdown of the socket at client side */
  3810. return -1;
  3811. }
  3812. #if defined(TEMPORARY_INSTRUMENTATION)
  3813. {
  3814. FILE *f = fopen("r:\\all.txt", "ab");
  3815. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3816. fwrite(buf, 1, nread, f);
  3817. fclose(f);
  3818. }
  3819. #endif
  3820. } else if (pollres < 0) {
  3821. /* error callint poll */
  3822. return -1;
  3823. } else {
  3824. /* pollres = 0 means timeout */
  3825. nread = 0;
  3826. }
  3827. }
  3828. if (conn->ctx->stop_flag) {
  3829. return -1;
  3830. }
  3831. if ((nread > 0) || (nread == 0 && len == 0)) {
  3832. /* some data has been read, or no data was requested */
  3833. return nread;
  3834. }
  3835. if (nread < 0) {
  3836. /* socket error - check errno */
  3837. #ifdef _WIN32
  3838. if (err == WSAEWOULDBLOCK) {
  3839. /* TODO: check if this is still required */
  3840. /* standard case if called from close_socket_gracefully */
  3841. return -1;
  3842. } else if (err == WSAETIMEDOUT) {
  3843. /* TODO: check if this is still required */
  3844. /* timeout is handled by the while loop */
  3845. return 0;
  3846. } else if (err == WSAECONNABORTED) {
  3847. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3848. return -1;
  3849. } else {
  3850. DEBUG_TRACE("recv() failed, error %d", err);
  3851. return -1;
  3852. }
  3853. #else
  3854. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3855. * if the timeout is reached and if the socket was set to non-
  3856. * blocking in close_socket_gracefully, so we can not distinguish
  3857. * here. We have to wait for the timeout in both cases for now.
  3858. */
  3859. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3860. /* TODO: check if this is still required */
  3861. /* EAGAIN/EWOULDBLOCK:
  3862. * standard case if called from close_socket_gracefully
  3863. * => should return -1 */
  3864. /* or timeout occured
  3865. * => the code must stay in the while loop */
  3866. /* EINTR can be generated on a socket with a timeout set even
  3867. * when SA_RESTART is effective for all relevant signals
  3868. * (see signal(7)).
  3869. * => stay in the while loop */
  3870. } else {
  3871. DEBUG_TRACE("recv() failed, error %d", err);
  3872. return -1;
  3873. }
  3874. #endif
  3875. }
  3876. /* Timeout occured, but no data available. */
  3877. return -1;
  3878. }
  3879. static int
  3880. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3881. {
  3882. int n, nread = 0;
  3883. double timeout = -1.0;
  3884. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3885. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3886. }
  3887. while (len > 0 && conn->ctx->stop_flag == 0) {
  3888. n = pull(fp, conn, buf + nread, len, timeout);
  3889. if (n < 0) {
  3890. if (nread == 0) {
  3891. nread = n; /* Propagate the error */
  3892. }
  3893. break;
  3894. } else if (n == 0) {
  3895. break; /* No more data to read */
  3896. } else {
  3897. conn->consumed_content += n;
  3898. nread += n;
  3899. len -= n;
  3900. }
  3901. }
  3902. return nread;
  3903. }
  3904. static void
  3905. discard_unread_request_data(struct mg_connection *conn)
  3906. {
  3907. char buf[MG_BUF_LEN];
  3908. size_t to_read;
  3909. int nread;
  3910. if (conn == NULL) {
  3911. return;
  3912. }
  3913. to_read = sizeof(buf);
  3914. if (conn->is_chunked) {
  3915. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3916. * completely */
  3917. while (conn->is_chunked == 1) {
  3918. nread = mg_read(conn, buf, to_read);
  3919. if (nread <= 0) {
  3920. break;
  3921. }
  3922. }
  3923. } else {
  3924. /* Not chunked: content length is known */
  3925. while (conn->consumed_content < conn->content_len) {
  3926. if (to_read
  3927. > (size_t)(conn->content_len - conn->consumed_content)) {
  3928. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3929. }
  3930. nread = mg_read(conn, buf, to_read);
  3931. if (nread <= 0) {
  3932. break;
  3933. }
  3934. }
  3935. }
  3936. }
  3937. static int
  3938. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3939. {
  3940. int64_t n, buffered_len, nread;
  3941. int64_t len64 =
  3942. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3943. * int, we may not read more
  3944. * bytes */
  3945. const char *body;
  3946. if (conn == NULL) {
  3947. return 0;
  3948. }
  3949. /* If Content-Length is not set for a PUT or POST request, read until
  3950. * socket is closed */
  3951. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3952. conn->content_len = INT64_MAX;
  3953. conn->must_close = 1;
  3954. }
  3955. nread = 0;
  3956. if (conn->consumed_content < conn->content_len) {
  3957. /* Adjust number of bytes to read. */
  3958. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3959. if (left_to_read < len64) {
  3960. /* Do not read more than the total content length of the request.
  3961. */
  3962. len64 = left_to_read;
  3963. }
  3964. /* Return buffered data */
  3965. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3966. - conn->consumed_content;
  3967. if (buffered_len > 0) {
  3968. if (len64 < buffered_len) {
  3969. buffered_len = len64;
  3970. }
  3971. body = conn->buf + conn->request_len + conn->consumed_content;
  3972. memcpy(buf, body, (size_t)buffered_len);
  3973. len64 -= buffered_len;
  3974. conn->consumed_content += buffered_len;
  3975. nread += buffered_len;
  3976. buf = (char *)buf + buffered_len;
  3977. }
  3978. /* We have returned all buffered data. Read new data from the remote
  3979. * socket.
  3980. */
  3981. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3982. nread += n;
  3983. } else {
  3984. nread = ((nread > 0) ? nread : n);
  3985. }
  3986. }
  3987. return (int)nread;
  3988. }
  3989. static char
  3990. mg_getc(struct mg_connection *conn)
  3991. {
  3992. char c;
  3993. if (conn == NULL) {
  3994. return 0;
  3995. }
  3996. conn->content_len++;
  3997. if (mg_read_inner(conn, &c, 1) <= 0) {
  3998. return (char)0;
  3999. }
  4000. return c;
  4001. }
  4002. int
  4003. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4004. {
  4005. if (len > INT_MAX) {
  4006. len = INT_MAX;
  4007. }
  4008. if (conn == NULL) {
  4009. return 0;
  4010. }
  4011. if (conn->is_chunked) {
  4012. size_t all_read = 0;
  4013. while (len > 0) {
  4014. if (conn->is_chunked == 2) {
  4015. /* No more data left to read */
  4016. return 0;
  4017. }
  4018. if (conn->chunk_remainder) {
  4019. /* copy from the remainder of the last received chunk */
  4020. long read_ret;
  4021. size_t read_now =
  4022. ((conn->chunk_remainder > len) ? (len)
  4023. : (conn->chunk_remainder));
  4024. conn->content_len += (int)read_now;
  4025. read_ret =
  4026. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4027. if (read_ret < 1) {
  4028. /* read error */
  4029. return -1;
  4030. }
  4031. all_read += (size_t)read_ret;
  4032. conn->chunk_remainder -= (size_t)read_ret;
  4033. len -= (size_t)read_ret;
  4034. if (conn->chunk_remainder == 0) {
  4035. /* Add data bytes in the current chunk have been read,
  4036. * so we are expecting \r\n now. */
  4037. char x1 = mg_getc(conn);
  4038. char x2 = mg_getc(conn);
  4039. if ((x1 != '\r') || (x2 != '\n')) {
  4040. /* Protocol violation */
  4041. return -1;
  4042. }
  4043. }
  4044. } else {
  4045. /* fetch a new chunk */
  4046. int i = 0;
  4047. char lenbuf[64];
  4048. char *end = 0;
  4049. unsigned long chunkSize = 0;
  4050. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4051. lenbuf[i] = mg_getc(conn);
  4052. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4053. continue;
  4054. }
  4055. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4056. lenbuf[i + 1] = 0;
  4057. chunkSize = strtoul(lenbuf, &end, 16);
  4058. if (chunkSize == 0) {
  4059. /* regular end of content */
  4060. conn->is_chunked = 2;
  4061. }
  4062. break;
  4063. }
  4064. if (!isxdigit(lenbuf[i])) {
  4065. /* illegal character for chunk length */
  4066. return -1;
  4067. }
  4068. }
  4069. if ((end == NULL) || (*end != '\r')) {
  4070. /* chunksize not set correctly */
  4071. return -1;
  4072. }
  4073. if (chunkSize == 0) {
  4074. break;
  4075. }
  4076. conn->chunk_remainder = chunkSize;
  4077. }
  4078. }
  4079. return (int)all_read;
  4080. }
  4081. return mg_read_inner(conn, buf, len);
  4082. }
  4083. int
  4084. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4085. {
  4086. time_t now;
  4087. int64_t n, total, allowed;
  4088. if (conn == NULL) {
  4089. return 0;
  4090. }
  4091. if (conn->throttle > 0) {
  4092. if ((now = time(NULL)) != conn->last_throttle_time) {
  4093. conn->last_throttle_time = now;
  4094. conn->last_throttle_bytes = 0;
  4095. }
  4096. allowed = conn->throttle - conn->last_throttle_bytes;
  4097. if (allowed > (int64_t)len) {
  4098. allowed = (int64_t)len;
  4099. }
  4100. if ((total = push_all(conn->ctx,
  4101. NULL,
  4102. conn->client.sock,
  4103. conn->ssl,
  4104. (const char *)buf,
  4105. (int64_t)allowed)) == allowed) {
  4106. buf = (const char *)buf + total;
  4107. conn->last_throttle_bytes += total;
  4108. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4109. allowed = (conn->throttle > ((int64_t)len - total))
  4110. ? (int64_t)len - total
  4111. : conn->throttle;
  4112. if ((n = push_all(conn->ctx,
  4113. NULL,
  4114. conn->client.sock,
  4115. conn->ssl,
  4116. (const char *)buf,
  4117. (int64_t)allowed)) != allowed) {
  4118. break;
  4119. }
  4120. sleep(1);
  4121. conn->last_throttle_bytes = allowed;
  4122. conn->last_throttle_time = time(NULL);
  4123. buf = (const char *)buf + n;
  4124. total += n;
  4125. }
  4126. }
  4127. } else {
  4128. total = push_all(conn->ctx,
  4129. NULL,
  4130. conn->client.sock,
  4131. conn->ssl,
  4132. (const char *)buf,
  4133. (int64_t)len);
  4134. }
  4135. return (int)total;
  4136. }
  4137. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4138. static int
  4139. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4140. {
  4141. va_list ap_copy;
  4142. size_t size = MG_BUF_LEN / 4;
  4143. int len = -1;
  4144. *buf = NULL;
  4145. while (len < 0) {
  4146. if (*buf) {
  4147. mg_free(*buf);
  4148. }
  4149. size *= 4;
  4150. *buf = (char *)mg_malloc(size);
  4151. if (!*buf) {
  4152. break;
  4153. }
  4154. va_copy(ap_copy, ap);
  4155. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4156. va_end(ap_copy);
  4157. (*buf)[size - 1] = 0;
  4158. }
  4159. return len;
  4160. }
  4161. /* Print message to buffer. If buffer is large enough to hold the message,
  4162. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4163. * and return allocated buffer. */
  4164. static int
  4165. alloc_vprintf(char **out_buf,
  4166. char *prealloc_buf,
  4167. size_t prealloc_size,
  4168. const char *fmt,
  4169. va_list ap)
  4170. {
  4171. va_list ap_copy;
  4172. int len;
  4173. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4174. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4175. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4176. * Therefore, we make two passes: on first pass, get required message
  4177. * length.
  4178. * On second pass, actually print the message. */
  4179. va_copy(ap_copy, ap);
  4180. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4181. va_end(ap_copy);
  4182. if (len < 0) {
  4183. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4184. * Switch to alternative code path that uses incremental allocations.
  4185. */
  4186. va_copy(ap_copy, ap);
  4187. len = alloc_vprintf2(out_buf, fmt, ap);
  4188. va_end(ap_copy);
  4189. } else if ((size_t)(len) >= prealloc_size) {
  4190. /* The pre-allocated buffer not large enough. */
  4191. /* Allocate a new buffer. */
  4192. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4193. if (!*out_buf) {
  4194. /* Allocation failed. Return -1 as "out of memory" error. */
  4195. return -1;
  4196. }
  4197. /* Buffer allocation successful. Store the string there. */
  4198. va_copy(ap_copy, ap);
  4199. IGNORE_UNUSED_RESULT(
  4200. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4201. va_end(ap_copy);
  4202. } else {
  4203. /* The pre-allocated buffer is large enough.
  4204. * Use it to store the string and return the address. */
  4205. va_copy(ap_copy, ap);
  4206. IGNORE_UNUSED_RESULT(
  4207. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4208. va_end(ap_copy);
  4209. *out_buf = prealloc_buf;
  4210. }
  4211. return len;
  4212. }
  4213. static int
  4214. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4215. {
  4216. char mem[MG_BUF_LEN];
  4217. char *buf = NULL;
  4218. int len;
  4219. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4220. len = mg_write(conn, buf, (size_t)len);
  4221. }
  4222. if (buf != mem && buf != NULL) {
  4223. mg_free(buf);
  4224. }
  4225. return len;
  4226. }
  4227. int
  4228. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4229. {
  4230. va_list ap;
  4231. int result;
  4232. va_start(ap, fmt);
  4233. result = mg_vprintf(conn, fmt, ap);
  4234. va_end(ap);
  4235. return result;
  4236. }
  4237. int
  4238. mg_url_decode(const char *src,
  4239. int src_len,
  4240. char *dst,
  4241. int dst_len,
  4242. int is_form_url_encoded)
  4243. {
  4244. int i, j, a, b;
  4245. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4246. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4247. if (i < src_len - 2 && src[i] == '%'
  4248. && isxdigit(*(const unsigned char *)(src + i + 1))
  4249. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4250. a = tolower(*(const unsigned char *)(src + i + 1));
  4251. b = tolower(*(const unsigned char *)(src + i + 2));
  4252. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4253. i += 2;
  4254. } else if (is_form_url_encoded && src[i] == '+') {
  4255. dst[j] = ' ';
  4256. } else {
  4257. dst[j] = src[i];
  4258. }
  4259. }
  4260. dst[j] = '\0'; /* Null-terminate the destination */
  4261. return (i >= src_len) ? j : -1;
  4262. }
  4263. int
  4264. mg_get_var(const char *data,
  4265. size_t data_len,
  4266. const char *name,
  4267. char *dst,
  4268. size_t dst_len)
  4269. {
  4270. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4271. }
  4272. int
  4273. mg_get_var2(const char *data,
  4274. size_t data_len,
  4275. const char *name,
  4276. char *dst,
  4277. size_t dst_len,
  4278. size_t occurrence)
  4279. {
  4280. const char *p, *e, *s;
  4281. size_t name_len;
  4282. int len;
  4283. if (dst == NULL || dst_len == 0) {
  4284. len = -2;
  4285. } else if (data == NULL || name == NULL || data_len == 0) {
  4286. len = -1;
  4287. dst[0] = '\0';
  4288. } else {
  4289. name_len = strlen(name);
  4290. e = data + data_len;
  4291. len = -1;
  4292. dst[0] = '\0';
  4293. /* data is "var1=val1&var2=val2...". Find variable first */
  4294. for (p = data; p + name_len < e; p++) {
  4295. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4296. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4297. /* Point p to variable value */
  4298. p += name_len + 1;
  4299. /* Point s to the end of the value */
  4300. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4301. if (s == NULL) {
  4302. s = e;
  4303. }
  4304. /* assert(s >= p); */
  4305. if (s < p) {
  4306. return -3;
  4307. }
  4308. /* Decode variable into destination buffer */
  4309. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4310. /* Redirect error code from -1 to -2 (destination buffer too
  4311. * small). */
  4312. if (len == -1) {
  4313. len = -2;
  4314. }
  4315. break;
  4316. }
  4317. }
  4318. }
  4319. return len;
  4320. }
  4321. /* HCP24: some changes to compare hole var_name */
  4322. int
  4323. mg_get_cookie(const char *cookie_header,
  4324. const char *var_name,
  4325. char *dst,
  4326. size_t dst_size)
  4327. {
  4328. const char *s, *p, *end;
  4329. int name_len, len = -1;
  4330. if (dst == NULL || dst_size == 0) {
  4331. return -2;
  4332. }
  4333. dst[0] = '\0';
  4334. if (var_name == NULL || (s = cookie_header) == NULL) {
  4335. return -1;
  4336. }
  4337. name_len = (int)strlen(var_name);
  4338. end = s + strlen(s);
  4339. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4340. if (s[name_len] == '=') {
  4341. /* HCP24: now check is it a substring or a full cookie name */
  4342. if ((s == cookie_header) || (s[-1] == ' ')) {
  4343. s += name_len + 1;
  4344. if ((p = strchr(s, ' ')) == NULL) {
  4345. p = end;
  4346. }
  4347. if (p[-1] == ';') {
  4348. p--;
  4349. }
  4350. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4351. s++;
  4352. p--;
  4353. }
  4354. if ((size_t)(p - s) < dst_size) {
  4355. len = (int)(p - s);
  4356. mg_strlcpy(dst, s, (size_t)len + 1);
  4357. } else {
  4358. len = -3;
  4359. }
  4360. break;
  4361. }
  4362. }
  4363. }
  4364. return len;
  4365. }
  4366. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4367. static void
  4368. base64_encode(const unsigned char *src, int src_len, char *dst)
  4369. {
  4370. static const char *b64 =
  4371. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4372. int i, j, a, b, c;
  4373. for (i = j = 0; i < src_len; i += 3) {
  4374. a = src[i];
  4375. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4376. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4377. dst[j++] = b64[a >> 2];
  4378. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4379. if (i + 1 < src_len) {
  4380. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4381. }
  4382. if (i + 2 < src_len) {
  4383. dst[j++] = b64[c & 63];
  4384. }
  4385. }
  4386. while (j % 4 != 0) {
  4387. dst[j++] = '=';
  4388. }
  4389. dst[j++] = '\0';
  4390. }
  4391. #endif
  4392. #if defined(USE_LUA)
  4393. static unsigned char
  4394. b64reverse(char letter)
  4395. {
  4396. if (letter >= 'A' && letter <= 'Z') {
  4397. return letter - 'A';
  4398. }
  4399. if (letter >= 'a' && letter <= 'z') {
  4400. return letter - 'a' + 26;
  4401. }
  4402. if (letter >= '0' && letter <= '9') {
  4403. return letter - '0' + 52;
  4404. }
  4405. if (letter == '+') {
  4406. return 62;
  4407. }
  4408. if (letter == '/') {
  4409. return 63;
  4410. }
  4411. if (letter == '=') {
  4412. return 255; /* normal end */
  4413. }
  4414. return 254; /* error */
  4415. }
  4416. static int
  4417. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4418. {
  4419. int i;
  4420. unsigned char a, b, c, d;
  4421. *dst_len = 0;
  4422. for (i = 0; i < src_len; i += 4) {
  4423. a = b64reverse(src[i]);
  4424. if (a >= 254) {
  4425. return i;
  4426. }
  4427. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4428. if (b >= 254) {
  4429. return i + 1;
  4430. }
  4431. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4432. if (c == 254) {
  4433. return i + 2;
  4434. }
  4435. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4436. if (d == 254) {
  4437. return i + 3;
  4438. }
  4439. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4440. if (c != 255) {
  4441. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4442. if (d != 255) {
  4443. dst[(*dst_len)++] = (c << 6) + d;
  4444. }
  4445. }
  4446. }
  4447. return -1;
  4448. }
  4449. #endif
  4450. static int
  4451. is_put_or_delete_method(const struct mg_connection *conn)
  4452. {
  4453. if (conn) {
  4454. const char *s = conn->request_info.request_method;
  4455. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4456. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4457. }
  4458. return 0;
  4459. }
  4460. static void
  4461. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4462. char *filename, /* out: filename */
  4463. size_t filename_buf_len, /* in: size of filename buffer */
  4464. struct mg_file_stat *filestat, /* out: file structure */
  4465. int *is_found, /* out: file found (directly) */
  4466. int *is_script_resource, /* out: handled by a script? */
  4467. int *is_websocket_request, /* out: websocket connetion? */
  4468. int *is_put_or_delete_request /* out: put/delete a file? */
  4469. )
  4470. {
  4471. /* TODO (high): Restructure this function */
  4472. #if !defined(NO_FILES)
  4473. const char *uri = conn->request_info.local_uri;
  4474. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4475. const char *rewrite;
  4476. struct vec a, b;
  4477. int match_len;
  4478. char gz_path[PATH_MAX];
  4479. char const *accept_encoding;
  4480. int truncated;
  4481. #if !defined(NO_CGI) || defined(USE_LUA)
  4482. char *p;
  4483. #endif
  4484. #else
  4485. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4486. #endif
  4487. memset(filestat, 0, sizeof(*filestat));
  4488. *filename = 0;
  4489. *is_found = 0;
  4490. *is_script_resource = 0;
  4491. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4492. #if defined(USE_WEBSOCKET)
  4493. *is_websocket_request = is_websocket_protocol(conn);
  4494. #if !defined(NO_FILES)
  4495. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4496. root = conn->ctx->config[WEBSOCKET_ROOT];
  4497. }
  4498. #endif /* !NO_FILES */
  4499. #else /* USE_WEBSOCKET */
  4500. *is_websocket_request = 0;
  4501. #endif /* USE_WEBSOCKET */
  4502. #if !defined(NO_FILES)
  4503. /* Note that root == NULL is a regular use case here. This occurs,
  4504. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4505. * config is not required. */
  4506. if (root == NULL) {
  4507. /* all file related outputs have already been set to 0, just return
  4508. */
  4509. return;
  4510. }
  4511. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4512. * of the path one byte on the right.
  4513. * If document_root is NULL, leave the file empty. */
  4514. mg_snprintf(
  4515. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4516. if (truncated) {
  4517. goto interpret_cleanup;
  4518. }
  4519. rewrite = conn->ctx->config[REWRITE];
  4520. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4521. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4522. mg_snprintf(conn,
  4523. &truncated,
  4524. filename,
  4525. filename_buf_len - 1,
  4526. "%.*s%s",
  4527. (int)b.len,
  4528. b.ptr,
  4529. uri + match_len);
  4530. break;
  4531. }
  4532. }
  4533. if (truncated) {
  4534. goto interpret_cleanup;
  4535. }
  4536. /* Local file path and name, corresponding to requested URI
  4537. * is now stored in "filename" variable. */
  4538. if (mg_stat(conn, filename, filestat)) {
  4539. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4540. /* File exists. Check if it is a script type. */
  4541. if (0
  4542. #if !defined(NO_CGI)
  4543. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4544. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4545. filename) > 0
  4546. #endif
  4547. #if defined(USE_LUA)
  4548. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4549. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4550. filename) > 0
  4551. #endif
  4552. #if defined(USE_DUKTAPE)
  4553. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4554. strlen(
  4555. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4556. filename) > 0
  4557. #endif
  4558. ) {
  4559. /* The request addresses a CGI script or a Lua script. The URI
  4560. * corresponds to the script itself (like /path/script.cgi),
  4561. * and there is no additional resource path
  4562. * (like /path/script.cgi/something).
  4563. * Requests that modify (replace or delete) a resource, like
  4564. * PUT and DELETE requests, should replace/delete the script
  4565. * file.
  4566. * Requests that read or write from/to a resource, like GET and
  4567. * POST requests, should call the script and return the
  4568. * generated response. */
  4569. *is_script_resource = !*is_put_or_delete_request;
  4570. }
  4571. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4572. *is_found = 1;
  4573. return;
  4574. }
  4575. /* If we can't find the actual file, look for the file
  4576. * with the same name but a .gz extension. If we find it,
  4577. * use that and set the gzipped flag in the file struct
  4578. * to indicate that the response need to have the content-
  4579. * encoding: gzip header.
  4580. * We can only do this if the browser declares support. */
  4581. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4582. if (strstr(accept_encoding, "gzip") != NULL) {
  4583. mg_snprintf(
  4584. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4585. if (truncated) {
  4586. goto interpret_cleanup;
  4587. }
  4588. if (mg_stat(conn, gz_path, filestat)) {
  4589. if (filestat) {
  4590. filestat->is_gzipped = 1;
  4591. *is_found = 1;
  4592. }
  4593. /* Currently gz files can not be scripts. */
  4594. return;
  4595. }
  4596. }
  4597. }
  4598. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4599. /* Support PATH_INFO for CGI scripts. */
  4600. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4601. if (*p == '/') {
  4602. *p = '\0';
  4603. if ((0
  4604. #if !defined(NO_CGI)
  4605. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4606. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4607. filename) > 0
  4608. #endif
  4609. #if defined(USE_LUA)
  4610. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4611. strlen(
  4612. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4613. filename) > 0
  4614. #endif
  4615. #if defined(USE_DUKTAPE)
  4616. || match_prefix(
  4617. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4618. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4619. filename) > 0
  4620. #endif
  4621. ) && mg_stat(conn, filename, filestat)) {
  4622. /* Shift PATH_INFO block one character right, e.g.
  4623. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4624. * conn->path_info is pointing to the local variable "path"
  4625. * declared in handle_request(), so PATH_INFO is not valid
  4626. * after handle_request returns. */
  4627. conn->path_info = p + 1;
  4628. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4629. * trailing \0 */
  4630. p[1] = '/';
  4631. *is_script_resource = 1;
  4632. break;
  4633. } else {
  4634. *p = '/';
  4635. }
  4636. }
  4637. }
  4638. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4639. #endif /* !defined(NO_FILES) */
  4640. return;
  4641. #if !defined(NO_FILES)
  4642. /* Reset all outputs */
  4643. interpret_cleanup:
  4644. memset(filestat, 0, sizeof(*filestat));
  4645. *filename = 0;
  4646. *is_found = 0;
  4647. *is_script_resource = 0;
  4648. *is_websocket_request = 0;
  4649. *is_put_or_delete_request = 0;
  4650. #endif /* !defined(NO_FILES) */
  4651. }
  4652. /* Check whether full request is buffered. Return:
  4653. * -1 if request is malformed
  4654. * 0 if request is not yet fully buffered
  4655. * >0 actual request length, including last \r\n\r\n */
  4656. static int
  4657. get_request_len(const char *buf, int buflen)
  4658. {
  4659. const char *s, *e;
  4660. int len = 0;
  4661. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4662. /* Control characters are not allowed but >=128 is. */
  4663. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4664. && *(const unsigned char *)s < 128) {
  4665. len = -1;
  4666. break; /* [i_a] abort scan as soon as one malformed character is
  4667. * found; */
  4668. /* don't let subsequent \r\n\r\n win us over anyhow */
  4669. } else if (s[0] == '\n' && s[1] == '\n') {
  4670. len = (int)(s - buf) + 2;
  4671. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4672. len = (int)(s - buf) + 3;
  4673. }
  4674. return len;
  4675. }
  4676. #if !defined(NO_CACHING)
  4677. /* Convert month to the month number. Return -1 on error, or month number */
  4678. static int
  4679. get_month_index(const char *s)
  4680. {
  4681. size_t i;
  4682. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4683. if (!strcmp(s, month_names[i])) {
  4684. return (int)i;
  4685. }
  4686. }
  4687. return -1;
  4688. }
  4689. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4690. static time_t
  4691. parse_date_string(const char *datetime)
  4692. {
  4693. char month_str[32] = {0};
  4694. int second, minute, hour, day, month, year;
  4695. time_t result = (time_t)0;
  4696. struct tm tm;
  4697. if ((sscanf(datetime,
  4698. "%d/%3s/%d %d:%d:%d",
  4699. &day,
  4700. month_str,
  4701. &year,
  4702. &hour,
  4703. &minute,
  4704. &second) == 6) || (sscanf(datetime,
  4705. "%d %3s %d %d:%d:%d",
  4706. &day,
  4707. month_str,
  4708. &year,
  4709. &hour,
  4710. &minute,
  4711. &second) == 6)
  4712. || (sscanf(datetime,
  4713. "%*3s, %d %3s %d %d:%d:%d",
  4714. &day,
  4715. month_str,
  4716. &year,
  4717. &hour,
  4718. &minute,
  4719. &second) == 6) || (sscanf(datetime,
  4720. "%d-%3s-%d %d:%d:%d",
  4721. &day,
  4722. month_str,
  4723. &year,
  4724. &hour,
  4725. &minute,
  4726. &second) == 6)) {
  4727. month = get_month_index(month_str);
  4728. if ((month >= 0) && (year >= 1970)) {
  4729. memset(&tm, 0, sizeof(tm));
  4730. tm.tm_year = year - 1900;
  4731. tm.tm_mon = month;
  4732. tm.tm_mday = day;
  4733. tm.tm_hour = hour;
  4734. tm.tm_min = minute;
  4735. tm.tm_sec = second;
  4736. result = timegm(&tm);
  4737. }
  4738. }
  4739. return result;
  4740. }
  4741. #endif /* !NO_CACHING */
  4742. /* Protect against directory disclosure attack by removing '..',
  4743. * excessive '/' and '\' characters */
  4744. static void
  4745. remove_double_dots_and_double_slashes(char *s)
  4746. {
  4747. char *p = s;
  4748. while ((s[0] == '.') && (s[1] == '.')) {
  4749. s++;
  4750. }
  4751. while (*s != '\0') {
  4752. *p++ = *s++;
  4753. if (s[-1] == '/' || s[-1] == '\\') {
  4754. /* Skip all following slashes, backslashes and double-dots */
  4755. while (s[0] != '\0') {
  4756. if (s[0] == '/' || s[0] == '\\') {
  4757. s++;
  4758. } else if (s[0] == '.' && s[1] == '.') {
  4759. s += 2;
  4760. } else {
  4761. break;
  4762. }
  4763. }
  4764. }
  4765. }
  4766. *p = '\0';
  4767. }
  4768. static const struct {
  4769. const char *extension;
  4770. size_t ext_len;
  4771. const char *mime_type;
  4772. } builtin_mime_types[] = {
  4773. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4774. * application types */
  4775. {".doc", 4, "application/msword"},
  4776. {".eps", 4, "application/postscript"},
  4777. {".exe", 4, "application/octet-stream"},
  4778. {".js", 3, "application/javascript"},
  4779. {".json", 5, "application/json"},
  4780. {".pdf", 4, "application/pdf"},
  4781. {".ps", 3, "application/postscript"},
  4782. {".rtf", 4, "application/rtf"},
  4783. {".xhtml", 6, "application/xhtml+xml"},
  4784. {".xsl", 4, "application/xml"},
  4785. {".xslt", 5, "application/xml"},
  4786. /* fonts */
  4787. {".ttf", 4, "application/font-sfnt"},
  4788. {".cff", 4, "application/font-sfnt"},
  4789. {".otf", 4, "application/font-sfnt"},
  4790. {".aat", 4, "application/font-sfnt"},
  4791. {".sil", 4, "application/font-sfnt"},
  4792. {".pfr", 4, "application/font-tdpfr"},
  4793. {".woff", 5, "application/font-woff"},
  4794. /* audio */
  4795. {".mp3", 4, "audio/mpeg"},
  4796. {".oga", 4, "audio/ogg"},
  4797. {".ogg", 4, "audio/ogg"},
  4798. /* image */
  4799. {".gif", 4, "image/gif"},
  4800. {".ief", 4, "image/ief"},
  4801. {".jpeg", 5, "image/jpeg"},
  4802. {".jpg", 4, "image/jpeg"},
  4803. {".jpm", 4, "image/jpm"},
  4804. {".jpx", 4, "image/jpx"},
  4805. {".png", 4, "image/png"},
  4806. {".svg", 4, "image/svg+xml"},
  4807. {".tif", 4, "image/tiff"},
  4808. {".tiff", 5, "image/tiff"},
  4809. /* model */
  4810. {".wrl", 4, "model/vrml"},
  4811. /* text */
  4812. {".css", 4, "text/css"},
  4813. {".csv", 4, "text/csv"},
  4814. {".htm", 4, "text/html"},
  4815. {".html", 5, "text/html"},
  4816. {".sgm", 4, "text/sgml"},
  4817. {".shtm", 5, "text/html"},
  4818. {".shtml", 6, "text/html"},
  4819. {".txt", 4, "text/plain"},
  4820. {".xml", 4, "text/xml"},
  4821. /* video */
  4822. {".mov", 4, "video/quicktime"},
  4823. {".mp4", 4, "video/mp4"},
  4824. {".mpeg", 5, "video/mpeg"},
  4825. {".mpg", 4, "video/mpeg"},
  4826. {".ogv", 4, "video/ogg"},
  4827. {".qt", 3, "video/quicktime"},
  4828. /* not registered types
  4829. * (http://reference.sitepoint.com/html/mime-types-full,
  4830. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4831. {".arj", 4, "application/x-arj-compressed"},
  4832. {".gz", 3, "application/x-gunzip"},
  4833. {".rar", 4, "application/x-arj-compressed"},
  4834. {".swf", 4, "application/x-shockwave-flash"},
  4835. {".tar", 4, "application/x-tar"},
  4836. {".tgz", 4, "application/x-tar-gz"},
  4837. {".torrent", 8, "application/x-bittorrent"},
  4838. {".ppt", 4, "application/x-mspowerpoint"},
  4839. {".xls", 4, "application/x-msexcel"},
  4840. {".zip", 4, "application/x-zip-compressed"},
  4841. {".aac",
  4842. 4,
  4843. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4844. {".aif", 4, "audio/x-aif"},
  4845. {".m3u", 4, "audio/x-mpegurl"},
  4846. {".mid", 4, "audio/x-midi"},
  4847. {".ra", 3, "audio/x-pn-realaudio"},
  4848. {".ram", 4, "audio/x-pn-realaudio"},
  4849. {".wav", 4, "audio/x-wav"},
  4850. {".bmp", 4, "image/bmp"},
  4851. {".ico", 4, "image/x-icon"},
  4852. {".pct", 4, "image/x-pct"},
  4853. {".pict", 5, "image/pict"},
  4854. {".rgb", 4, "image/x-rgb"},
  4855. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4856. {".asf", 4, "video/x-ms-asf"},
  4857. {".avi", 4, "video/x-msvideo"},
  4858. {".m4v", 4, "video/x-m4v"},
  4859. {NULL, 0, NULL}};
  4860. const char *
  4861. mg_get_builtin_mime_type(const char *path)
  4862. {
  4863. const char *ext;
  4864. size_t i, path_len;
  4865. path_len = strlen(path);
  4866. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4867. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4868. if (path_len > builtin_mime_types[i].ext_len
  4869. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4870. return builtin_mime_types[i].mime_type;
  4871. }
  4872. }
  4873. return "text/plain";
  4874. }
  4875. /* Look at the "path" extension and figure what mime type it has.
  4876. * Store mime type in the vector. */
  4877. static void
  4878. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4879. {
  4880. struct vec ext_vec, mime_vec;
  4881. const char *list, *ext;
  4882. size_t path_len;
  4883. path_len = strlen(path);
  4884. if (ctx == NULL || vec == NULL) {
  4885. return;
  4886. }
  4887. /* Scan user-defined mime types first, in case user wants to
  4888. * override default mime types. */
  4889. list = ctx->config[EXTRA_MIME_TYPES];
  4890. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4891. /* ext now points to the path suffix */
  4892. ext = path + path_len - ext_vec.len;
  4893. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4894. *vec = mime_vec;
  4895. return;
  4896. }
  4897. }
  4898. vec->ptr = mg_get_builtin_mime_type(path);
  4899. vec->len = strlen(vec->ptr);
  4900. }
  4901. /* Stringify binary data. Output buffer must be twice as big as input,
  4902. * because each byte takes 2 bytes in string representation */
  4903. static void
  4904. bin2str(char *to, const unsigned char *p, size_t len)
  4905. {
  4906. static const char *hex = "0123456789abcdef";
  4907. for (; len--; p++) {
  4908. *to++ = hex[p[0] >> 4];
  4909. *to++ = hex[p[0] & 0x0f];
  4910. }
  4911. *to = '\0';
  4912. }
  4913. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4914. char *
  4915. mg_md5(char buf[33], ...)
  4916. {
  4917. md5_byte_t hash[16];
  4918. const char *p;
  4919. va_list ap;
  4920. md5_state_t ctx;
  4921. md5_init(&ctx);
  4922. va_start(ap, buf);
  4923. while ((p = va_arg(ap, const char *)) != NULL) {
  4924. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4925. }
  4926. va_end(ap);
  4927. md5_finish(&ctx, hash);
  4928. bin2str(buf, hash, sizeof(hash));
  4929. return buf;
  4930. }
  4931. /* Check the user's password, return 1 if OK */
  4932. static int
  4933. check_password(const char *method,
  4934. const char *ha1,
  4935. const char *uri,
  4936. const char *nonce,
  4937. const char *nc,
  4938. const char *cnonce,
  4939. const char *qop,
  4940. const char *response)
  4941. {
  4942. char ha2[32 + 1], expected_response[32 + 1];
  4943. /* Some of the parameters may be NULL */
  4944. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4945. || qop == NULL
  4946. || response == NULL) {
  4947. return 0;
  4948. }
  4949. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4950. if (strlen(response) != 32) {
  4951. return 0;
  4952. }
  4953. mg_md5(ha2, method, ":", uri, NULL);
  4954. mg_md5(expected_response,
  4955. ha1,
  4956. ":",
  4957. nonce,
  4958. ":",
  4959. nc,
  4960. ":",
  4961. cnonce,
  4962. ":",
  4963. qop,
  4964. ":",
  4965. ha2,
  4966. NULL);
  4967. return mg_strcasecmp(response, expected_response) == 0;
  4968. }
  4969. /* Use the global passwords file, if specified by auth_gpass option,
  4970. * or search for .htpasswd in the requested directory. */
  4971. static void
  4972. open_auth_file(struct mg_connection *conn,
  4973. const char *path,
  4974. struct mg_file *filep)
  4975. {
  4976. if (conn != NULL && conn->ctx != NULL) {
  4977. char name[PATH_MAX];
  4978. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4979. int truncated;
  4980. if (gpass != NULL) {
  4981. /* Use global passwords file */
  4982. if (!mg_fopen(conn, gpass, "r", filep)) {
  4983. #ifdef DEBUG
  4984. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4985. #endif
  4986. }
  4987. /* Important: using local struct mg_file to test path for
  4988. * is_directory
  4989. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4990. * was opened. TODO: mg_stat must not make anything appear to be
  4991. * opened */
  4992. } else if (mg_stat(conn, path, &filep->stat)
  4993. && filep->stat.is_directory) {
  4994. mg_snprintf(conn,
  4995. &truncated,
  4996. name,
  4997. sizeof(name),
  4998. "%s/%s",
  4999. path,
  5000. PASSWORDS_FILE_NAME);
  5001. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  5002. #ifdef DEBUG
  5003. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5004. #endif
  5005. }
  5006. } else {
  5007. /* Try to find .htpasswd in requested directory. */
  5008. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5009. if (e[0] == '/') {
  5010. break;
  5011. }
  5012. }
  5013. mg_snprintf(conn,
  5014. &truncated,
  5015. name,
  5016. sizeof(name),
  5017. "%.*s/%s",
  5018. (int)(e - p),
  5019. p,
  5020. PASSWORDS_FILE_NAME);
  5021. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  5022. #ifdef DEBUG
  5023. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5024. #endif
  5025. }
  5026. }
  5027. }
  5028. }
  5029. /* Parsed Authorization header */
  5030. struct ah {
  5031. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5032. };
  5033. /* Return 1 on success. Always initializes the ah structure. */
  5034. static int
  5035. parse_auth_header(struct mg_connection *conn,
  5036. char *buf,
  5037. size_t buf_size,
  5038. struct ah *ah)
  5039. {
  5040. char *name, *value, *s;
  5041. const char *auth_header;
  5042. uint64_t nonce;
  5043. if (!ah || !conn) {
  5044. return 0;
  5045. }
  5046. (void)memset(ah, 0, sizeof(*ah));
  5047. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5048. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5049. return 0;
  5050. }
  5051. /* Make modifiable copy of the auth header */
  5052. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5053. s = buf;
  5054. /* Parse authorization header */
  5055. for (;;) {
  5056. /* Gobble initial spaces */
  5057. while (isspace(*(unsigned char *)s)) {
  5058. s++;
  5059. }
  5060. name = skip_quoted(&s, "=", " ", 0);
  5061. /* Value is either quote-delimited, or ends at first comma or space. */
  5062. if (s[0] == '\"') {
  5063. s++;
  5064. value = skip_quoted(&s, "\"", " ", '\\');
  5065. if (s[0] == ',') {
  5066. s++;
  5067. }
  5068. } else {
  5069. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5070. * spaces */
  5071. }
  5072. if (*name == '\0') {
  5073. break;
  5074. }
  5075. if (!strcmp(name, "username")) {
  5076. ah->user = value;
  5077. } else if (!strcmp(name, "cnonce")) {
  5078. ah->cnonce = value;
  5079. } else if (!strcmp(name, "response")) {
  5080. ah->response = value;
  5081. } else if (!strcmp(name, "uri")) {
  5082. ah->uri = value;
  5083. } else if (!strcmp(name, "qop")) {
  5084. ah->qop = value;
  5085. } else if (!strcmp(name, "nc")) {
  5086. ah->nc = value;
  5087. } else if (!strcmp(name, "nonce")) {
  5088. ah->nonce = value;
  5089. }
  5090. }
  5091. #ifndef NO_NONCE_CHECK
  5092. /* Read the nonce from the response. */
  5093. if (ah->nonce == NULL) {
  5094. return 0;
  5095. }
  5096. s = NULL;
  5097. nonce = strtoull(ah->nonce, &s, 10);
  5098. if ((s == NULL) || (*s != 0)) {
  5099. return 0;
  5100. }
  5101. /* Convert the nonce from the client to a number. */
  5102. nonce ^= conn->ctx->auth_nonce_mask;
  5103. /* The converted number corresponds to the time the nounce has been
  5104. * created. This should not be earlier than the server start. */
  5105. /* Server side nonce check is valuable in all situations but one:
  5106. * if the server restarts frequently, but the client should not see
  5107. * that, so the server should accept nonces from previous starts. */
  5108. /* However, the reasonable default is to not accept a nonce from a
  5109. * previous start, so if anyone changed the access rights between
  5110. * two restarts, a new login is required. */
  5111. if (nonce < (uint64_t)conn->ctx->start_time) {
  5112. /* nonce is from a previous start of the server and no longer valid
  5113. * (replay attack?) */
  5114. return 0;
  5115. }
  5116. /* Check if the nonce is too high, so it has not (yet) been used by the
  5117. * server. */
  5118. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5119. return 0;
  5120. }
  5121. #else
  5122. (void)nonce;
  5123. #endif
  5124. /* CGI needs it as REMOTE_USER */
  5125. if (ah->user != NULL) {
  5126. conn->request_info.remote_user = mg_strdup(ah->user);
  5127. } else {
  5128. return 0;
  5129. }
  5130. return 1;
  5131. }
  5132. static const char *
  5133. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5134. {
  5135. const char *eof;
  5136. size_t len;
  5137. const char *memend;
  5138. if (!filep) {
  5139. return NULL;
  5140. }
  5141. if (filep->access.membuf != NULL && *p != NULL) {
  5142. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5143. /* Search for \n from p till the end of stream */
  5144. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5145. if (eof != NULL) {
  5146. eof += 1; /* Include \n */
  5147. } else {
  5148. eof = memend; /* Copy remaining data */
  5149. }
  5150. len =
  5151. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5152. memcpy(buf, *p, len);
  5153. buf[len] = '\0';
  5154. *p += len;
  5155. return len ? eof : NULL;
  5156. } else if (filep->access.fp != NULL) {
  5157. return fgets(buf, (int)size, filep->access.fp);
  5158. } else {
  5159. return NULL;
  5160. }
  5161. }
  5162. struct read_auth_file_struct {
  5163. struct mg_connection *conn;
  5164. struct ah ah;
  5165. char *domain;
  5166. char buf[256 + 256 + 40];
  5167. char *f_user;
  5168. char *f_domain;
  5169. char *f_ha1;
  5170. };
  5171. static int
  5172. read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata)
  5173. {
  5174. char *p;
  5175. int is_authorized = 0;
  5176. struct mg_file fp;
  5177. size_t l;
  5178. if (!filep || !workdata) {
  5179. return 0;
  5180. }
  5181. /* Loop over passwords file */
  5182. p = (char *)filep->access.membuf;
  5183. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5184. l = strlen(workdata->buf);
  5185. while (l > 0) {
  5186. if (isspace(workdata->buf[l - 1])
  5187. || iscntrl(workdata->buf[l - 1])) {
  5188. l--;
  5189. workdata->buf[l] = 0;
  5190. } else
  5191. break;
  5192. }
  5193. if (l < 1) {
  5194. continue;
  5195. }
  5196. workdata->f_user = workdata->buf;
  5197. if (workdata->f_user[0] == ':') {
  5198. /* user names may not contain a ':' and may not be empty,
  5199. * so lines starting with ':' may be used for a special purpose */
  5200. if (workdata->f_user[1] == '#') {
  5201. /* :# is a comment */
  5202. continue;
  5203. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5204. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  5205. is_authorized = read_auth_file(&fp, workdata);
  5206. (void)mg_fclose(
  5207. &fp.access); /* ignore error on read only file */
  5208. } else {
  5209. mg_cry(workdata->conn,
  5210. "%s: cannot open authorization file: %s",
  5211. __func__,
  5212. workdata->buf);
  5213. }
  5214. continue;
  5215. }
  5216. /* everything is invalid for the moment (might change in the
  5217. * future) */
  5218. mg_cry(workdata->conn,
  5219. "%s: syntax error in authorization file: %s",
  5220. __func__,
  5221. workdata->buf);
  5222. continue;
  5223. }
  5224. workdata->f_domain = strchr(workdata->f_user, ':');
  5225. if (workdata->f_domain == NULL) {
  5226. mg_cry(workdata->conn,
  5227. "%s: syntax error in authorization file: %s",
  5228. __func__,
  5229. workdata->buf);
  5230. continue;
  5231. }
  5232. *(workdata->f_domain) = 0;
  5233. (workdata->f_domain)++;
  5234. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5235. if (workdata->f_ha1 == NULL) {
  5236. mg_cry(workdata->conn,
  5237. "%s: syntax error in authorization file: %s",
  5238. __func__,
  5239. workdata->buf);
  5240. continue;
  5241. }
  5242. *(workdata->f_ha1) = 0;
  5243. (workdata->f_ha1)++;
  5244. if (!strcmp(workdata->ah.user, workdata->f_user)
  5245. && !strcmp(workdata->domain, workdata->f_domain)) {
  5246. return check_password(workdata->conn->request_info.request_method,
  5247. workdata->f_ha1,
  5248. workdata->ah.uri,
  5249. workdata->ah.nonce,
  5250. workdata->ah.nc,
  5251. workdata->ah.cnonce,
  5252. workdata->ah.qop,
  5253. workdata->ah.response);
  5254. }
  5255. }
  5256. return is_authorized;
  5257. }
  5258. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5259. static int
  5260. authorize(struct mg_connection *conn, struct mg_file *filep)
  5261. {
  5262. struct read_auth_file_struct workdata;
  5263. char buf[MG_BUF_LEN];
  5264. if (!conn || !conn->ctx) {
  5265. return 0;
  5266. }
  5267. memset(&workdata, 0, sizeof(workdata));
  5268. workdata.conn = conn;
  5269. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5270. return 0;
  5271. }
  5272. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5273. return read_auth_file(filep, &workdata);
  5274. }
  5275. /* Return 1 if request is authorised, 0 otherwise. */
  5276. static int
  5277. check_authorization(struct mg_connection *conn, const char *path)
  5278. {
  5279. char fname[PATH_MAX];
  5280. struct vec uri_vec, filename_vec;
  5281. const char *list;
  5282. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5283. int authorized = 1, truncated;
  5284. if (!conn || !conn->ctx) {
  5285. return 0;
  5286. }
  5287. list = conn->ctx->config[PROTECT_URI];
  5288. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5289. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5290. mg_snprintf(conn,
  5291. &truncated,
  5292. fname,
  5293. sizeof(fname),
  5294. "%.*s",
  5295. (int)filename_vec.len,
  5296. filename_vec.ptr);
  5297. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5298. mg_cry(conn,
  5299. "%s: cannot open %s: %s",
  5300. __func__,
  5301. fname,
  5302. strerror(errno));
  5303. }
  5304. break;
  5305. }
  5306. }
  5307. if (!is_file_opened(&file.access)) {
  5308. open_auth_file(conn, path, &file);
  5309. }
  5310. if (is_file_opened(&file.access)) {
  5311. authorized = authorize(conn, &file);
  5312. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5313. }
  5314. return authorized;
  5315. }
  5316. static void
  5317. send_authorization_request(struct mg_connection *conn)
  5318. {
  5319. char date[64];
  5320. time_t curtime = time(NULL);
  5321. if (conn && conn->ctx) {
  5322. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5323. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5324. nonce += conn->ctx->nonce_count;
  5325. ++conn->ctx->nonce_count;
  5326. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5327. nonce ^= conn->ctx->auth_nonce_mask;
  5328. conn->status_code = 401;
  5329. conn->must_close = 1;
  5330. gmt_time_string(date, sizeof(date), &curtime);
  5331. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5332. send_no_cache_header(conn);
  5333. mg_printf(conn,
  5334. "Date: %s\r\n"
  5335. "Connection: %s\r\n"
  5336. "Content-Length: 0\r\n"
  5337. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5338. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5339. date,
  5340. suggest_connection_header(conn),
  5341. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5342. nonce);
  5343. }
  5344. }
  5345. #if !defined(NO_FILES)
  5346. static int
  5347. is_authorized_for_put(struct mg_connection *conn)
  5348. {
  5349. if (conn) {
  5350. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5351. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5352. int ret = 0;
  5353. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5354. ret = authorize(conn, &file);
  5355. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5356. }
  5357. return ret;
  5358. }
  5359. return 0;
  5360. }
  5361. #endif
  5362. int
  5363. mg_modify_passwords_file(const char *fname,
  5364. const char *domain,
  5365. const char *user,
  5366. const char *pass)
  5367. {
  5368. int found, i;
  5369. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5370. FILE *fp, *fp2;
  5371. found = 0;
  5372. fp = fp2 = NULL;
  5373. /* Regard empty password as no password - remove user record. */
  5374. if (pass != NULL && pass[0] == '\0') {
  5375. pass = NULL;
  5376. }
  5377. /* Other arguments must not be empty */
  5378. if (fname == NULL || domain == NULL || user == NULL) {
  5379. return 0;
  5380. }
  5381. /* Using the given file format, user name and domain must not contain ':'
  5382. */
  5383. if (strchr(user, ':') != NULL) {
  5384. return 0;
  5385. }
  5386. if (strchr(domain, ':') != NULL) {
  5387. return 0;
  5388. }
  5389. /* Do not allow control characters like newline in user name and domain.
  5390. * Do not allow excessively long names either. */
  5391. for (i = 0; i < 255 && user[i] != 0; i++) {
  5392. if (iscntrl(user[i])) {
  5393. return 0;
  5394. }
  5395. }
  5396. if (user[i]) {
  5397. return 0;
  5398. }
  5399. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5400. if (iscntrl(domain[i])) {
  5401. return 0;
  5402. }
  5403. }
  5404. if (domain[i]) {
  5405. return 0;
  5406. }
  5407. /* The maximum length of the path to the password file is limited */
  5408. if ((strlen(fname) + 4) >= PATH_MAX) {
  5409. return 0;
  5410. }
  5411. /* Create a temporary file name. Length has been checked before. */
  5412. strcpy(tmp, fname);
  5413. strcat(tmp, ".tmp");
  5414. /* Create the file if does not exist */
  5415. /* Use of fopen here is OK, since fname is only ASCII */
  5416. if ((fp = fopen(fname, "a+")) != NULL) {
  5417. (void)fclose(fp);
  5418. }
  5419. /* Open the given file and temporary file */
  5420. if ((fp = fopen(fname, "r")) == NULL) {
  5421. return 0;
  5422. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5423. fclose(fp);
  5424. return 0;
  5425. }
  5426. /* Copy the stuff to temporary file */
  5427. while (fgets(line, sizeof(line), fp) != NULL) {
  5428. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5429. continue;
  5430. }
  5431. u[255] = 0;
  5432. d[255] = 0;
  5433. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5434. found++;
  5435. if (pass != NULL) {
  5436. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5437. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5438. }
  5439. } else {
  5440. fprintf(fp2, "%s", line);
  5441. }
  5442. }
  5443. /* If new user, just add it */
  5444. if (!found && pass != NULL) {
  5445. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5446. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5447. }
  5448. /* Close files */
  5449. fclose(fp);
  5450. fclose(fp2);
  5451. /* Put the temp file in place of real file */
  5452. IGNORE_UNUSED_RESULT(remove(fname));
  5453. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5454. return 1;
  5455. }
  5456. static int
  5457. is_valid_port(unsigned long port)
  5458. {
  5459. return port < 0xffff;
  5460. }
  5461. static int
  5462. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5463. {
  5464. struct addrinfo hints, *res, *ressave;
  5465. int func_ret = 0;
  5466. int gai_ret;
  5467. memset(&hints, 0, sizeof(struct addrinfo));
  5468. hints.ai_family = af;
  5469. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5470. if (gai_ret != 0) {
  5471. /* gai_strerror could be used to convert gai_ret to a string */
  5472. /* POSIX return values: see
  5473. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5474. */
  5475. /* Windows return values: see
  5476. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5477. */
  5478. return 0;
  5479. }
  5480. ressave = res;
  5481. while (res) {
  5482. if (dstlen >= res->ai_addrlen) {
  5483. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5484. func_ret = 1;
  5485. }
  5486. res = res->ai_next;
  5487. }
  5488. freeaddrinfo(ressave);
  5489. return func_ret;
  5490. }
  5491. static int
  5492. connect_socket(struct mg_context *ctx /* may be NULL */,
  5493. const char *host,
  5494. int port,
  5495. int use_ssl,
  5496. char *ebuf,
  5497. size_t ebuf_len,
  5498. SOCKET *sock /* output: socket, must not be NULL */,
  5499. union usa *sa /* output: socket address, must not be NULL */
  5500. )
  5501. {
  5502. int ip_ver = 0;
  5503. *sock = INVALID_SOCKET;
  5504. memset(sa, 0, sizeof(*sa));
  5505. if (ebuf_len > 0) {
  5506. *ebuf = 0;
  5507. }
  5508. if (host == NULL) {
  5509. mg_snprintf(NULL,
  5510. NULL, /* No truncation check for ebuf */
  5511. ebuf,
  5512. ebuf_len,
  5513. "%s",
  5514. "NULL host");
  5515. return 0;
  5516. }
  5517. if (port < 0 || !is_valid_port((unsigned)port)) {
  5518. mg_snprintf(NULL,
  5519. NULL, /* No truncation check for ebuf */
  5520. ebuf,
  5521. ebuf_len,
  5522. "%s",
  5523. "invalid port");
  5524. return 0;
  5525. }
  5526. #if !defined(NO_SSL)
  5527. if (use_ssl && (SSLv23_client_method == NULL)) {
  5528. mg_snprintf(NULL,
  5529. NULL, /* No truncation check for ebuf */
  5530. ebuf,
  5531. ebuf_len,
  5532. "%s",
  5533. "SSL is not initialized");
  5534. return 0;
  5535. }
  5536. #else
  5537. (void)use_ssl;
  5538. #endif
  5539. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5540. sa->sin.sin_port = htons((uint16_t)port);
  5541. ip_ver = 4;
  5542. #ifdef USE_IPV6
  5543. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5544. sa->sin6.sin6_port = htons((uint16_t)port);
  5545. ip_ver = 6;
  5546. } else if (host[0] == '[') {
  5547. /* While getaddrinfo on Windows will work with [::1],
  5548. * getaddrinfo on Linux only works with ::1 (without []). */
  5549. size_t l = strlen(host + 1);
  5550. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5551. if (h) {
  5552. h[l - 1] = 0;
  5553. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5554. sa->sin6.sin6_port = htons((uint16_t)port);
  5555. ip_ver = 6;
  5556. }
  5557. mg_free(h);
  5558. }
  5559. #endif
  5560. }
  5561. if (ip_ver == 0) {
  5562. mg_snprintf(NULL,
  5563. NULL, /* No truncation check for ebuf */
  5564. ebuf,
  5565. ebuf_len,
  5566. "%s",
  5567. "host not found");
  5568. return 0;
  5569. }
  5570. if (ip_ver == 4) {
  5571. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5572. }
  5573. #ifdef USE_IPV6
  5574. else if (ip_ver == 6) {
  5575. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5576. }
  5577. #endif
  5578. if (*sock == INVALID_SOCKET) {
  5579. mg_snprintf(NULL,
  5580. NULL, /* No truncation check for ebuf */
  5581. ebuf,
  5582. ebuf_len,
  5583. "socket(): %s",
  5584. strerror(ERRNO));
  5585. return 0;
  5586. }
  5587. set_close_on_exec(*sock, fc(ctx));
  5588. if ((ip_ver == 4)
  5589. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5590. == 0)) {
  5591. /* connected with IPv4 */
  5592. set_non_blocking_mode(*sock);
  5593. return 1;
  5594. }
  5595. #ifdef USE_IPV6
  5596. if ((ip_ver == 6)
  5597. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5598. == 0)) {
  5599. /* connected with IPv6 */
  5600. set_non_blocking_mode(*sock);
  5601. return 1;
  5602. }
  5603. #endif
  5604. /* Not connected */
  5605. mg_snprintf(NULL,
  5606. NULL, /* No truncation check for ebuf */
  5607. ebuf,
  5608. ebuf_len,
  5609. "connect(%s:%d): %s",
  5610. host,
  5611. port,
  5612. strerror(ERRNO));
  5613. closesocket(*sock);
  5614. *sock = INVALID_SOCKET;
  5615. return 0;
  5616. }
  5617. int
  5618. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5619. {
  5620. static const char *dont_escape = "._-$,;~()";
  5621. static const char *hex = "0123456789abcdef";
  5622. char *pos = dst;
  5623. const char *end = dst + dst_len - 1;
  5624. for (; *src != '\0' && pos < end; src++, pos++) {
  5625. if (isalnum(*(const unsigned char *)src)
  5626. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5627. *pos = *src;
  5628. } else if (pos + 2 < end) {
  5629. pos[0] = '%';
  5630. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5631. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5632. pos += 2;
  5633. } else {
  5634. break;
  5635. }
  5636. }
  5637. *pos = '\0';
  5638. return (*src == '\0') ? (int)(pos - dst) : -1;
  5639. }
  5640. static void
  5641. print_dir_entry(struct de *de)
  5642. {
  5643. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5644. struct tm *tm;
  5645. if (de->file.is_directory) {
  5646. mg_snprintf(de->conn,
  5647. NULL, /* Buffer is big enough */
  5648. size,
  5649. sizeof(size),
  5650. "%s",
  5651. "[DIRECTORY]");
  5652. } else {
  5653. /* We use (signed) cast below because MSVC 6 compiler cannot
  5654. * convert unsigned __int64 to double. Sigh. */
  5655. if (de->file.size < 1024) {
  5656. mg_snprintf(de->conn,
  5657. NULL, /* Buffer is big enough */
  5658. size,
  5659. sizeof(size),
  5660. "%d",
  5661. (int)de->file.size);
  5662. } else if (de->file.size < 0x100000) {
  5663. mg_snprintf(de->conn,
  5664. NULL, /* Buffer is big enough */
  5665. size,
  5666. sizeof(size),
  5667. "%.1fk",
  5668. (double)de->file.size / 1024.0);
  5669. } else if (de->file.size < 0x40000000) {
  5670. mg_snprintf(de->conn,
  5671. NULL, /* Buffer is big enough */
  5672. size,
  5673. sizeof(size),
  5674. "%.1fM",
  5675. (double)de->file.size / 1048576);
  5676. } else {
  5677. mg_snprintf(de->conn,
  5678. NULL, /* Buffer is big enough */
  5679. size,
  5680. sizeof(size),
  5681. "%.1fG",
  5682. (double)de->file.size / 1073741824);
  5683. }
  5684. }
  5685. /* Note: mg_snprintf will not cause a buffer overflow above.
  5686. * So, string truncation checks are not required here. */
  5687. tm = localtime(&de->file.last_modified);
  5688. if (tm != NULL) {
  5689. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5690. } else {
  5691. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5692. mod[sizeof(mod) - 1] = '\0';
  5693. }
  5694. mg_url_encode(de->file_name, href, sizeof(href));
  5695. de->conn->num_bytes_sent +=
  5696. mg_printf(de->conn,
  5697. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5698. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5699. de->conn->request_info.local_uri,
  5700. href,
  5701. de->file.is_directory ? "/" : "",
  5702. de->file_name,
  5703. de->file.is_directory ? "/" : "",
  5704. mod,
  5705. size);
  5706. }
  5707. /* This function is called from send_directory() and used for
  5708. * sorting directory entries by size, or name, or modification time.
  5709. * On windows, __cdecl specification is needed in case if project is built
  5710. * with __stdcall convention. qsort always requires __cdels callback. */
  5711. static int WINCDECL
  5712. compare_dir_entries(const void *p1, const void *p2)
  5713. {
  5714. if (p1 && p2) {
  5715. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5716. const char *query_string = a->conn->request_info.query_string;
  5717. int cmp_result = 0;
  5718. if (query_string == NULL) {
  5719. query_string = "na";
  5720. }
  5721. if (a->file.is_directory && !b->file.is_directory) {
  5722. return -1; /* Always put directories on top */
  5723. } else if (!a->file.is_directory && b->file.is_directory) {
  5724. return 1; /* Always put directories on top */
  5725. } else if (*query_string == 'n') {
  5726. cmp_result = strcmp(a->file_name, b->file_name);
  5727. } else if (*query_string == 's') {
  5728. cmp_result = (a->file.size == b->file.size)
  5729. ? 0
  5730. : ((a->file.size > b->file.size) ? 1 : -1);
  5731. } else if (*query_string == 'd') {
  5732. cmp_result =
  5733. (a->file.last_modified == b->file.last_modified)
  5734. ? 0
  5735. : ((a->file.last_modified > b->file.last_modified) ? 1
  5736. : -1);
  5737. }
  5738. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5739. }
  5740. return 0;
  5741. }
  5742. static int
  5743. must_hide_file(struct mg_connection *conn, const char *path)
  5744. {
  5745. if (conn && conn->ctx) {
  5746. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5747. const char *pattern = conn->ctx->config[HIDE_FILES];
  5748. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5749. || (pattern != NULL
  5750. && match_prefix(pattern, strlen(pattern), path) > 0);
  5751. }
  5752. return 0;
  5753. }
  5754. static int
  5755. scan_directory(struct mg_connection *conn,
  5756. const char *dir,
  5757. void *data,
  5758. void (*cb)(struct de *, void *))
  5759. {
  5760. char path[PATH_MAX];
  5761. struct dirent *dp;
  5762. DIR *dirp;
  5763. struct de de;
  5764. int truncated;
  5765. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5766. return 0;
  5767. } else {
  5768. de.conn = conn;
  5769. while ((dp = mg_readdir(dirp)) != NULL) {
  5770. /* Do not show current dir and hidden files */
  5771. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5772. || must_hide_file(conn, dp->d_name)) {
  5773. continue;
  5774. }
  5775. mg_snprintf(
  5776. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5777. /* If we don't memset stat structure to zero, mtime will have
  5778. * garbage and strftime() will segfault later on in
  5779. * print_dir_entry(). memset is required only if mg_stat()
  5780. * fails. For more details, see
  5781. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5782. memset(&de.file, 0, sizeof(de.file));
  5783. if (truncated) {
  5784. /* If the path is not complete, skip processing. */
  5785. continue;
  5786. }
  5787. if (!mg_stat(conn, path, &de.file)) {
  5788. mg_cry(conn,
  5789. "%s: mg_stat(%s) failed: %s",
  5790. __func__,
  5791. path,
  5792. strerror(ERRNO));
  5793. }
  5794. de.file_name = dp->d_name;
  5795. cb(&de, data);
  5796. }
  5797. (void)mg_closedir(dirp);
  5798. }
  5799. return 1;
  5800. }
  5801. #if !defined(NO_FILES)
  5802. static int
  5803. remove_directory(struct mg_connection *conn, const char *dir)
  5804. {
  5805. char path[PATH_MAX];
  5806. struct dirent *dp;
  5807. DIR *dirp;
  5808. struct de de;
  5809. int truncated;
  5810. int ok = 1;
  5811. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5812. return 0;
  5813. } else {
  5814. de.conn = conn;
  5815. while ((dp = mg_readdir(dirp)) != NULL) {
  5816. /* Do not show current dir (but show hidden files as they will
  5817. * also be removed) */
  5818. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5819. continue;
  5820. }
  5821. mg_snprintf(
  5822. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5823. /* If we don't memset stat structure to zero, mtime will have
  5824. * garbage and strftime() will segfault later on in
  5825. * print_dir_entry(). memset is required only if mg_stat()
  5826. * fails. For more details, see
  5827. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5828. memset(&de.file, 0, sizeof(de.file));
  5829. if (truncated) {
  5830. /* Do not delete anything shorter */
  5831. ok = 0;
  5832. continue;
  5833. }
  5834. if (!mg_stat(conn, path, &de.file)) {
  5835. mg_cry(conn,
  5836. "%s: mg_stat(%s) failed: %s",
  5837. __func__,
  5838. path,
  5839. strerror(ERRNO));
  5840. ok = 0;
  5841. }
  5842. if (de.file.is_directory) {
  5843. if (remove_directory(conn, path) == 0) {
  5844. ok = 0;
  5845. }
  5846. } else {
  5847. /* This will fail file is the file is in memory */
  5848. if (mg_remove(conn, path) == 0) {
  5849. ok = 0;
  5850. }
  5851. }
  5852. }
  5853. (void)mg_closedir(dirp);
  5854. IGNORE_UNUSED_RESULT(rmdir(dir));
  5855. }
  5856. return ok;
  5857. }
  5858. #endif
  5859. struct dir_scan_data {
  5860. struct de *entries;
  5861. unsigned int num_entries;
  5862. unsigned int arr_size;
  5863. };
  5864. /* Behaves like realloc(), but frees original pointer on failure */
  5865. static void *
  5866. realloc2(void *ptr, size_t size)
  5867. {
  5868. void *new_ptr = mg_realloc(ptr, size);
  5869. if (new_ptr == NULL) {
  5870. mg_free(ptr);
  5871. }
  5872. return new_ptr;
  5873. }
  5874. static void
  5875. dir_scan_callback(struct de *de, void *data)
  5876. {
  5877. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5878. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5879. dsd->arr_size *= 2;
  5880. dsd->entries =
  5881. (struct de *)realloc2(dsd->entries,
  5882. dsd->arr_size * sizeof(dsd->entries[0]));
  5883. }
  5884. if (dsd->entries == NULL) {
  5885. /* TODO(lsm, low): propagate an error to the caller */
  5886. dsd->num_entries = 0;
  5887. } else {
  5888. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5889. dsd->entries[dsd->num_entries].file = de->file;
  5890. dsd->entries[dsd->num_entries].conn = de->conn;
  5891. dsd->num_entries++;
  5892. }
  5893. }
  5894. static void
  5895. handle_directory_request(struct mg_connection *conn, const char *dir)
  5896. {
  5897. unsigned int i;
  5898. int sort_direction;
  5899. struct dir_scan_data data = {NULL, 0, 128};
  5900. char date[64];
  5901. time_t curtime = time(NULL);
  5902. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5903. send_http_error(conn,
  5904. 500,
  5905. "Error: Cannot open directory\nopendir(%s): %s",
  5906. dir,
  5907. strerror(ERRNO));
  5908. return;
  5909. }
  5910. gmt_time_string(date, sizeof(date), &curtime);
  5911. if (!conn) {
  5912. return;
  5913. }
  5914. sort_direction = ((conn->request_info.query_string != NULL)
  5915. && (conn->request_info.query_string[1] == 'd'))
  5916. ? 'a'
  5917. : 'd';
  5918. conn->must_close = 1;
  5919. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5920. send_static_cache_header(conn);
  5921. mg_printf(conn,
  5922. "Date: %s\r\n"
  5923. "Connection: close\r\n"
  5924. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5925. date);
  5926. conn->num_bytes_sent +=
  5927. mg_printf(conn,
  5928. "<html><head><title>Index of %s</title>"
  5929. "<style>th {text-align: left;}</style></head>"
  5930. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5931. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5932. "<th><a href=\"?d%c\">Modified</a></th>"
  5933. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5934. "<tr><td colspan=\"3\"><hr></td></tr>",
  5935. conn->request_info.local_uri,
  5936. conn->request_info.local_uri,
  5937. sort_direction,
  5938. sort_direction,
  5939. sort_direction);
  5940. /* Print first entry - link to a parent directory */
  5941. conn->num_bytes_sent +=
  5942. mg_printf(conn,
  5943. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5944. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5945. conn->request_info.local_uri,
  5946. "..",
  5947. "Parent directory",
  5948. "-",
  5949. "-");
  5950. /* Sort and print directory entries */
  5951. if (data.entries != NULL) {
  5952. qsort(data.entries,
  5953. (size_t)data.num_entries,
  5954. sizeof(data.entries[0]),
  5955. compare_dir_entries);
  5956. for (i = 0; i < data.num_entries; i++) {
  5957. print_dir_entry(&data.entries[i]);
  5958. mg_free(data.entries[i].file_name);
  5959. }
  5960. mg_free(data.entries);
  5961. }
  5962. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5963. conn->status_code = 200;
  5964. }
  5965. /* Send len bytes from the opened file to the client. */
  5966. static void
  5967. send_file_data(struct mg_connection *conn,
  5968. struct mg_file *filep,
  5969. int64_t offset,
  5970. int64_t len)
  5971. {
  5972. char buf[MG_BUF_LEN];
  5973. int to_read, num_read, num_written;
  5974. int64_t size;
  5975. if (!filep || !conn) {
  5976. return;
  5977. }
  5978. /* Sanity check the offset */
  5979. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  5980. : (int64_t)(filep->stat.size);
  5981. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5982. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  5983. /* file stored in memory */
  5984. if (len > size - offset) {
  5985. len = size - offset;
  5986. }
  5987. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  5988. } else if (len > 0 && filep->access.fp != NULL) {
  5989. /* file stored on disk */
  5990. #if defined(__linux__)
  5991. /* sendfile is only available for Linux */
  5992. if ((conn->ssl == 0) && (conn->throttle == 0)
  5993. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  5994. "yes"))) {
  5995. off_t sf_offs = (off_t)offset;
  5996. ssize_t sf_sent;
  5997. int sf_file = fileno(filep->access.fp);
  5998. int loop_cnt = 0;
  5999. do {
  6000. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6001. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6002. size_t sf_tosend =
  6003. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6004. sf_sent =
  6005. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6006. if (sf_sent > 0) {
  6007. conn->num_bytes_sent += sf_sent;
  6008. len -= sf_sent;
  6009. offset += sf_sent;
  6010. } else if (loop_cnt == 0) {
  6011. /* This file can not be sent using sendfile.
  6012. * This might be the case for pseudo-files in the
  6013. * /sys/ and /proc/ file system.
  6014. * Use the regular user mode copy code instead. */
  6015. break;
  6016. } else if (sf_sent == 0) {
  6017. /* No error, but 0 bytes sent. May be EOF? */
  6018. return;
  6019. }
  6020. loop_cnt++;
  6021. } while ((len > 0) && (sf_sent >= 0));
  6022. if (sf_sent > 0) {
  6023. return; /* OK */
  6024. }
  6025. /* sf_sent<0 means error, thus fall back to the classic way */
  6026. /* This is always the case, if sf_file is not a "normal" file,
  6027. * e.g., for sending data from the output of a CGI process. */
  6028. offset = (int64_t)sf_offs;
  6029. }
  6030. #endif
  6031. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6032. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6033. send_http_error(
  6034. conn,
  6035. 500,
  6036. "%s",
  6037. "Error: Unable to access file at requested position.");
  6038. } else {
  6039. while (len > 0) {
  6040. /* Calculate how much to read from the file in the buffer */
  6041. to_read = sizeof(buf);
  6042. if ((int64_t)to_read > len) {
  6043. to_read = (int)len;
  6044. }
  6045. /* Read from file, exit the loop on error */
  6046. if ((num_read =
  6047. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6048. <= 0) {
  6049. break;
  6050. }
  6051. /* Send read bytes to the client, exit the loop on error */
  6052. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6053. != num_read) {
  6054. break;
  6055. }
  6056. /* Both read and were successful, adjust counters */
  6057. conn->num_bytes_sent += num_written;
  6058. len -= num_written;
  6059. }
  6060. }
  6061. }
  6062. }
  6063. static int
  6064. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6065. {
  6066. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6067. }
  6068. static void
  6069. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6070. {
  6071. if (filestat != NULL && buf != NULL) {
  6072. mg_snprintf(NULL,
  6073. NULL, /* All calls to construct_etag use 64 byte buffer */
  6074. buf,
  6075. buf_len,
  6076. "\"%lx.%" INT64_FMT "\"",
  6077. (unsigned long)filestat->last_modified,
  6078. filestat->size);
  6079. }
  6080. }
  6081. static void
  6082. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6083. {
  6084. if (filep != NULL && filep->fp != NULL) {
  6085. #ifdef _WIN32
  6086. (void)conn; /* Unused. */
  6087. #else
  6088. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6089. mg_cry(conn,
  6090. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6091. __func__,
  6092. strerror(ERRNO));
  6093. }
  6094. #endif
  6095. }
  6096. }
  6097. static void
  6098. handle_static_file_request(struct mg_connection *conn,
  6099. const char *path,
  6100. struct mg_file *filep,
  6101. const char *mime_type,
  6102. const char *additional_headers)
  6103. {
  6104. char date[64], lm[64], etag[64];
  6105. char range[128]; /* large enough, so there will be no overflow */
  6106. const char *msg = "OK", *hdr;
  6107. time_t curtime = time(NULL);
  6108. int64_t cl, r1, r2;
  6109. struct vec mime_vec;
  6110. int n, truncated;
  6111. char gz_path[PATH_MAX];
  6112. const char *encoding = "";
  6113. const char *cors1, *cors2, *cors3;
  6114. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6115. return;
  6116. }
  6117. if (mime_type == NULL) {
  6118. get_mime_type(conn->ctx, path, &mime_vec);
  6119. } else {
  6120. mime_vec.ptr = mime_type;
  6121. mime_vec.len = strlen(mime_type);
  6122. }
  6123. if (filep->stat.size > INT64_MAX) {
  6124. send_http_error(conn,
  6125. 500,
  6126. "Error: File size is too large to send\n%" INT64_FMT,
  6127. filep->stat.size);
  6128. }
  6129. cl = (int64_t)filep->stat.size;
  6130. conn->status_code = 200;
  6131. range[0] = '\0';
  6132. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6133. * it's important to rewrite the filename after resolving
  6134. * the mime type from it, to preserve the actual file's type */
  6135. if (filep->stat.is_gzipped) {
  6136. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6137. if (truncated) {
  6138. send_http_error(conn,
  6139. 500,
  6140. "Error: Path of zipped file too long (%s)",
  6141. path);
  6142. return;
  6143. }
  6144. path = gz_path;
  6145. encoding = "Content-Encoding: gzip\r\n";
  6146. }
  6147. if (!mg_fopen(conn, path, "rb", filep)) {
  6148. send_http_error(conn,
  6149. 500,
  6150. "Error: Cannot open file\nfopen(%s): %s",
  6151. path,
  6152. strerror(ERRNO));
  6153. return;
  6154. }
  6155. fclose_on_exec(&filep->access, conn);
  6156. /* If Range: header specified, act accordingly */
  6157. r1 = r2 = 0;
  6158. hdr = mg_get_header(conn, "Range");
  6159. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6160. && r2 >= 0) {
  6161. /* actually, range requests don't play well with a pre-gzipped
  6162. * file (since the range is specified in the uncompressed space) */
  6163. if (filep->stat.is_gzipped) {
  6164. send_http_error(
  6165. conn,
  6166. 501,
  6167. "%s",
  6168. "Error: Range requests in gzipped files are not supported");
  6169. (void)mg_fclose(
  6170. &filep->access); /* ignore error on read only file */
  6171. return;
  6172. }
  6173. conn->status_code = 206;
  6174. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6175. mg_snprintf(conn,
  6176. NULL, /* range buffer is big enough */
  6177. range,
  6178. sizeof(range),
  6179. "Content-Range: bytes "
  6180. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6181. r1,
  6182. r1 + cl - 1,
  6183. filep->stat.size);
  6184. msg = "Partial Content";
  6185. }
  6186. hdr = mg_get_header(conn, "Origin");
  6187. if (hdr) {
  6188. /* Cross-origin resource sharing (CORS), see
  6189. * http://www.html5rocks.com/en/tutorials/cors/,
  6190. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6191. * preflight is not supported for files. */
  6192. cors1 = "Access-Control-Allow-Origin: ";
  6193. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6194. cors3 = "\r\n";
  6195. } else {
  6196. cors1 = cors2 = cors3 = "";
  6197. }
  6198. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6199. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6200. gmt_time_string(date, sizeof(date), &curtime);
  6201. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6202. construct_etag(etag, sizeof(etag), &filep->stat);
  6203. (void)mg_printf(conn,
  6204. "HTTP/1.1 %d %s\r\n"
  6205. "%s%s%s"
  6206. "Date: %s\r\n",
  6207. conn->status_code,
  6208. msg,
  6209. cors1,
  6210. cors2,
  6211. cors3,
  6212. date);
  6213. send_static_cache_header(conn);
  6214. (void)mg_printf(conn,
  6215. "Last-Modified: %s\r\n"
  6216. "Etag: %s\r\n"
  6217. "Content-Type: %.*s\r\n"
  6218. "Content-Length: %" INT64_FMT "\r\n"
  6219. "Connection: %s\r\n"
  6220. "Accept-Ranges: bytes\r\n"
  6221. "%s%s",
  6222. lm,
  6223. etag,
  6224. (int)mime_vec.len,
  6225. mime_vec.ptr,
  6226. cl,
  6227. suggest_connection_header(conn),
  6228. range,
  6229. encoding);
  6230. /* The previous code must not add any header starting with X- to make
  6231. * sure no one of the additional_headers is included twice */
  6232. if (additional_headers != NULL) {
  6233. (void)mg_printf(conn,
  6234. "%.*s\r\n\r\n",
  6235. (int)strlen(additional_headers),
  6236. additional_headers);
  6237. } else {
  6238. (void)mg_printf(conn, "\r\n");
  6239. }
  6240. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6241. send_file_data(conn, filep, r1, cl);
  6242. }
  6243. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6244. }
  6245. #if !defined(NO_CACHING)
  6246. static void
  6247. handle_not_modified_static_file_request(struct mg_connection *conn,
  6248. struct mg_file *filep)
  6249. {
  6250. char date[64], lm[64], etag[64];
  6251. time_t curtime = time(NULL);
  6252. if (conn == NULL || filep == NULL) {
  6253. return;
  6254. }
  6255. conn->status_code = 304;
  6256. gmt_time_string(date, sizeof(date), &curtime);
  6257. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6258. construct_etag(etag, sizeof(etag), &filep->stat);
  6259. (void)mg_printf(conn,
  6260. "HTTP/1.1 %d %s\r\n"
  6261. "Date: %s\r\n",
  6262. conn->status_code,
  6263. mg_get_response_code_text(conn, conn->status_code),
  6264. date);
  6265. send_static_cache_header(conn);
  6266. (void)mg_printf(conn,
  6267. "Last-Modified: %s\r\n"
  6268. "Etag: %s\r\n"
  6269. "Connection: %s\r\n"
  6270. "\r\n",
  6271. lm,
  6272. etag,
  6273. suggest_connection_header(conn));
  6274. }
  6275. #endif
  6276. void
  6277. mg_send_file(struct mg_connection *conn, const char *path)
  6278. {
  6279. mg_send_mime_file(conn, path, NULL);
  6280. }
  6281. void
  6282. mg_send_mime_file(struct mg_connection *conn,
  6283. const char *path,
  6284. const char *mime_type)
  6285. {
  6286. mg_send_mime_file2(conn, path, mime_type, NULL);
  6287. }
  6288. void
  6289. mg_send_mime_file2(struct mg_connection *conn,
  6290. const char *path,
  6291. const char *mime_type,
  6292. const char *additional_headers)
  6293. {
  6294. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6295. if (mg_stat(conn, path, &file.stat)) {
  6296. if (file.stat.is_directory) {
  6297. if (!conn) {
  6298. return;
  6299. }
  6300. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6301. "yes")) {
  6302. handle_directory_request(conn, path);
  6303. } else {
  6304. send_http_error(conn,
  6305. 403,
  6306. "%s",
  6307. "Error: Directory listing denied");
  6308. }
  6309. } else {
  6310. handle_static_file_request(
  6311. conn, path, &file, mime_type, additional_headers);
  6312. }
  6313. } else {
  6314. send_http_error(conn, 404, "%s", "Error: File not found");
  6315. }
  6316. }
  6317. /* For a given PUT path, create all intermediate subdirectories.
  6318. * Return 0 if the path itself is a directory.
  6319. * Return 1 if the path leads to a file.
  6320. * Return -1 for if the path is too long.
  6321. * Return -2 if path can not be created.
  6322. */
  6323. static int
  6324. put_dir(struct mg_connection *conn, const char *path)
  6325. {
  6326. char buf[PATH_MAX];
  6327. const char *s, *p;
  6328. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6329. size_t len;
  6330. int res = 1;
  6331. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6332. len = (size_t)(p - path);
  6333. if (len >= sizeof(buf)) {
  6334. /* path too long */
  6335. res = -1;
  6336. break;
  6337. }
  6338. memcpy(buf, path, len);
  6339. buf[len] = '\0';
  6340. /* Try to create intermediate directory */
  6341. DEBUG_TRACE("mkdir(%s)", buf);
  6342. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6343. /* path does not exixt and can not be created */
  6344. res = -2;
  6345. break;
  6346. }
  6347. /* Is path itself a directory? */
  6348. if (p[1] == '\0') {
  6349. res = 0;
  6350. }
  6351. }
  6352. return res;
  6353. }
  6354. static void
  6355. remove_bad_file(const struct mg_connection *conn, const char *path)
  6356. {
  6357. int r = mg_remove(conn, path);
  6358. if (r != 0) {
  6359. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6360. }
  6361. }
  6362. long long
  6363. mg_store_body(struct mg_connection *conn, const char *path)
  6364. {
  6365. char buf[MG_BUF_LEN];
  6366. long long len = 0;
  6367. int ret, n;
  6368. struct mg_file fi;
  6369. if (conn->consumed_content != 0) {
  6370. mg_cry(conn, "%s: Contents already consumed", __func__);
  6371. return -11;
  6372. }
  6373. ret = put_dir(conn, path);
  6374. if (ret < 0) {
  6375. /* -1 for path too long,
  6376. * -2 for path can not be created. */
  6377. return ret;
  6378. }
  6379. if (ret != 1) {
  6380. /* Return 0 means, path itself is a directory. */
  6381. return 0;
  6382. }
  6383. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6384. return -12;
  6385. }
  6386. ret = mg_read(conn, buf, sizeof(buf));
  6387. while (ret > 0) {
  6388. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6389. if (n != ret) {
  6390. (void)mg_fclose(
  6391. &fi.access); /* File is bad and will be removed anyway. */
  6392. remove_bad_file(conn, path);
  6393. return -13;
  6394. }
  6395. ret = mg_read(conn, buf, sizeof(buf));
  6396. }
  6397. /* File is open for writing. If fclose fails, there was probably an
  6398. * error flushing the buffer to disk, so the file on disk might be
  6399. * broken. Delete it and return an error to the caller. */
  6400. if (mg_fclose(&fi.access) != 0) {
  6401. remove_bad_file(conn, path);
  6402. return -14;
  6403. }
  6404. return len;
  6405. }
  6406. /* Parse HTTP headers from the given buffer, advance buf pointer
  6407. * to the point where parsing stopped.
  6408. * All parameters must be valid pointers (not NULL).
  6409. * Return <0 on error. */
  6410. static int
  6411. parse_http_headers(char **buf, struct mg_request_info *ri)
  6412. {
  6413. int i;
  6414. ri->num_headers = 0;
  6415. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6416. char *dp = *buf;
  6417. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6418. dp++;
  6419. }
  6420. if (dp == *buf) {
  6421. /* End of headers reached. */
  6422. break;
  6423. }
  6424. if (*dp != ':') {
  6425. /* This is not a valid field. */
  6426. return -1;
  6427. }
  6428. /* End of header key (*dp == ':') */
  6429. /* Truncate here and set the key name */
  6430. *dp = 0;
  6431. ri->http_headers[i].name = *buf;
  6432. do {
  6433. dp++;
  6434. } while (*dp == ' ');
  6435. /* The rest of the line is the value */
  6436. ri->http_headers[i].value = dp;
  6437. *buf = dp + strcspn(dp, "\r\n");
  6438. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6439. *buf = NULL;
  6440. }
  6441. ri->num_headers = i + 1;
  6442. if (*buf) {
  6443. (*buf)[0] = 0;
  6444. (*buf)[1] = 0;
  6445. *buf += 2;
  6446. } else {
  6447. *buf = dp;
  6448. break;
  6449. }
  6450. if ((*buf)[0] == '\r') {
  6451. /* This is the end of the header */
  6452. break;
  6453. }
  6454. }
  6455. return ri->num_headers;
  6456. }
  6457. static int
  6458. is_valid_http_method(const char *method)
  6459. {
  6460. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6461. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6462. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6463. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6464. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6465. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6466. /* TRACE method (RFC 2616) is not supported for security reasons */
  6467. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6468. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6469. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6470. /* Unsupported WEBDAV Methods: */
  6471. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6472. /* + 11 methods from RFC 3253 */
  6473. /* ORDERPATCH (RFC 3648) */
  6474. /* ACL (RFC 3744) */
  6475. /* SEARCH (RFC 5323) */
  6476. /* + MicroSoft extensions
  6477. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6478. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6479. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6480. }
  6481. /* Parse HTTP request, fill in mg_request_info structure.
  6482. * This function modifies the buffer by NUL-terminating
  6483. * HTTP request components, header names and header values.
  6484. * Parameters:
  6485. * buf (in/out): pointer to the HTTP header to parse and split
  6486. * len (in): length of HTTP header buffer
  6487. * re (out): parsed header as mg_request_info
  6488. * buf and ri must be valid pointers (not NULL), len>0.
  6489. * Returns <0 on error. */
  6490. static int
  6491. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6492. {
  6493. int is_request, request_length;
  6494. char *start_line;
  6495. request_length = get_request_len(buf, len);
  6496. if (request_length > 0) {
  6497. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6498. * remote_port */
  6499. ri->remote_user = ri->request_method = ri->request_uri =
  6500. ri->http_version = NULL;
  6501. ri->num_headers = 0;
  6502. buf[request_length - 1] = '\0';
  6503. /* RFC says that all initial whitespaces should be ingored */
  6504. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6505. buf++;
  6506. }
  6507. start_line = skip(&buf, "\r\n");
  6508. ri->request_method = skip(&start_line, " ");
  6509. ri->request_uri = skip(&start_line, " ");
  6510. ri->http_version = start_line;
  6511. /* HTTP message could be either HTTP request:
  6512. * "GET / HTTP/1.0 ..."
  6513. * or a HTTP response:
  6514. * "HTTP/1.0 200 OK ..."
  6515. * otherwise it is invalid.
  6516. */
  6517. is_request = is_valid_http_method(ri->request_method);
  6518. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6519. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6520. /* Not a valid request or response: invalid */
  6521. return -1;
  6522. }
  6523. if (is_request) {
  6524. ri->http_version += 5;
  6525. }
  6526. if (parse_http_headers(&buf, ri) < 0) {
  6527. /* Error while parsing headers */
  6528. return -1;
  6529. }
  6530. }
  6531. return request_length;
  6532. }
  6533. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6534. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6535. * buffer (which marks the end of HTTP request). Buffer buf may already
  6536. * have some data. The length of the data is stored in nread.
  6537. * Upon every read operation, increase nread by the number of bytes read. */
  6538. static int
  6539. read_request(FILE *fp,
  6540. struct mg_connection *conn,
  6541. char *buf,
  6542. int bufsiz,
  6543. int *nread)
  6544. {
  6545. int request_len, n = 0;
  6546. struct timespec last_action_time;
  6547. double request_timeout;
  6548. if (!conn) {
  6549. return 0;
  6550. }
  6551. memset(&last_action_time, 0, sizeof(last_action_time));
  6552. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6553. /* value of request_timeout is in seconds, config in milliseconds */
  6554. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6555. } else {
  6556. request_timeout = -1.0;
  6557. }
  6558. request_len = get_request_len(buf, *nread);
  6559. /* first time reading from this connection */
  6560. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6561. while (request_len == 0) {
  6562. /* Full request not yet received */
  6563. if (conn->ctx->stop_flag != 0) {
  6564. /* Server is to be stopped. */
  6565. return -1;
  6566. }
  6567. if (*nread >= bufsiz) {
  6568. /* Request too long */
  6569. return -2;
  6570. }
  6571. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6572. if (n < 0) {
  6573. /* Receive error */
  6574. return -1;
  6575. }
  6576. *nread += n;
  6577. request_len = get_request_len(buf, *nread);
  6578. if ((request_len == 0) && (request_timeout >= 0)) {
  6579. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6580. > request_timeout) {
  6581. /* Timeout */
  6582. return -1;
  6583. }
  6584. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6585. }
  6586. }
  6587. return request_len;
  6588. }
  6589. #if !defined(NO_FILES)
  6590. /* For given directory path, substitute it to valid index file.
  6591. * Return 1 if index file has been found, 0 if not found.
  6592. * If the file is found, it's stats is returned in stp. */
  6593. static int
  6594. substitute_index_file(struct mg_connection *conn,
  6595. char *path,
  6596. size_t path_len,
  6597. struct mg_file *filep)
  6598. {
  6599. if (conn && conn->ctx) {
  6600. const char *list = conn->ctx->config[INDEX_FILES];
  6601. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6602. struct vec filename_vec;
  6603. size_t n = strlen(path);
  6604. int found = 0;
  6605. /* The 'path' given to us points to the directory. Remove all trailing
  6606. * directory separator characters from the end of the path, and
  6607. * then append single directory separator character. */
  6608. while (n > 0 && path[n - 1] == '/') {
  6609. n--;
  6610. }
  6611. path[n] = '/';
  6612. /* Traverse index files list. For each entry, append it to the given
  6613. * path and see if the file exists. If it exists, break the loop */
  6614. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6615. /* Ignore too long entries that may overflow path buffer */
  6616. if (filename_vec.len > path_len - (n + 2)) {
  6617. continue;
  6618. }
  6619. /* Prepare full path to the index file */
  6620. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6621. /* Does it exist? */
  6622. if (mg_stat(conn, path, &file.stat)) {
  6623. /* Yes it does, break the loop */
  6624. *filep = file;
  6625. found = 1;
  6626. break;
  6627. }
  6628. }
  6629. /* If no index file exists, restore directory path */
  6630. if (!found) {
  6631. path[n] = '\0';
  6632. }
  6633. return found;
  6634. }
  6635. return 0;
  6636. }
  6637. #endif
  6638. #if !defined(NO_CACHING)
  6639. /* Return True if we should reply 304 Not Modified. */
  6640. static int
  6641. is_not_modified(const struct mg_connection *conn,
  6642. const struct mg_file_stat *filestat)
  6643. {
  6644. char etag[64];
  6645. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6646. const char *inm = mg_get_header(conn, "If-None-Match");
  6647. construct_etag(etag, sizeof(etag), filestat);
  6648. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6649. || ((ims != NULL)
  6650. && (filestat->last_modified <= parse_date_string(ims)));
  6651. }
  6652. #endif /* !NO_CACHING */
  6653. #if !defined(NO_CGI) || !defined(NO_FILES)
  6654. static int
  6655. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6656. {
  6657. const char *expect, *body;
  6658. char buf[MG_BUF_LEN];
  6659. int to_read, nread, success = 0;
  6660. int64_t buffered_len;
  6661. double timeout = -1.0;
  6662. if (!conn) {
  6663. return 0;
  6664. }
  6665. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6666. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6667. }
  6668. expect = mg_get_header(conn, "Expect");
  6669. /* assert(fp != NULL); */
  6670. if (!fp) {
  6671. send_http_error(conn, 500, "%s", "Error: NULL File");
  6672. return 0;
  6673. }
  6674. if (conn->content_len == -1 && !conn->is_chunked) {
  6675. /* Content length is not specified by the client. */
  6676. send_http_error(conn,
  6677. 411,
  6678. "%s",
  6679. "Error: Client did not specify content length");
  6680. } else if ((expect != NULL)
  6681. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6682. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6683. send_http_error(conn,
  6684. 417,
  6685. "Error: Can not fulfill expectation %s",
  6686. expect);
  6687. } else {
  6688. if (expect != NULL) {
  6689. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6690. conn->status_code = 100;
  6691. } else {
  6692. conn->status_code = 200;
  6693. }
  6694. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6695. - conn->consumed_content;
  6696. /* assert(buffered_len >= 0); */
  6697. /* assert(conn->consumed_content == 0); */
  6698. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6699. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6700. return 0;
  6701. }
  6702. if (buffered_len > 0) {
  6703. if ((int64_t)buffered_len > conn->content_len) {
  6704. buffered_len = (int)conn->content_len;
  6705. }
  6706. body = conn->buf + conn->request_len + conn->consumed_content;
  6707. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6708. conn->consumed_content += buffered_len;
  6709. }
  6710. nread = 0;
  6711. while (conn->consumed_content < conn->content_len) {
  6712. to_read = sizeof(buf);
  6713. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6714. to_read = (int)(conn->content_len - conn->consumed_content);
  6715. }
  6716. nread = pull(NULL, conn, buf, to_read, timeout);
  6717. if (nread <= 0
  6718. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6719. break;
  6720. }
  6721. conn->consumed_content += nread;
  6722. }
  6723. if (conn->consumed_content == conn->content_len) {
  6724. success = (nread >= 0);
  6725. }
  6726. /* Each error code path in this function must send an error */
  6727. if (!success) {
  6728. /* NOTE: Maybe some data has already been sent. */
  6729. /* TODO (low): If some data has been sent, a correct error
  6730. * reply can no longer be sent, so just close the connection */
  6731. send_http_error(conn, 500, "%s", "");
  6732. }
  6733. }
  6734. return success;
  6735. }
  6736. #endif
  6737. #if !defined(NO_CGI)
  6738. /* This structure helps to create an environment for the spawned CGI program.
  6739. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6740. * last element must be NULL.
  6741. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6742. * strings must reside in a contiguous buffer. The end of the buffer is
  6743. * marked by two '\0' characters.
  6744. * We satisfy both worlds: we create an envp array (which is vars), all
  6745. * entries are actually pointers inside buf. */
  6746. struct cgi_environment {
  6747. struct mg_connection *conn;
  6748. /* Data block */
  6749. char *buf; /* Environment buffer */
  6750. size_t buflen; /* Space available in buf */
  6751. size_t bufused; /* Space taken in buf */
  6752. /* Index block */
  6753. char **var; /* char **envp */
  6754. size_t varlen; /* Number of variables available in var */
  6755. size_t varused; /* Number of variables stored in var */
  6756. };
  6757. static void addenv(struct cgi_environment *env,
  6758. PRINTF_FORMAT_STRING(const char *fmt),
  6759. ...) PRINTF_ARGS(2, 3);
  6760. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6761. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6762. static void
  6763. addenv(struct cgi_environment *env, const char *fmt, ...)
  6764. {
  6765. size_t n, space;
  6766. int truncated = 0;
  6767. char *added;
  6768. va_list ap;
  6769. /* Calculate how much space is left in the buffer */
  6770. space = (env->buflen - env->bufused);
  6771. /* Calculate an estimate for the required space */
  6772. n = strlen(fmt) + 2 + 128;
  6773. do {
  6774. if (space <= n) {
  6775. /* Allocate new buffer */
  6776. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6777. added = (char *)mg_realloc(env->buf, n);
  6778. if (!added) {
  6779. /* Out of memory */
  6780. mg_cry(env->conn,
  6781. "%s: Cannot allocate memory for CGI variable [%s]",
  6782. __func__,
  6783. fmt);
  6784. return;
  6785. }
  6786. env->buf = added;
  6787. env->buflen = n;
  6788. space = (env->buflen - env->bufused);
  6789. }
  6790. /* Make a pointer to the free space int the buffer */
  6791. added = env->buf + env->bufused;
  6792. /* Copy VARIABLE=VALUE\0 string into the free space */
  6793. va_start(ap, fmt);
  6794. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6795. va_end(ap);
  6796. /* Do not add truncated strings to the environment */
  6797. if (truncated) {
  6798. /* Reallocate the buffer */
  6799. space = 0;
  6800. n = 1;
  6801. }
  6802. } while (truncated);
  6803. /* Calculate number of bytes added to the environment */
  6804. n = strlen(added) + 1;
  6805. env->bufused += n;
  6806. /* Now update the variable index */
  6807. space = (env->varlen - env->varused);
  6808. if (space < 2) {
  6809. mg_cry(env->conn,
  6810. "%s: Cannot register CGI variable [%s]",
  6811. __func__,
  6812. fmt);
  6813. return;
  6814. }
  6815. /* Append a pointer to the added string into the envp array */
  6816. env->var[env->varused] = added;
  6817. env->varused++;
  6818. }
  6819. static void
  6820. prepare_cgi_environment(struct mg_connection *conn,
  6821. const char *prog,
  6822. struct cgi_environment *env)
  6823. {
  6824. const char *s;
  6825. struct vec var_vec;
  6826. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6827. int i, truncated;
  6828. if (conn == NULL || prog == NULL || env == NULL) {
  6829. return;
  6830. }
  6831. env->conn = conn;
  6832. env->buflen = CGI_ENVIRONMENT_SIZE;
  6833. env->bufused = 0;
  6834. env->buf = (char *)mg_malloc(env->buflen);
  6835. env->varlen = MAX_CGI_ENVIR_VARS;
  6836. env->varused = 0;
  6837. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6838. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6839. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6840. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6841. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6842. /* Prepare the environment block */
  6843. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6844. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6845. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6846. #if defined(USE_IPV6)
  6847. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6848. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6849. } else
  6850. #endif
  6851. {
  6852. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6853. }
  6854. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6855. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6856. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6857. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6858. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6859. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6860. /* SCRIPT_NAME */
  6861. addenv(env,
  6862. "SCRIPT_NAME=%.*s",
  6863. (int)strlen(conn->request_info.local_uri)
  6864. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6865. conn->request_info.local_uri);
  6866. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6867. if (conn->path_info == NULL) {
  6868. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6869. } else {
  6870. addenv(env,
  6871. "PATH_TRANSLATED=%s%s",
  6872. conn->ctx->config[DOCUMENT_ROOT],
  6873. conn->path_info);
  6874. }
  6875. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6876. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6877. addenv(env, "CONTENT_TYPE=%s", s);
  6878. }
  6879. if (conn->request_info.query_string != NULL) {
  6880. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6881. }
  6882. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6883. addenv(env, "CONTENT_LENGTH=%s", s);
  6884. }
  6885. if ((s = getenv("PATH")) != NULL) {
  6886. addenv(env, "PATH=%s", s);
  6887. }
  6888. if (conn->path_info != NULL) {
  6889. addenv(env, "PATH_INFO=%s", conn->path_info);
  6890. }
  6891. if (conn->status_code > 0) {
  6892. /* CGI error handler should show the status code */
  6893. addenv(env, "STATUS=%d", conn->status_code);
  6894. }
  6895. #if defined(_WIN32)
  6896. if ((s = getenv("COMSPEC")) != NULL) {
  6897. addenv(env, "COMSPEC=%s", s);
  6898. }
  6899. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6900. addenv(env, "SYSTEMROOT=%s", s);
  6901. }
  6902. if ((s = getenv("SystemDrive")) != NULL) {
  6903. addenv(env, "SystemDrive=%s", s);
  6904. }
  6905. if ((s = getenv("ProgramFiles")) != NULL) {
  6906. addenv(env, "ProgramFiles=%s", s);
  6907. }
  6908. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6909. addenv(env, "ProgramFiles(x86)=%s", s);
  6910. }
  6911. #else
  6912. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6913. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6914. }
  6915. #endif /* _WIN32 */
  6916. if ((s = getenv("PERLLIB")) != NULL) {
  6917. addenv(env, "PERLLIB=%s", s);
  6918. }
  6919. if (conn->request_info.remote_user != NULL) {
  6920. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6921. addenv(env, "%s", "AUTH_TYPE=Digest");
  6922. }
  6923. /* Add all headers as HTTP_* variables */
  6924. for (i = 0; i < conn->request_info.num_headers; i++) {
  6925. (void)mg_snprintf(conn,
  6926. &truncated,
  6927. http_var_name,
  6928. sizeof(http_var_name),
  6929. "HTTP_%s",
  6930. conn->request_info.http_headers[i].name);
  6931. if (truncated) {
  6932. mg_cry(conn,
  6933. "%s: HTTP header variable too long [%s]",
  6934. __func__,
  6935. conn->request_info.http_headers[i].name);
  6936. continue;
  6937. }
  6938. /* Convert variable name into uppercase, and change - to _ */
  6939. for (p = http_var_name; *p != '\0'; p++) {
  6940. if (*p == '-') {
  6941. *p = '_';
  6942. }
  6943. *p = (char)toupper(*(unsigned char *)p);
  6944. }
  6945. addenv(env,
  6946. "%s=%s",
  6947. http_var_name,
  6948. conn->request_info.http_headers[i].value);
  6949. }
  6950. /* Add user-specified variables */
  6951. s = conn->ctx->config[CGI_ENVIRONMENT];
  6952. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6953. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6954. }
  6955. env->var[env->varused] = NULL;
  6956. env->buf[env->bufused] = '\0';
  6957. }
  6958. static void
  6959. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6960. {
  6961. char *buf;
  6962. size_t buflen;
  6963. int headers_len, data_len, i, truncated;
  6964. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6965. const char *status, *status_text, *connection_state;
  6966. char *pbuf, dir[PATH_MAX], *p;
  6967. struct mg_request_info ri;
  6968. struct cgi_environment blk;
  6969. FILE *in = NULL, *out = NULL, *err = NULL;
  6970. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  6971. pid_t pid = (pid_t)-1;
  6972. if (conn == NULL) {
  6973. return;
  6974. }
  6975. buf = NULL;
  6976. buflen = 16384;
  6977. prepare_cgi_environment(conn, prog, &blk);
  6978. /* CGI must be executed in its own directory. 'dir' must point to the
  6979. * directory containing executable program, 'p' must point to the
  6980. * executable program name relative to 'dir'. */
  6981. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6982. if (truncated) {
  6983. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6984. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6985. goto done;
  6986. }
  6987. if ((p = strrchr(dir, '/')) != NULL) {
  6988. *p++ = '\0';
  6989. } else {
  6990. dir[0] = '.', dir[1] = '\0';
  6991. p = (char *)prog;
  6992. }
  6993. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6994. status = strerror(ERRNO);
  6995. mg_cry(conn,
  6996. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6997. prog,
  6998. status);
  6999. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7000. goto done;
  7001. }
  7002. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7003. if (pid == (pid_t)-1) {
  7004. status = strerror(ERRNO);
  7005. mg_cry(conn,
  7006. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7007. prog,
  7008. status);
  7009. send_http_error(conn,
  7010. 500,
  7011. "Error: Cannot spawn CGI process [%s]: %s",
  7012. prog,
  7013. status);
  7014. goto done;
  7015. }
  7016. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7017. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7018. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7019. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7020. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7021. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7022. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7023. /* Parent closes only one side of the pipes.
  7024. * If we don't mark them as closed, close() attempt before
  7025. * return from this function throws an exception on Windows.
  7026. * Windows does not like when closed descriptor is closed again. */
  7027. (void)close(fdin[0]);
  7028. (void)close(fdout[1]);
  7029. (void)close(fderr[1]);
  7030. fdin[0] = fdout[1] = fderr[1] = -1;
  7031. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7032. status = strerror(ERRNO);
  7033. mg_cry(conn,
  7034. "Error: CGI program \"%s\": Can not open stdin: %s",
  7035. prog,
  7036. status);
  7037. send_http_error(conn,
  7038. 500,
  7039. "Error: CGI can not open fdin\nfopen: %s",
  7040. status);
  7041. goto done;
  7042. }
  7043. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7044. status = strerror(ERRNO);
  7045. mg_cry(conn,
  7046. "Error: CGI program \"%s\": Can not open stdout: %s",
  7047. prog,
  7048. status);
  7049. send_http_error(conn,
  7050. 500,
  7051. "Error: CGI can not open fdout\nfopen: %s",
  7052. status);
  7053. goto done;
  7054. }
  7055. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7056. status = strerror(ERRNO);
  7057. mg_cry(conn,
  7058. "Error: CGI program \"%s\": Can not open stderr: %s",
  7059. prog,
  7060. status);
  7061. send_http_error(conn,
  7062. 500,
  7063. "Error: CGI can not open fdout\nfopen: %s",
  7064. status);
  7065. goto done;
  7066. }
  7067. setbuf(in, NULL);
  7068. setbuf(out, NULL);
  7069. setbuf(err, NULL);
  7070. fout.access.fp = out;
  7071. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7072. /* This is a POST/PUT request, or another request with body data. */
  7073. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7074. /* Error sending the body data */
  7075. mg_cry(conn,
  7076. "Error: CGI program \"%s\": Forward body data failed",
  7077. prog);
  7078. goto done;
  7079. }
  7080. }
  7081. /* Close so child gets an EOF. */
  7082. fclose(in);
  7083. in = NULL;
  7084. fdin[1] = -1;
  7085. /* Now read CGI reply into a buffer. We need to set correct
  7086. * status code, thus we need to see all HTTP headers first.
  7087. * Do not send anything back to client, until we buffer in all
  7088. * HTTP headers. */
  7089. data_len = 0;
  7090. buf = (char *)mg_malloc(buflen);
  7091. if (buf == NULL) {
  7092. send_http_error(conn,
  7093. 500,
  7094. "Error: Not enough memory for CGI buffer (%u bytes)",
  7095. (unsigned int)buflen);
  7096. mg_cry(conn,
  7097. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7098. "bytes)",
  7099. prog,
  7100. (unsigned int)buflen);
  7101. goto done;
  7102. }
  7103. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7104. if (headers_len <= 0) {
  7105. /* Could not parse the CGI response. Check if some error message on
  7106. * stderr. */
  7107. i = pull_all(err, conn, buf, (int)buflen);
  7108. if (i > 0) {
  7109. mg_cry(conn,
  7110. "Error: CGI program \"%s\" sent error "
  7111. "message: [%.*s]",
  7112. prog,
  7113. i,
  7114. buf);
  7115. send_http_error(conn,
  7116. 500,
  7117. "Error: CGI program \"%s\" sent error "
  7118. "message: [%.*s]",
  7119. prog,
  7120. i,
  7121. buf);
  7122. } else {
  7123. mg_cry(conn,
  7124. "Error: CGI program sent malformed or too big "
  7125. "(>%u bytes) HTTP headers: [%.*s]",
  7126. (unsigned)buflen,
  7127. data_len,
  7128. buf);
  7129. send_http_error(conn,
  7130. 500,
  7131. "Error: CGI program sent malformed or too big "
  7132. "(>%u bytes) HTTP headers: [%.*s]",
  7133. (unsigned)buflen,
  7134. data_len,
  7135. buf);
  7136. }
  7137. goto done;
  7138. }
  7139. pbuf = buf;
  7140. buf[headers_len - 1] = '\0';
  7141. parse_http_headers(&pbuf, &ri);
  7142. /* Make up and send the status line */
  7143. status_text = "OK";
  7144. if ((status = get_header(&ri, "Status")) != NULL) {
  7145. conn->status_code = atoi(status);
  7146. status_text = status;
  7147. while (isdigit(*(const unsigned char *)status_text)
  7148. || *status_text == ' ') {
  7149. status_text++;
  7150. }
  7151. } else if (get_header(&ri, "Location") != NULL) {
  7152. conn->status_code = 302;
  7153. } else {
  7154. conn->status_code = 200;
  7155. }
  7156. connection_state = get_header(&ri, "Connection");
  7157. if (!header_has_option(connection_state, "keep-alive")) {
  7158. conn->must_close = 1;
  7159. }
  7160. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7161. /* Send headers */
  7162. for (i = 0; i < ri.num_headers; i++) {
  7163. mg_printf(conn,
  7164. "%s: %s\r\n",
  7165. ri.http_headers[i].name,
  7166. ri.http_headers[i].value);
  7167. }
  7168. mg_write(conn, "\r\n", 2);
  7169. /* Send chunk of data that may have been read after the headers */
  7170. conn->num_bytes_sent +=
  7171. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7172. /* Read the rest of CGI output and send to the client */
  7173. send_file_data(conn, &fout, 0, INT64_MAX);
  7174. done:
  7175. mg_free(blk.var);
  7176. mg_free(blk.buf);
  7177. if (pid != (pid_t)-1) {
  7178. kill(pid, SIGKILL);
  7179. #if !defined(_WIN32)
  7180. {
  7181. int st;
  7182. while (waitpid(pid, &st, 0) != -1)
  7183. ; /* clean zombies */
  7184. }
  7185. #endif
  7186. }
  7187. if (fdin[0] != -1) {
  7188. close(fdin[0]);
  7189. }
  7190. if (fdout[1] != -1) {
  7191. close(fdout[1]);
  7192. }
  7193. if (in != NULL) {
  7194. fclose(in);
  7195. } else if (fdin[1] != -1) {
  7196. close(fdin[1]);
  7197. }
  7198. if (out != NULL) {
  7199. fclose(out);
  7200. } else if (fdout[0] != -1) {
  7201. close(fdout[0]);
  7202. }
  7203. if (err != NULL) {
  7204. fclose(err);
  7205. } else if (fderr[0] != -1) {
  7206. close(fderr[0]);
  7207. }
  7208. if (buf != NULL) {
  7209. mg_free(buf);
  7210. }
  7211. }
  7212. #endif /* !NO_CGI */
  7213. #if !defined(NO_FILES)
  7214. static void
  7215. mkcol(struct mg_connection *conn, const char *path)
  7216. {
  7217. int rc, body_len;
  7218. struct de de;
  7219. char date[64];
  7220. time_t curtime = time(NULL);
  7221. if (conn == NULL) {
  7222. return;
  7223. }
  7224. /* TODO (mid): Check the send_http_error situations in this function */
  7225. memset(&de.file, 0, sizeof(de.file));
  7226. if (!mg_stat(conn, path, &de.file)) {
  7227. mg_cry(conn,
  7228. "%s: mg_stat(%s) failed: %s",
  7229. __func__,
  7230. path,
  7231. strerror(ERRNO));
  7232. }
  7233. if (de.file.last_modified) {
  7234. /* TODO (high): This check does not seem to make any sense ! */
  7235. send_http_error(
  7236. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7237. return;
  7238. }
  7239. body_len = conn->data_len - conn->request_len;
  7240. if (body_len > 0) {
  7241. send_http_error(
  7242. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7243. return;
  7244. }
  7245. rc = mg_mkdir(conn, path, 0755);
  7246. if (rc == 0) {
  7247. conn->status_code = 201;
  7248. gmt_time_string(date, sizeof(date), &curtime);
  7249. mg_printf(conn,
  7250. "HTTP/1.1 %d Created\r\n"
  7251. "Date: %s\r\n",
  7252. conn->status_code,
  7253. date);
  7254. send_static_cache_header(conn);
  7255. mg_printf(conn,
  7256. "Content-Length: 0\r\n"
  7257. "Connection: %s\r\n\r\n",
  7258. suggest_connection_header(conn));
  7259. } else if (rc == -1) {
  7260. if (errno == EEXIST) {
  7261. send_http_error(
  7262. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7263. } else if (errno == EACCES) {
  7264. send_http_error(
  7265. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7266. } else if (errno == ENOENT) {
  7267. send_http_error(
  7268. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7269. } else {
  7270. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7271. }
  7272. }
  7273. }
  7274. static void
  7275. put_file(struct mg_connection *conn, const char *path)
  7276. {
  7277. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7278. const char *range;
  7279. int64_t r1, r2;
  7280. int rc;
  7281. char date[64];
  7282. time_t curtime = time(NULL);
  7283. if (conn == NULL) {
  7284. return;
  7285. }
  7286. if (mg_stat(conn, path, &file.stat)) {
  7287. /* File already exists */
  7288. conn->status_code = 200;
  7289. if (file.stat.is_directory) {
  7290. /* This is an already existing directory,
  7291. * so there is nothing to do for the server. */
  7292. rc = 0;
  7293. } else {
  7294. /* File exists and is not a directory. */
  7295. /* Can it be replaced? */
  7296. if (file.access.membuf != NULL) {
  7297. /* This is an "in-memory" file, that can not be replaced */
  7298. send_http_error(
  7299. conn,
  7300. 405,
  7301. "Error: Put not possible\nReplacing %s is not supported",
  7302. path);
  7303. return;
  7304. }
  7305. /* Check if the server may write this file */
  7306. if (access(path, W_OK) == 0) {
  7307. /* Access granted */
  7308. conn->status_code = 200;
  7309. rc = 1;
  7310. } else {
  7311. send_http_error(
  7312. conn,
  7313. 403,
  7314. "Error: Put not possible\nReplacing %s is not allowed",
  7315. path);
  7316. return;
  7317. }
  7318. }
  7319. } else {
  7320. /* File should be created */
  7321. conn->status_code = 201;
  7322. rc = put_dir(conn, path);
  7323. }
  7324. if (rc == 0) {
  7325. /* put_dir returns 0 if path is a directory */
  7326. gmt_time_string(date, sizeof(date), &curtime);
  7327. mg_printf(conn,
  7328. "HTTP/1.1 %d %s\r\n",
  7329. conn->status_code,
  7330. mg_get_response_code_text(NULL, conn->status_code));
  7331. send_no_cache_header(conn);
  7332. mg_printf(conn,
  7333. "Date: %s\r\n"
  7334. "Content-Length: 0\r\n"
  7335. "Connection: %s\r\n\r\n",
  7336. date,
  7337. suggest_connection_header(conn));
  7338. /* Request to create a directory has been fulfilled successfully.
  7339. * No need to put a file. */
  7340. return;
  7341. }
  7342. if (rc == -1) {
  7343. /* put_dir returns -1 if the path is too long */
  7344. send_http_error(conn,
  7345. 414,
  7346. "Error: Path too long\nput_dir(%s): %s",
  7347. path,
  7348. strerror(ERRNO));
  7349. return;
  7350. }
  7351. if (rc == -2) {
  7352. /* put_dir returns -2 if the directory can not be created */
  7353. send_http_error(conn,
  7354. 500,
  7355. "Error: Can not create directory\nput_dir(%s): %s",
  7356. path,
  7357. strerror(ERRNO));
  7358. return;
  7359. }
  7360. /* A file should be created or overwritten. */
  7361. if (!mg_fopen(conn, path, "wb+", &file) || file.access.fp == NULL) {
  7362. (void)mg_fclose(&file.access);
  7363. send_http_error(conn,
  7364. 500,
  7365. "Error: Can not create file\nfopen(%s): %s",
  7366. path,
  7367. strerror(ERRNO));
  7368. return;
  7369. }
  7370. fclose_on_exec(&file.access, conn);
  7371. range = mg_get_header(conn, "Content-Range");
  7372. r1 = r2 = 0;
  7373. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7374. conn->status_code = 206; /* Partial content */
  7375. fseeko(file.access.fp, r1, SEEK_SET);
  7376. }
  7377. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7378. /* forward_body_data failed.
  7379. * The error code has already been sent to the client,
  7380. * and conn->status_code is already set. */
  7381. (void)mg_fclose(&file.access);
  7382. return;
  7383. }
  7384. if (mg_fclose(&file.access) != 0) {
  7385. /* fclose failed. This might have different reasons, but a likely
  7386. * one is "no space on disk", http 507. */
  7387. conn->status_code = 507;
  7388. }
  7389. gmt_time_string(date, sizeof(date), &curtime);
  7390. mg_printf(conn,
  7391. "HTTP/1.1 %d %s\r\n",
  7392. conn->status_code,
  7393. mg_get_response_code_text(NULL, conn->status_code));
  7394. send_no_cache_header(conn);
  7395. mg_printf(conn,
  7396. "Date: %s\r\n"
  7397. "Content-Length: 0\r\n"
  7398. "Connection: %s\r\n\r\n",
  7399. date,
  7400. suggest_connection_header(conn));
  7401. }
  7402. static void
  7403. delete_file(struct mg_connection *conn, const char *path)
  7404. {
  7405. struct de de;
  7406. memset(&de.file, 0, sizeof(de.file));
  7407. if (!mg_stat(conn, path, &de.file)) {
  7408. /* mg_stat returns 0 if the file does not exist */
  7409. send_http_error(conn,
  7410. 404,
  7411. "Error: Cannot delete file\nFile %s not found",
  7412. path);
  7413. return;
  7414. }
  7415. #if 0 /* Ignore if a file in memory is inside a folder */
  7416. if (de.access.membuf != NULL) {
  7417. /* the file is cached in memory */
  7418. send_http_error(
  7419. conn,
  7420. 405,
  7421. "Error: Delete not possible\nDeleting %s is not supported",
  7422. path);
  7423. return;
  7424. }
  7425. #endif
  7426. if (de.file.is_directory) {
  7427. if (remove_directory(conn, path)) {
  7428. /* Delete is successful: Return 204 without content. */
  7429. send_http_error(conn, 204, "%s", "");
  7430. } else {
  7431. /* Delete is not successful: Return 500 (Server error). */
  7432. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7433. }
  7434. return;
  7435. }
  7436. /* This is an existing file (not a directory).
  7437. * Check if write permission is granted. */
  7438. if (access(path, W_OK) != 0) {
  7439. /* File is read only */
  7440. send_http_error(
  7441. conn,
  7442. 403,
  7443. "Error: Delete not possible\nDeleting %s is not allowed",
  7444. path);
  7445. return;
  7446. }
  7447. /* Try to delete it. */
  7448. if (mg_remove(conn, path) == 0) {
  7449. /* Delete was successful: Return 204 without content. */
  7450. send_http_error(conn, 204, "%s", "");
  7451. } else {
  7452. /* Delete not successful (file locked). */
  7453. send_http_error(conn,
  7454. 423,
  7455. "Error: Cannot delete file\nremove(%s): %s",
  7456. path,
  7457. strerror(ERRNO));
  7458. }
  7459. }
  7460. #endif /* !NO_FILES */
  7461. static void
  7462. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7463. static void
  7464. do_ssi_include(struct mg_connection *conn,
  7465. const char *ssi,
  7466. char *tag,
  7467. int include_level)
  7468. {
  7469. char file_name[MG_BUF_LEN], path[512], *p;
  7470. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7471. size_t len;
  7472. int truncated = 0;
  7473. if (conn == NULL) {
  7474. return;
  7475. }
  7476. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7477. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7478. * always < MG_BUF_LEN. */
  7479. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7480. /* File name is relative to the webserver root */
  7481. file_name[511] = 0;
  7482. (void)mg_snprintf(conn,
  7483. &truncated,
  7484. path,
  7485. sizeof(path),
  7486. "%s/%s",
  7487. conn->ctx->config[DOCUMENT_ROOT],
  7488. file_name);
  7489. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7490. /* File name is relative to the webserver working directory
  7491. * or it is absolute system path */
  7492. file_name[511] = 0;
  7493. (void)
  7494. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7495. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7496. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7497. /* File name is relative to the currect document */
  7498. file_name[511] = 0;
  7499. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7500. if (!truncated) {
  7501. if ((p = strrchr(path, '/')) != NULL) {
  7502. p[1] = '\0';
  7503. }
  7504. len = strlen(path);
  7505. (void)mg_snprintf(conn,
  7506. &truncated,
  7507. path + len,
  7508. sizeof(path) - len,
  7509. "%s",
  7510. file_name);
  7511. }
  7512. } else {
  7513. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7514. return;
  7515. }
  7516. if (truncated) {
  7517. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7518. return;
  7519. }
  7520. if (!mg_fopen(conn, path, "rb", &file)) {
  7521. mg_cry(conn,
  7522. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7523. tag,
  7524. path,
  7525. strerror(ERRNO));
  7526. } else {
  7527. fclose_on_exec(&file.access, conn);
  7528. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7529. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7530. path) > 0) {
  7531. send_ssi_file(conn, path, &file, include_level + 1);
  7532. } else {
  7533. send_file_data(conn, &file, 0, INT64_MAX);
  7534. }
  7535. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7536. }
  7537. }
  7538. #if !defined(NO_POPEN)
  7539. static void
  7540. do_ssi_exec(struct mg_connection *conn, char *tag)
  7541. {
  7542. char cmd[1024] = "";
  7543. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7544. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7545. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7546. } else {
  7547. cmd[1023] = 0;
  7548. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7549. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7550. } else {
  7551. send_file_data(conn, &file, 0, INT64_MAX);
  7552. pclose(file.access.fp);
  7553. }
  7554. }
  7555. }
  7556. #endif /* !NO_POPEN */
  7557. static int
  7558. mg_fgetc(struct mg_file *filep, int offset)
  7559. {
  7560. if (filep == NULL) {
  7561. return EOF;
  7562. }
  7563. if (filep->access.membuf != NULL && offset >= 0
  7564. && ((unsigned int)(offset)) < filep->stat.size) {
  7565. return ((const unsigned char *)filep->access.membuf)[offset];
  7566. } else if (filep->access.fp != NULL) {
  7567. return fgetc(filep->access.fp);
  7568. } else {
  7569. return EOF;
  7570. }
  7571. }
  7572. static void
  7573. send_ssi_file(struct mg_connection *conn,
  7574. const char *path,
  7575. struct mg_file *filep,
  7576. int include_level)
  7577. {
  7578. char buf[MG_BUF_LEN];
  7579. int ch, offset, len, in_ssi_tag;
  7580. if (include_level > 10) {
  7581. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7582. return;
  7583. }
  7584. in_ssi_tag = len = offset = 0;
  7585. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7586. if (in_ssi_tag && ch == '>') {
  7587. in_ssi_tag = 0;
  7588. buf[len++] = (char)ch;
  7589. buf[len] = '\0';
  7590. /* assert(len <= (int) sizeof(buf)); */
  7591. if (len > (int)sizeof(buf)) {
  7592. break;
  7593. }
  7594. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7595. /* Not an SSI tag, pass it */
  7596. (void)mg_write(conn, buf, (size_t)len);
  7597. } else {
  7598. if (!memcmp(buf + 5, "include", 7)) {
  7599. do_ssi_include(conn, path, buf + 12, include_level);
  7600. #if !defined(NO_POPEN)
  7601. } else if (!memcmp(buf + 5, "exec", 4)) {
  7602. do_ssi_exec(conn, buf + 9);
  7603. #endif /* !NO_POPEN */
  7604. } else {
  7605. mg_cry(conn,
  7606. "%s: unknown SSI "
  7607. "command: \"%s\"",
  7608. path,
  7609. buf);
  7610. }
  7611. }
  7612. len = 0;
  7613. } else if (in_ssi_tag) {
  7614. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7615. /* Not an SSI tag */
  7616. in_ssi_tag = 0;
  7617. } else if (len == (int)sizeof(buf) - 2) {
  7618. mg_cry(conn, "%s: SSI tag is too large", path);
  7619. len = 0;
  7620. }
  7621. buf[len++] = (char)(ch & 0xff);
  7622. } else if (ch == '<') {
  7623. in_ssi_tag = 1;
  7624. if (len > 0) {
  7625. mg_write(conn, buf, (size_t)len);
  7626. }
  7627. len = 0;
  7628. buf[len++] = (char)(ch & 0xff);
  7629. } else {
  7630. buf[len++] = (char)(ch & 0xff);
  7631. if (len == (int)sizeof(buf)) {
  7632. mg_write(conn, buf, (size_t)len);
  7633. len = 0;
  7634. }
  7635. }
  7636. }
  7637. /* Send the rest of buffered data */
  7638. if (len > 0) {
  7639. mg_write(conn, buf, (size_t)len);
  7640. }
  7641. }
  7642. static void
  7643. handle_ssi_file_request(struct mg_connection *conn,
  7644. const char *path,
  7645. struct mg_file *filep)
  7646. {
  7647. char date[64];
  7648. time_t curtime = time(NULL);
  7649. const char *cors1, *cors2, *cors3;
  7650. if (conn == NULL || path == NULL || filep == NULL) {
  7651. return;
  7652. }
  7653. if (mg_get_header(conn, "Origin")) {
  7654. /* Cross-origin resource sharing (CORS). */
  7655. cors1 = "Access-Control-Allow-Origin: ";
  7656. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7657. cors3 = "\r\n";
  7658. } else {
  7659. cors1 = cors2 = cors3 = "";
  7660. }
  7661. if (!mg_fopen(conn, path, "rb", filep)) {
  7662. /* File exists (precondition for calling this function),
  7663. * but can not be opened by the server. */
  7664. send_http_error(conn,
  7665. 500,
  7666. "Error: Cannot read file\nfopen(%s): %s",
  7667. path,
  7668. strerror(ERRNO));
  7669. } else {
  7670. conn->must_close = 1;
  7671. gmt_time_string(date, sizeof(date), &curtime);
  7672. fclose_on_exec(&filep->access, conn);
  7673. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7674. send_no_cache_header(conn);
  7675. mg_printf(conn,
  7676. "%s%s%s"
  7677. "Date: %s\r\n"
  7678. "Content-Type: text/html\r\n"
  7679. "Connection: %s\r\n\r\n",
  7680. cors1,
  7681. cors2,
  7682. cors3,
  7683. date,
  7684. suggest_connection_header(conn));
  7685. send_ssi_file(conn, path, filep, 0);
  7686. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7687. }
  7688. }
  7689. #if !defined(NO_FILES)
  7690. static void
  7691. send_options(struct mg_connection *conn)
  7692. {
  7693. char date[64];
  7694. time_t curtime = time(NULL);
  7695. if (!conn) {
  7696. return;
  7697. }
  7698. conn->status_code = 200;
  7699. conn->must_close = 1;
  7700. gmt_time_string(date, sizeof(date), &curtime);
  7701. mg_printf(conn,
  7702. "HTTP/1.1 200 OK\r\n"
  7703. "Date: %s\r\n"
  7704. /* TODO: "Cache-Control" (?) */
  7705. "Connection: %s\r\n"
  7706. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7707. "PROPFIND, MKCOL\r\n"
  7708. "DAV: 1\r\n\r\n",
  7709. date,
  7710. suggest_connection_header(conn));
  7711. }
  7712. /* Writes PROPFIND properties for a collection element */
  7713. static void
  7714. print_props(struct mg_connection *conn,
  7715. const char *uri,
  7716. struct mg_file_stat *filep)
  7717. {
  7718. char mtime[64];
  7719. if (conn == NULL || uri == NULL || filep == NULL) {
  7720. return;
  7721. }
  7722. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7723. conn->num_bytes_sent +=
  7724. mg_printf(conn,
  7725. "<d:response>"
  7726. "<d:href>%s</d:href>"
  7727. "<d:propstat>"
  7728. "<d:prop>"
  7729. "<d:resourcetype>%s</d:resourcetype>"
  7730. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7731. "<d:getlastmodified>%s</d:getlastmodified>"
  7732. "</d:prop>"
  7733. "<d:status>HTTP/1.1 200 OK</d:status>"
  7734. "</d:propstat>"
  7735. "</d:response>\n",
  7736. uri,
  7737. filep->is_directory ? "<d:collection/>" : "",
  7738. filep->size,
  7739. mtime);
  7740. }
  7741. static void
  7742. print_dav_dir_entry(struct de *de, void *data)
  7743. {
  7744. char href[PATH_MAX];
  7745. char href_encoded[PATH_MAX * 3 /* worst case */];
  7746. int truncated;
  7747. struct mg_connection *conn = (struct mg_connection *)data;
  7748. if (!de || !conn) {
  7749. return;
  7750. }
  7751. mg_snprintf(conn,
  7752. &truncated,
  7753. href,
  7754. sizeof(href),
  7755. "%s%s",
  7756. conn->request_info.local_uri,
  7757. de->file_name);
  7758. if (!truncated) {
  7759. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7760. print_props(conn, href_encoded, &de->file);
  7761. }
  7762. }
  7763. static void
  7764. handle_propfind(struct mg_connection *conn,
  7765. const char *path,
  7766. struct mg_file_stat *filep)
  7767. {
  7768. const char *depth = mg_get_header(conn, "Depth");
  7769. char date[64];
  7770. time_t curtime = time(NULL);
  7771. gmt_time_string(date, sizeof(date), &curtime);
  7772. if (!conn || !path || !filep || !conn->ctx) {
  7773. return;
  7774. }
  7775. conn->must_close = 1;
  7776. conn->status_code = 207;
  7777. mg_printf(conn,
  7778. "HTTP/1.1 207 Multi-Status\r\n"
  7779. "Date: %s\r\n",
  7780. date);
  7781. send_static_cache_header(conn);
  7782. mg_printf(conn,
  7783. "Connection: %s\r\n"
  7784. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7785. suggest_connection_header(conn));
  7786. conn->num_bytes_sent +=
  7787. mg_printf(conn,
  7788. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7789. "<d:multistatus xmlns:d='DAV:'>\n");
  7790. /* Print properties for the requested resource itself */
  7791. print_props(conn, conn->request_info.local_uri, filep);
  7792. /* If it is a directory, print directory entries too if Depth is not 0 */
  7793. if (filep && filep->is_directory
  7794. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7795. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7796. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7797. }
  7798. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7799. }
  7800. #endif
  7801. void
  7802. mg_lock_connection(struct mg_connection *conn)
  7803. {
  7804. if (conn) {
  7805. (void)pthread_mutex_lock(&conn->mutex);
  7806. }
  7807. }
  7808. void
  7809. mg_unlock_connection(struct mg_connection *conn)
  7810. {
  7811. if (conn) {
  7812. (void)pthread_mutex_unlock(&conn->mutex);
  7813. }
  7814. }
  7815. void
  7816. mg_lock_context(struct mg_context *ctx)
  7817. {
  7818. if (ctx) {
  7819. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7820. }
  7821. }
  7822. void
  7823. mg_unlock_context(struct mg_context *ctx)
  7824. {
  7825. if (ctx) {
  7826. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7827. }
  7828. }
  7829. #if defined(USE_TIMERS)
  7830. #include "timer.inl"
  7831. #endif /* USE_TIMERS */
  7832. #ifdef USE_LUA
  7833. #include "mod_lua.inl"
  7834. #endif /* USE_LUA */
  7835. #ifdef USE_DUKTAPE
  7836. #include "mod_duktape.inl"
  7837. #endif /* USE_DUKTAPE */
  7838. #if defined(USE_WEBSOCKET)
  7839. /* START OF SHA-1 code
  7840. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7841. #define SHA1HANDSOFF
  7842. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7843. *
  7844. * #if defined(__sun)
  7845. * #include "solarisfixes.h"
  7846. * #endif
  7847. */
  7848. static int
  7849. is_big_endian(void)
  7850. {
  7851. static const int n = 1;
  7852. return ((char *)&n)[0] == 0;
  7853. }
  7854. union char64long16 {
  7855. unsigned char c[64];
  7856. uint32_t l[16];
  7857. };
  7858. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7859. static uint32_t
  7860. blk0(union char64long16 *block, int i)
  7861. {
  7862. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7863. if (!is_big_endian()) {
  7864. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7865. | (rol(block->l[i], 8) & 0x00FF00FF);
  7866. }
  7867. return block->l[i];
  7868. }
  7869. #define blk(i) \
  7870. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7871. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7872. 1))
  7873. #define R0(v, w, x, y, z, i) \
  7874. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7875. w = rol(w, 30);
  7876. #define R1(v, w, x, y, z, i) \
  7877. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7878. w = rol(w, 30);
  7879. #define R2(v, w, x, y, z, i) \
  7880. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7881. w = rol(w, 30);
  7882. #define R3(v, w, x, y, z, i) \
  7883. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7884. w = rol(w, 30);
  7885. #define R4(v, w, x, y, z, i) \
  7886. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7887. w = rol(w, 30);
  7888. typedef struct {
  7889. uint32_t state[5];
  7890. uint32_t count[2];
  7891. unsigned char buffer[64];
  7892. } SHA1_CTX;
  7893. static void
  7894. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7895. {
  7896. uint32_t a, b, c, d, e;
  7897. union char64long16 block[1];
  7898. memcpy(block, buffer, 64);
  7899. a = state[0];
  7900. b = state[1];
  7901. c = state[2];
  7902. d = state[3];
  7903. e = state[4];
  7904. R0(a, b, c, d, e, 0);
  7905. R0(e, a, b, c, d, 1);
  7906. R0(d, e, a, b, c, 2);
  7907. R0(c, d, e, a, b, 3);
  7908. R0(b, c, d, e, a, 4);
  7909. R0(a, b, c, d, e, 5);
  7910. R0(e, a, b, c, d, 6);
  7911. R0(d, e, a, b, c, 7);
  7912. R0(c, d, e, a, b, 8);
  7913. R0(b, c, d, e, a, 9);
  7914. R0(a, b, c, d, e, 10);
  7915. R0(e, a, b, c, d, 11);
  7916. R0(d, e, a, b, c, 12);
  7917. R0(c, d, e, a, b, 13);
  7918. R0(b, c, d, e, a, 14);
  7919. R0(a, b, c, d, e, 15);
  7920. R1(e, a, b, c, d, 16);
  7921. R1(d, e, a, b, c, 17);
  7922. R1(c, d, e, a, b, 18);
  7923. R1(b, c, d, e, a, 19);
  7924. R2(a, b, c, d, e, 20);
  7925. R2(e, a, b, c, d, 21);
  7926. R2(d, e, a, b, c, 22);
  7927. R2(c, d, e, a, b, 23);
  7928. R2(b, c, d, e, a, 24);
  7929. R2(a, b, c, d, e, 25);
  7930. R2(e, a, b, c, d, 26);
  7931. R2(d, e, a, b, c, 27);
  7932. R2(c, d, e, a, b, 28);
  7933. R2(b, c, d, e, a, 29);
  7934. R2(a, b, c, d, e, 30);
  7935. R2(e, a, b, c, d, 31);
  7936. R2(d, e, a, b, c, 32);
  7937. R2(c, d, e, a, b, 33);
  7938. R2(b, c, d, e, a, 34);
  7939. R2(a, b, c, d, e, 35);
  7940. R2(e, a, b, c, d, 36);
  7941. R2(d, e, a, b, c, 37);
  7942. R2(c, d, e, a, b, 38);
  7943. R2(b, c, d, e, a, 39);
  7944. R3(a, b, c, d, e, 40);
  7945. R3(e, a, b, c, d, 41);
  7946. R3(d, e, a, b, c, 42);
  7947. R3(c, d, e, a, b, 43);
  7948. R3(b, c, d, e, a, 44);
  7949. R3(a, b, c, d, e, 45);
  7950. R3(e, a, b, c, d, 46);
  7951. R3(d, e, a, b, c, 47);
  7952. R3(c, d, e, a, b, 48);
  7953. R3(b, c, d, e, a, 49);
  7954. R3(a, b, c, d, e, 50);
  7955. R3(e, a, b, c, d, 51);
  7956. R3(d, e, a, b, c, 52);
  7957. R3(c, d, e, a, b, 53);
  7958. R3(b, c, d, e, a, 54);
  7959. R3(a, b, c, d, e, 55);
  7960. R3(e, a, b, c, d, 56);
  7961. R3(d, e, a, b, c, 57);
  7962. R3(c, d, e, a, b, 58);
  7963. R3(b, c, d, e, a, 59);
  7964. R4(a, b, c, d, e, 60);
  7965. R4(e, a, b, c, d, 61);
  7966. R4(d, e, a, b, c, 62);
  7967. R4(c, d, e, a, b, 63);
  7968. R4(b, c, d, e, a, 64);
  7969. R4(a, b, c, d, e, 65);
  7970. R4(e, a, b, c, d, 66);
  7971. R4(d, e, a, b, c, 67);
  7972. R4(c, d, e, a, b, 68);
  7973. R4(b, c, d, e, a, 69);
  7974. R4(a, b, c, d, e, 70);
  7975. R4(e, a, b, c, d, 71);
  7976. R4(d, e, a, b, c, 72);
  7977. R4(c, d, e, a, b, 73);
  7978. R4(b, c, d, e, a, 74);
  7979. R4(a, b, c, d, e, 75);
  7980. R4(e, a, b, c, d, 76);
  7981. R4(d, e, a, b, c, 77);
  7982. R4(c, d, e, a, b, 78);
  7983. R4(b, c, d, e, a, 79);
  7984. state[0] += a;
  7985. state[1] += b;
  7986. state[2] += c;
  7987. state[3] += d;
  7988. state[4] += e;
  7989. a = b = c = d = e = 0;
  7990. memset(block, '\0', sizeof(block));
  7991. }
  7992. static void
  7993. SHA1Init(SHA1_CTX *context)
  7994. {
  7995. context->state[0] = 0x67452301;
  7996. context->state[1] = 0xEFCDAB89;
  7997. context->state[2] = 0x98BADCFE;
  7998. context->state[3] = 0x10325476;
  7999. context->state[4] = 0xC3D2E1F0;
  8000. context->count[0] = context->count[1] = 0;
  8001. }
  8002. static void
  8003. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  8004. {
  8005. uint32_t i, j;
  8006. j = context->count[0];
  8007. if ((context->count[0] += len << 3) < j) {
  8008. context->count[1]++;
  8009. }
  8010. context->count[1] += (len >> 29);
  8011. j = (j >> 3) & 63;
  8012. if ((j + len) > 63) {
  8013. memcpy(&context->buffer[j], data, (i = 64 - j));
  8014. SHA1Transform(context->state, context->buffer);
  8015. for (; i + 63 < len; i += 64) {
  8016. SHA1Transform(context->state, &data[i]);
  8017. }
  8018. j = 0;
  8019. } else
  8020. i = 0;
  8021. memcpy(&context->buffer[j], &data[i], len - i);
  8022. }
  8023. static void
  8024. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  8025. {
  8026. unsigned i;
  8027. unsigned char finalcount[8], c;
  8028. for (i = 0; i < 8; i++) {
  8029. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  8030. >> ((3 - (i & 3)) * 8)) & 255);
  8031. }
  8032. c = 0200;
  8033. SHA1Update(context, &c, 1);
  8034. while ((context->count[0] & 504) != 448) {
  8035. c = 0000;
  8036. SHA1Update(context, &c, 1);
  8037. }
  8038. SHA1Update(context, finalcount, 8);
  8039. for (i = 0; i < 20; i++) {
  8040. digest[i] = (unsigned char)((context->state[i >> 2]
  8041. >> ((3 - (i & 3)) * 8)) & 255);
  8042. }
  8043. memset(context, '\0', sizeof(*context));
  8044. memset(&finalcount, '\0', sizeof(finalcount));
  8045. }
  8046. /* END OF SHA1 CODE */
  8047. static int
  8048. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8049. {
  8050. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8051. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8052. SHA1_CTX sha_ctx;
  8053. int truncated;
  8054. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8055. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8056. if (truncated) {
  8057. conn->must_close = 1;
  8058. return 0;
  8059. }
  8060. SHA1Init(&sha_ctx);
  8061. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8062. SHA1Final((unsigned char *)sha, &sha_ctx);
  8063. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8064. mg_printf(conn,
  8065. "HTTP/1.1 101 Switching Protocols\r\n"
  8066. "Upgrade: websocket\r\n"
  8067. "Connection: Upgrade\r\n"
  8068. "Sec-WebSocket-Accept: %s\r\n",
  8069. b64_sha);
  8070. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8071. mg_printf(conn,
  8072. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8073. conn->request_info.acceptedWebSocketSubprotocol);
  8074. } else {
  8075. mg_printf(conn, "%s", "\r\n");
  8076. }
  8077. return 1;
  8078. }
  8079. static void
  8080. read_websocket(struct mg_connection *conn,
  8081. mg_websocket_data_handler ws_data_handler,
  8082. void *callback_data)
  8083. {
  8084. /* Pointer to the beginning of the portion of the incoming websocket
  8085. * message queue.
  8086. * The original websocket upgrade request is never removed, so the queue
  8087. * begins after it. */
  8088. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8089. int n, error, exit_by_callback;
  8090. /* body_len is the length of the entire queue in bytes
  8091. * len is the length of the current message
  8092. * data_len is the length of the current message's data payload
  8093. * header_len is the length of the current message's header */
  8094. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8095. /* "The masking key is a 32-bit value chosen at random by the client."
  8096. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8097. */
  8098. unsigned char mask[4];
  8099. /* data points to the place where the message is stored when passed to
  8100. * the
  8101. * websocket_data callback. This is either mem on the stack, or a
  8102. * dynamically allocated buffer if it is too large. */
  8103. unsigned char mem[4096];
  8104. unsigned char *data = mem;
  8105. unsigned char mop; /* mask flag and opcode */
  8106. double timeout = -1.0;
  8107. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8108. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8109. }
  8110. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8111. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8112. }
  8113. mg_set_thread_name("wsock");
  8114. /* Loop continuously, reading messages from the socket, invoking the
  8115. * callback, and waiting repeatedly until an error occurs. */
  8116. while (!conn->ctx->stop_flag) {
  8117. header_len = 0;
  8118. assert(conn->data_len >= conn->request_len);
  8119. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8120. len = buf[1] & 127;
  8121. mask_len = (buf[1] & 128) ? 4 : 0;
  8122. if ((len < 126) && (body_len >= mask_len)) {
  8123. data_len = len;
  8124. header_len = 2 + mask_len;
  8125. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8126. header_len = 4 + mask_len;
  8127. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8128. } else if (body_len >= (10 + mask_len)) {
  8129. header_len = 10 + mask_len;
  8130. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8131. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8132. }
  8133. }
  8134. if (header_len > 0 && body_len >= header_len) {
  8135. /* Allocate space to hold websocket payload */
  8136. data = mem;
  8137. if (data_len > sizeof(mem)) {
  8138. data = (unsigned char *)mg_malloc(data_len);
  8139. if (data == NULL) {
  8140. /* Allocation failed, exit the loop and then close the
  8141. * connection */
  8142. mg_cry(conn, "websocket out of memory; closing connection");
  8143. break;
  8144. }
  8145. }
  8146. /* Copy the mask before we shift the queue and destroy it */
  8147. if (mask_len > 0) {
  8148. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8149. } else {
  8150. memset(mask, 0, sizeof(mask));
  8151. }
  8152. /* Read frame payload from the first message in the queue into
  8153. * data and advance the queue by moving the memory in place. */
  8154. assert(body_len >= header_len);
  8155. if (data_len + header_len > body_len) {
  8156. mop = buf[0]; /* current mask and opcode */
  8157. /* Overflow case */
  8158. len = body_len - header_len;
  8159. memcpy(data, buf + header_len, len);
  8160. error = 0;
  8161. while (len < data_len) {
  8162. n = pull(NULL,
  8163. conn,
  8164. (char *)(data + len),
  8165. (int)(data_len - len),
  8166. timeout);
  8167. if (n <= 0) {
  8168. error = 1;
  8169. break;
  8170. }
  8171. len += (size_t)n;
  8172. }
  8173. if (error) {
  8174. mg_cry(conn, "Websocket pull failed; closing connection");
  8175. break;
  8176. }
  8177. conn->data_len = conn->request_len;
  8178. } else {
  8179. mop = buf[0]; /* current mask and opcode, overwritten by
  8180. * memmove() */
  8181. /* Length of the message being read at the front of the
  8182. * queue */
  8183. len = data_len + header_len;
  8184. /* Copy the data payload into the data pointer for the
  8185. * callback */
  8186. memcpy(data, buf + header_len, data_len);
  8187. /* Move the queue forward len bytes */
  8188. memmove(buf, buf + len, body_len - len);
  8189. /* Mark the queue as advanced */
  8190. conn->data_len -= (int)len;
  8191. }
  8192. /* Apply mask if necessary */
  8193. if (mask_len > 0) {
  8194. for (i = 0; i < data_len; ++i) {
  8195. data[i] ^= mask[i & 3];
  8196. }
  8197. }
  8198. /* Exit the loop if callback signals to exit (server side),
  8199. * or "connection close" opcode received (client side). */
  8200. exit_by_callback = 0;
  8201. if ((ws_data_handler != NULL)
  8202. && !ws_data_handler(
  8203. conn, mop, (char *)data, data_len, callback_data)) {
  8204. exit_by_callback = 1;
  8205. }
  8206. if (data != mem) {
  8207. mg_free(data);
  8208. }
  8209. if (exit_by_callback
  8210. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8211. /* Opcode == 8, connection close */
  8212. break;
  8213. }
  8214. /* Not breaking the loop, process next websocket frame. */
  8215. } else {
  8216. /* Read from the socket into the next available location in the
  8217. * message queue. */
  8218. if ((n = pull(NULL,
  8219. conn,
  8220. conn->buf + conn->data_len,
  8221. conn->buf_size - conn->data_len,
  8222. timeout)) <= 0) {
  8223. /* Error, no bytes read */
  8224. break;
  8225. }
  8226. conn->data_len += n;
  8227. }
  8228. }
  8229. mg_set_thread_name("worker");
  8230. }
  8231. static int
  8232. mg_websocket_write_exec(struct mg_connection *conn,
  8233. int opcode,
  8234. const char *data,
  8235. size_t dataLen,
  8236. uint32_t masking_key)
  8237. {
  8238. unsigned char header[14];
  8239. size_t headerLen = 1;
  8240. int retval = -1;
  8241. #if defined(__GNUC__) || defined(__MINGW32__)
  8242. /* Disable spurious conversion warning for GCC */
  8243. #pragma GCC diagnostic push
  8244. #pragma GCC diagnostic ignored "-Wconversion"
  8245. #endif
  8246. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8247. #if defined(__GNUC__) || defined(__MINGW32__)
  8248. #pragma GCC diagnostic pop
  8249. #endif
  8250. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8251. if (dataLen < 126) {
  8252. /* inline 7-bit length field */
  8253. header[1] = (unsigned char)dataLen;
  8254. headerLen = 2;
  8255. } else if (dataLen <= 0xFFFF) {
  8256. /* 16-bit length field */
  8257. uint16_t len = htons((uint16_t)dataLen);
  8258. header[1] = 126;
  8259. memcpy(header + 2, &len, 2);
  8260. headerLen = 4;
  8261. } else {
  8262. /* 64-bit length field */
  8263. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8264. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8265. header[1] = 127;
  8266. memcpy(header + 2, &len1, 4);
  8267. memcpy(header + 6, &len2, 4);
  8268. headerLen = 10;
  8269. }
  8270. if (masking_key) {
  8271. /* add mask */
  8272. header[1] |= 0x80;
  8273. memcpy(header + headerLen, &masking_key, 4);
  8274. headerLen += 4;
  8275. }
  8276. /* Note that POSIX/Winsock's send() is threadsafe
  8277. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8278. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8279. * push(), although that is only a problem if the packet is large or
  8280. * outgoing buffer is full). */
  8281. (void)mg_lock_connection(conn);
  8282. retval = mg_write(conn, header, headerLen);
  8283. if (dataLen > 0) {
  8284. retval = mg_write(conn, data, dataLen);
  8285. }
  8286. mg_unlock_connection(conn);
  8287. return retval;
  8288. }
  8289. int
  8290. mg_websocket_write(struct mg_connection *conn,
  8291. int opcode,
  8292. const char *data,
  8293. size_t dataLen)
  8294. {
  8295. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8296. }
  8297. static void
  8298. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8299. {
  8300. size_t i = 0;
  8301. i = 0;
  8302. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8303. /* Convert in 32 bit words, if data is 4 byte aligned */
  8304. while (i < (in_len - 3)) {
  8305. *(uint32_t *)(void *)(out + i) =
  8306. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8307. i += 4;
  8308. }
  8309. }
  8310. if (i != in_len) {
  8311. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8312. while (i < in_len) {
  8313. *(uint8_t *)(void *)(out + i) =
  8314. *(uint8_t *)(void *)(in + i)
  8315. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8316. i++;
  8317. }
  8318. }
  8319. }
  8320. int
  8321. mg_websocket_client_write(struct mg_connection *conn,
  8322. int opcode,
  8323. const char *data,
  8324. size_t dataLen)
  8325. {
  8326. int retval = -1;
  8327. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8328. uint32_t masking_key = (uint32_t)get_random();
  8329. if (masked_data == NULL) {
  8330. /* Return -1 in an error case */
  8331. mg_cry(conn,
  8332. "Cannot allocate buffer for masked websocket response: "
  8333. "Out of memory");
  8334. return -1;
  8335. }
  8336. mask_data(data, dataLen, masking_key, masked_data);
  8337. retval = mg_websocket_write_exec(
  8338. conn, opcode, masked_data, dataLen, masking_key);
  8339. mg_free(masked_data);
  8340. return retval;
  8341. }
  8342. static void
  8343. handle_websocket_request(struct mg_connection *conn,
  8344. const char *path,
  8345. int is_callback_resource,
  8346. struct mg_websocket_subprotocols *subprotocols,
  8347. mg_websocket_connect_handler ws_connect_handler,
  8348. mg_websocket_ready_handler ws_ready_handler,
  8349. mg_websocket_data_handler ws_data_handler,
  8350. mg_websocket_close_handler ws_close_handler,
  8351. void *cbData)
  8352. {
  8353. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8354. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8355. int lua_websock = 0;
  8356. #if !defined(USE_LUA)
  8357. (void)path;
  8358. #endif
  8359. /* Step 1: Check websocket protocol version. */
  8360. /* Step 1.1: Check Sec-WebSocket-Key. */
  8361. if (!websock_key) {
  8362. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8363. * requires a Sec-WebSocket-Key header.
  8364. */
  8365. /* It could be the hixie draft version
  8366. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8367. */
  8368. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8369. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8370. char key3[8];
  8371. if ((key1 != NULL) && (key2 != NULL)) {
  8372. /* This version uses 8 byte body data in a GET request */
  8373. conn->content_len = 8;
  8374. if (8 == mg_read(conn, key3, 8)) {
  8375. /* This is the hixie version */
  8376. send_http_error(conn,
  8377. 426,
  8378. "%s",
  8379. "Protocol upgrade to RFC 6455 required");
  8380. return;
  8381. }
  8382. }
  8383. /* This is an unknown version */
  8384. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8385. return;
  8386. }
  8387. /* Step 1.2: Check websocket protocol version. */
  8388. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8389. if (version == NULL || strcmp(version, "13") != 0) {
  8390. /* Reject wrong versions */
  8391. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8392. return;
  8393. }
  8394. /* Step 1.3: Could check for "Host", but we do not really nead this
  8395. * value for anything, so just ignore it. */
  8396. /* Step 2: If a callback is responsible, call it. */
  8397. if (is_callback_resource) {
  8398. /* Step 2.1 check and select subprotocol */
  8399. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8400. if (protocol && subprotocols) {
  8401. int idx;
  8402. unsigned long len;
  8403. const char *sep, *curSubProtocol,
  8404. *acceptedWebSocketSubprotocol = NULL;
  8405. /* look for matching subprotocol */
  8406. do {
  8407. sep = strchr(protocol, ',');
  8408. curSubProtocol = protocol;
  8409. len = sep ? (unsigned long)(sep - protocol) : strlen(protocol);
  8410. protocol = sep ? sep + 1 : NULL;
  8411. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8412. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8413. && (strncmp(curSubProtocol,
  8414. subprotocols->subprotocols[idx],
  8415. len) == 0)) {
  8416. acceptedWebSocketSubprotocol =
  8417. subprotocols->subprotocols[idx];
  8418. break;
  8419. }
  8420. }
  8421. } while (sep && !acceptedWebSocketSubprotocol);
  8422. conn->request_info.acceptedWebSocketSubprotocol =
  8423. acceptedWebSocketSubprotocol;
  8424. } else if (protocol) {
  8425. /* keep legacy behavior */
  8426. /* The protocol is a comma seperated list of names. */
  8427. /* The server must only return one value from this list. */
  8428. /* First check if it is a list or just a single value. */
  8429. const char *sep = strrchr(protocol, ',');
  8430. if (sep == NULL) {
  8431. /* Just a single protocol -> accept it. */
  8432. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8433. } else {
  8434. /* Multiple protocols -> accept the last one. */
  8435. /* This is just a quick fix if the client offers multiple
  8436. * protocols. The handler should have a list of accepted
  8437. * protocols on his own
  8438. * and use it to select one protocol among those the client has
  8439. * offered.
  8440. */
  8441. conn->request_info.acceptedWebSocketSubprotocol = (sep + 1);
  8442. }
  8443. }
  8444. if (ws_connect_handler != NULL
  8445. && ws_connect_handler(conn, cbData) != 0) {
  8446. /* C callback has returned non-zero, do not proceed with
  8447. * handshake.
  8448. */
  8449. /* Note that C callbacks are no longer called when Lua is
  8450. * responsible, so C can no longer filter callbacks for Lua. */
  8451. return;
  8452. }
  8453. }
  8454. #if defined(USE_LUA)
  8455. /* Step 3: No callback. Check if Lua is responsible. */
  8456. else {
  8457. /* Step 3.1: Check if Lua is responsible. */
  8458. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8459. lua_websock =
  8460. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8461. strlen(
  8462. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8463. path);
  8464. }
  8465. if (lua_websock) {
  8466. /* Step 3.2: Lua is responsible: call it. */
  8467. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8468. if (!conn->lua_websocket_state) {
  8469. /* Lua rejected the new client */
  8470. return;
  8471. }
  8472. }
  8473. }
  8474. #endif
  8475. /* Step 4: Check if there is a responsible websocket handler. */
  8476. if (!is_callback_resource && !lua_websock) {
  8477. /* There is no callback, an Lua is not responsible either. */
  8478. /* Reply with a 404 Not Found or with nothing at all?
  8479. * TODO (mid): check the websocket standards, how to reply to
  8480. * requests to invalid websocket addresses. */
  8481. send_http_error(conn, 404, "%s", "Not found");
  8482. return;
  8483. }
  8484. /* Step 5: The websocket connection has been accepted */
  8485. if (!send_websocket_handshake(conn, websock_key)) {
  8486. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8487. return;
  8488. }
  8489. /* Step 6: Call the ready handler */
  8490. if (is_callback_resource) {
  8491. if (ws_ready_handler != NULL) {
  8492. ws_ready_handler(conn, cbData);
  8493. }
  8494. #if defined(USE_LUA)
  8495. } else if (lua_websock) {
  8496. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8497. /* the ready handler returned false */
  8498. return;
  8499. }
  8500. #endif
  8501. }
  8502. /* Step 7: Enter the read loop */
  8503. if (is_callback_resource) {
  8504. read_websocket(conn, ws_data_handler, cbData);
  8505. #if defined(USE_LUA)
  8506. } else if (lua_websock) {
  8507. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8508. #endif
  8509. }
  8510. /* Step 8: Call the close handler */
  8511. if (ws_close_handler) {
  8512. ws_close_handler(conn, cbData);
  8513. }
  8514. }
  8515. static int
  8516. is_websocket_protocol(const struct mg_connection *conn)
  8517. {
  8518. const char *upgrade, *connection;
  8519. /* A websocket protocoll has the following HTTP headers:
  8520. *
  8521. * Connection: Upgrade
  8522. * Upgrade: Websocket
  8523. */
  8524. upgrade = mg_get_header(conn, "Upgrade");
  8525. if (upgrade == NULL) {
  8526. return 0; /* fail early, don't waste time checking other header
  8527. * fields
  8528. */
  8529. }
  8530. if (!mg_strcasestr(upgrade, "websocket")) {
  8531. return 0;
  8532. }
  8533. connection = mg_get_header(conn, "Connection");
  8534. if (connection == NULL) {
  8535. return 0;
  8536. }
  8537. if (!mg_strcasestr(connection, "upgrade")) {
  8538. return 0;
  8539. }
  8540. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8541. * "Sec-WebSocket-Version" are also required.
  8542. * Don't check them here, since even an unsupported websocket protocol
  8543. * request still IS a websocket request (in contrast to a standard HTTP
  8544. * request). It will fail later in handle_websocket_request.
  8545. */
  8546. return 1;
  8547. }
  8548. #endif /* !USE_WEBSOCKET */
  8549. static int
  8550. isbyte(int n)
  8551. {
  8552. return n >= 0 && n <= 255;
  8553. }
  8554. static int
  8555. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8556. {
  8557. int n, a, b, c, d, slash = 32, len = 0;
  8558. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8559. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8560. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8561. && slash < 33) {
  8562. len = n;
  8563. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8564. | (uint32_t)d;
  8565. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8566. }
  8567. return len;
  8568. }
  8569. static int
  8570. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8571. {
  8572. int throttle = 0;
  8573. struct vec vec, val;
  8574. uint32_t net, mask;
  8575. char mult;
  8576. double v;
  8577. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8578. mult = ',';
  8579. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8580. || (v < 0) || ((lowercase(&mult) != 'k')
  8581. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8582. continue;
  8583. }
  8584. v *= (lowercase(&mult) == 'k')
  8585. ? 1024
  8586. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8587. if (vec.len == 1 && vec.ptr[0] == '*') {
  8588. throttle = (int)v;
  8589. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8590. if ((remote_ip & mask) == net) {
  8591. throttle = (int)v;
  8592. }
  8593. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8594. throttle = (int)v;
  8595. }
  8596. }
  8597. return throttle;
  8598. }
  8599. static uint32_t
  8600. get_remote_ip(const struct mg_connection *conn)
  8601. {
  8602. if (!conn) {
  8603. return 0;
  8604. }
  8605. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8606. }
  8607. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8608. #include "handle_form.inl"
  8609. #if defined(MG_LEGACY_INTERFACE)
  8610. /* Implement the deprecated mg_upload function by calling the new
  8611. * mg_handle_form_request function. While mg_upload could only handle
  8612. * HTML forms sent as POST request in multipart/form-data format
  8613. * containing only file input elements, mg_handle_form_request can
  8614. * handle all form input elements and all standard request methods. */
  8615. struct mg_upload_user_data {
  8616. struct mg_connection *conn;
  8617. const char *destination_dir;
  8618. int num_uploaded_files;
  8619. };
  8620. /* Helper function for deprecated mg_upload. */
  8621. static int
  8622. mg_upload_field_found(const char *key,
  8623. const char *filename,
  8624. char *path,
  8625. size_t pathlen,
  8626. void *user_data)
  8627. {
  8628. int truncated = 0;
  8629. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8630. (void)key;
  8631. if (!filename) {
  8632. mg_cry(fud->conn, "%s: No filename set", __func__);
  8633. return FORM_FIELD_STORAGE_ABORT;
  8634. }
  8635. mg_snprintf(fud->conn,
  8636. &truncated,
  8637. path,
  8638. pathlen - 1,
  8639. "%s/%s",
  8640. fud->destination_dir,
  8641. filename);
  8642. if (!truncated) {
  8643. mg_cry(fud->conn, "%s: File path too long", __func__);
  8644. return FORM_FIELD_STORAGE_ABORT;
  8645. }
  8646. return FORM_FIELD_STORAGE_STORE;
  8647. }
  8648. /* Helper function for deprecated mg_upload. */
  8649. static int
  8650. mg_upload_field_get(const char *key,
  8651. const char *value,
  8652. size_t value_size,
  8653. void *user_data)
  8654. {
  8655. /* Function should never be called */
  8656. (void)key;
  8657. (void)value;
  8658. (void)value_size;
  8659. (void)user_data;
  8660. return 0;
  8661. }
  8662. /* Helper function for deprecated mg_upload. */
  8663. static int
  8664. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8665. {
  8666. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8667. (void)file_size;
  8668. fud->num_uploaded_files++;
  8669. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8670. return 0;
  8671. }
  8672. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8673. int
  8674. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8675. {
  8676. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8677. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8678. mg_upload_field_get,
  8679. mg_upload_field_stored,
  8680. 0};
  8681. int ret;
  8682. fdh.user_data = (void *)&fud;
  8683. ret = mg_handle_form_request(conn, &fdh);
  8684. if (ret < 0) {
  8685. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8686. }
  8687. return fud.num_uploaded_files;
  8688. }
  8689. #endif
  8690. static int
  8691. get_first_ssl_listener_index(const struct mg_context *ctx)
  8692. {
  8693. unsigned int i;
  8694. int idx = -1;
  8695. if (ctx) {
  8696. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8697. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8698. }
  8699. }
  8700. return idx;
  8701. }
  8702. static void
  8703. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8704. {
  8705. char host[1025];
  8706. const char *host_header;
  8707. size_t hostlen;
  8708. host_header = mg_get_header(conn, "Host");
  8709. hostlen = sizeof(host);
  8710. if (host_header != NULL) {
  8711. char *pos;
  8712. mg_strlcpy(host, host_header, hostlen);
  8713. host[hostlen - 1] = '\0';
  8714. pos = strchr(host, ':');
  8715. if (pos != NULL) {
  8716. *pos = '\0';
  8717. }
  8718. } else {
  8719. /* Cannot get host from the Host: header.
  8720. * Fallback to our IP address. */
  8721. if (conn) {
  8722. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8723. }
  8724. }
  8725. /* Send host, port, uri and (if it exists) ?query_string */
  8726. if (conn) {
  8727. mg_printf(conn,
  8728. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8729. host,
  8730. #if defined(USE_IPV6)
  8731. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8732. == AF_INET6)
  8733. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8734. .lsa.sin6.sin6_port)
  8735. :
  8736. #endif
  8737. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8738. .lsa.sin.sin_port),
  8739. conn->request_info.local_uri,
  8740. (conn->request_info.query_string == NULL) ? "" : "?",
  8741. (conn->request_info.query_string == NULL)
  8742. ? ""
  8743. : conn->request_info.query_string);
  8744. }
  8745. }
  8746. static void
  8747. mg_set_handler_type(struct mg_context *ctx,
  8748. const char *uri,
  8749. int handler_type,
  8750. int is_delete_request,
  8751. mg_request_handler handler,
  8752. struct mg_websocket_subprotocols *subprotocols,
  8753. mg_websocket_connect_handler connect_handler,
  8754. mg_websocket_ready_handler ready_handler,
  8755. mg_websocket_data_handler data_handler,
  8756. mg_websocket_close_handler close_handler,
  8757. mg_authorization_handler auth_handler,
  8758. void *cbdata)
  8759. {
  8760. struct mg_handler_info *tmp_rh, **lastref;
  8761. size_t urilen = strlen(uri);
  8762. if (handler_type == WEBSOCKET_HANDLER) {
  8763. /* assert(handler == NULL); */
  8764. /* assert(is_delete_request || connect_handler!=NULL ||
  8765. * ready_handler!=NULL || data_handler!=NULL ||
  8766. * close_handler!=NULL);
  8767. */
  8768. /* assert(auth_handler == NULL); */
  8769. if (handler != NULL) {
  8770. return;
  8771. }
  8772. if (!is_delete_request && connect_handler == NULL
  8773. && ready_handler == NULL
  8774. && data_handler == NULL
  8775. && close_handler == NULL) {
  8776. return;
  8777. }
  8778. if (auth_handler != NULL) {
  8779. return;
  8780. }
  8781. } else if (handler_type == REQUEST_HANDLER) {
  8782. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8783. * data_handler==NULL && close_handler==NULL); */
  8784. /* assert(is_delete_request || (handler!=NULL));
  8785. */
  8786. /* assert(auth_handler == NULL); */
  8787. if (connect_handler != NULL || ready_handler != NULL
  8788. || data_handler != NULL
  8789. || close_handler != NULL) {
  8790. return;
  8791. }
  8792. if (!is_delete_request && (handler == NULL)) {
  8793. return;
  8794. }
  8795. if (auth_handler != NULL) {
  8796. return;
  8797. }
  8798. } else { /* AUTH_HANDLER */
  8799. /* assert(handler == NULL); */
  8800. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8801. * data_handler==NULL && close_handler==NULL); */
  8802. /* assert(auth_handler != NULL); */
  8803. if (handler != NULL) {
  8804. return;
  8805. }
  8806. if (connect_handler != NULL || ready_handler != NULL
  8807. || data_handler != NULL
  8808. || close_handler != NULL) {
  8809. return;
  8810. }
  8811. if (!is_delete_request && (auth_handler == NULL)) {
  8812. return;
  8813. }
  8814. }
  8815. if (!ctx) {
  8816. return;
  8817. }
  8818. mg_lock_context(ctx);
  8819. /* first try to find an existing handler */
  8820. lastref = &(ctx->handlers);
  8821. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8822. if (tmp_rh->handler_type == handler_type) {
  8823. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8824. if (!is_delete_request) {
  8825. /* update existing handler */
  8826. if (handler_type == REQUEST_HANDLER) {
  8827. tmp_rh->handler = handler;
  8828. } else if (handler_type == WEBSOCKET_HANDLER) {
  8829. tmp_rh->subprotocols = subprotocols;
  8830. tmp_rh->connect_handler = connect_handler;
  8831. tmp_rh->ready_handler = ready_handler;
  8832. tmp_rh->data_handler = data_handler;
  8833. tmp_rh->close_handler = close_handler;
  8834. } else { /* AUTH_HANDLER */
  8835. tmp_rh->auth_handler = auth_handler;
  8836. }
  8837. tmp_rh->cbdata = cbdata;
  8838. } else {
  8839. /* remove existing handler */
  8840. *lastref = tmp_rh->next;
  8841. mg_free(tmp_rh->uri);
  8842. mg_free(tmp_rh);
  8843. }
  8844. mg_unlock_context(ctx);
  8845. return;
  8846. }
  8847. }
  8848. lastref = &(tmp_rh->next);
  8849. }
  8850. if (is_delete_request) {
  8851. /* no handler to set, this was a remove request to a non-existing
  8852. * handler */
  8853. mg_unlock_context(ctx);
  8854. return;
  8855. }
  8856. tmp_rh =
  8857. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8858. if (tmp_rh == NULL) {
  8859. mg_unlock_context(ctx);
  8860. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8861. return;
  8862. }
  8863. tmp_rh->uri = mg_strdup(uri);
  8864. if (!tmp_rh->uri) {
  8865. mg_unlock_context(ctx);
  8866. mg_free(tmp_rh);
  8867. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8868. return;
  8869. }
  8870. tmp_rh->uri_len = urilen;
  8871. if (handler_type == REQUEST_HANDLER) {
  8872. tmp_rh->handler = handler;
  8873. } else if (handler_type == WEBSOCKET_HANDLER) {
  8874. tmp_rh->subprotocols = subprotocols;
  8875. tmp_rh->connect_handler = connect_handler;
  8876. tmp_rh->ready_handler = ready_handler;
  8877. tmp_rh->data_handler = data_handler;
  8878. tmp_rh->close_handler = close_handler;
  8879. } else { /* AUTH_HANDLER */
  8880. tmp_rh->auth_handler = auth_handler;
  8881. }
  8882. tmp_rh->cbdata = cbdata;
  8883. tmp_rh->handler_type = handler_type;
  8884. tmp_rh->next = NULL;
  8885. *lastref = tmp_rh;
  8886. mg_unlock_context(ctx);
  8887. }
  8888. void
  8889. mg_set_request_handler(struct mg_context *ctx,
  8890. const char *uri,
  8891. mg_request_handler handler,
  8892. void *cbdata)
  8893. {
  8894. mg_set_handler_type(ctx,
  8895. uri,
  8896. REQUEST_HANDLER,
  8897. handler == NULL,
  8898. handler,
  8899. NULL,
  8900. NULL,
  8901. NULL,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. cbdata);
  8906. }
  8907. void
  8908. mg_set_websocket_handler(struct mg_context *ctx,
  8909. const char *uri,
  8910. mg_websocket_connect_handler connect_handler,
  8911. mg_websocket_ready_handler ready_handler,
  8912. mg_websocket_data_handler data_handler,
  8913. mg_websocket_close_handler close_handler,
  8914. void *cbdata)
  8915. {
  8916. mg_set_websocket_handler_with_subprotocols(ctx,
  8917. uri,
  8918. NULL,
  8919. connect_handler,
  8920. ready_handler,
  8921. data_handler,
  8922. close_handler,
  8923. cbdata);
  8924. }
  8925. void
  8926. mg_set_websocket_handler_with_subprotocols(
  8927. struct mg_context *ctx,
  8928. const char *uri,
  8929. struct mg_websocket_subprotocols *subprotocols,
  8930. mg_websocket_connect_handler connect_handler,
  8931. mg_websocket_ready_handler ready_handler,
  8932. mg_websocket_data_handler data_handler,
  8933. mg_websocket_close_handler close_handler,
  8934. void *cbdata)
  8935. {
  8936. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8937. && (data_handler == NULL)
  8938. && (close_handler == NULL);
  8939. mg_set_handler_type(ctx,
  8940. uri,
  8941. WEBSOCKET_HANDLER,
  8942. is_delete_request,
  8943. NULL,
  8944. subprotocols,
  8945. connect_handler,
  8946. ready_handler,
  8947. data_handler,
  8948. close_handler,
  8949. NULL,
  8950. cbdata);
  8951. }
  8952. void
  8953. mg_set_auth_handler(struct mg_context *ctx,
  8954. const char *uri,
  8955. mg_request_handler handler,
  8956. void *cbdata)
  8957. {
  8958. mg_set_handler_type(ctx,
  8959. uri,
  8960. AUTH_HANDLER,
  8961. handler == NULL,
  8962. NULL,
  8963. NULL,
  8964. NULL,
  8965. NULL,
  8966. NULL,
  8967. NULL,
  8968. handler,
  8969. cbdata);
  8970. }
  8971. static int
  8972. get_request_handler(struct mg_connection *conn,
  8973. int handler_type,
  8974. mg_request_handler *handler,
  8975. struct mg_websocket_subprotocols **subprotocols,
  8976. mg_websocket_connect_handler *connect_handler,
  8977. mg_websocket_ready_handler *ready_handler,
  8978. mg_websocket_data_handler *data_handler,
  8979. mg_websocket_close_handler *close_handler,
  8980. mg_authorization_handler *auth_handler,
  8981. void **cbdata)
  8982. {
  8983. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8984. if (request_info) {
  8985. const char *uri = request_info->local_uri;
  8986. size_t urilen = strlen(uri);
  8987. struct mg_handler_info *tmp_rh;
  8988. if (!conn || !conn->ctx) {
  8989. return 0;
  8990. }
  8991. mg_lock_context(conn->ctx);
  8992. /* first try for an exact match */
  8993. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8994. tmp_rh = tmp_rh->next) {
  8995. if (tmp_rh->handler_type == handler_type) {
  8996. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8997. if (handler_type == WEBSOCKET_HANDLER) {
  8998. *subprotocols = tmp_rh->subprotocols;
  8999. *connect_handler = tmp_rh->connect_handler;
  9000. *ready_handler = tmp_rh->ready_handler;
  9001. *data_handler = tmp_rh->data_handler;
  9002. *close_handler = tmp_rh->close_handler;
  9003. } else if (handler_type == REQUEST_HANDLER) {
  9004. *handler = tmp_rh->handler;
  9005. } else { /* AUTH_HANDLER */
  9006. *auth_handler = tmp_rh->auth_handler;
  9007. }
  9008. *cbdata = tmp_rh->cbdata;
  9009. mg_unlock_context(conn->ctx);
  9010. return 1;
  9011. }
  9012. }
  9013. }
  9014. /* next try for a partial match, we will accept uri/something */
  9015. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9016. tmp_rh = tmp_rh->next) {
  9017. if (tmp_rh->handler_type == handler_type) {
  9018. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9019. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9020. if (handler_type == WEBSOCKET_HANDLER) {
  9021. *subprotocols = tmp_rh->subprotocols;
  9022. *connect_handler = tmp_rh->connect_handler;
  9023. *ready_handler = tmp_rh->ready_handler;
  9024. *data_handler = tmp_rh->data_handler;
  9025. *close_handler = tmp_rh->close_handler;
  9026. } else if (handler_type == REQUEST_HANDLER) {
  9027. *handler = tmp_rh->handler;
  9028. } else { /* AUTH_HANDLER */
  9029. *auth_handler = tmp_rh->auth_handler;
  9030. }
  9031. *cbdata = tmp_rh->cbdata;
  9032. mg_unlock_context(conn->ctx);
  9033. return 1;
  9034. }
  9035. }
  9036. }
  9037. /* finally try for pattern match */
  9038. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9039. tmp_rh = tmp_rh->next) {
  9040. if (tmp_rh->handler_type == handler_type) {
  9041. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9042. if (handler_type == WEBSOCKET_HANDLER) {
  9043. *subprotocols = tmp_rh->subprotocols;
  9044. *connect_handler = tmp_rh->connect_handler;
  9045. *ready_handler = tmp_rh->ready_handler;
  9046. *data_handler = tmp_rh->data_handler;
  9047. *close_handler = tmp_rh->close_handler;
  9048. } else if (handler_type == REQUEST_HANDLER) {
  9049. *handler = tmp_rh->handler;
  9050. } else { /* AUTH_HANDLER */
  9051. *auth_handler = tmp_rh->auth_handler;
  9052. }
  9053. *cbdata = tmp_rh->cbdata;
  9054. mg_unlock_context(conn->ctx);
  9055. return 1;
  9056. }
  9057. }
  9058. }
  9059. mg_unlock_context(conn->ctx);
  9060. }
  9061. return 0; /* none found */
  9062. }
  9063. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9064. static int
  9065. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9066. void *cbdata)
  9067. {
  9068. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9069. if (pcallbacks->websocket_connect) {
  9070. return pcallbacks->websocket_connect(conn);
  9071. }
  9072. /* No handler set - assume "OK" */
  9073. return 0;
  9074. }
  9075. static void
  9076. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9077. {
  9078. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9079. if (pcallbacks->websocket_ready) {
  9080. pcallbacks->websocket_ready(conn);
  9081. }
  9082. }
  9083. static int
  9084. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9085. int bits,
  9086. char *data,
  9087. size_t len,
  9088. void *cbdata)
  9089. {
  9090. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9091. if (pcallbacks->websocket_data) {
  9092. return pcallbacks->websocket_data(conn, bits, data, len);
  9093. }
  9094. /* No handler set - assume "OK" */
  9095. return 1;
  9096. }
  9097. #endif
  9098. /* This is the heart of the Civetweb's logic.
  9099. * This function is called when the request is read, parsed and validated,
  9100. * and Civetweb must decide what action to take: serve a file, or
  9101. * a directory, or call embedded function, etcetera. */
  9102. static void
  9103. handle_request(struct mg_connection *conn)
  9104. {
  9105. if (conn) {
  9106. struct mg_request_info *ri = &conn->request_info;
  9107. char path[PATH_MAX];
  9108. int uri_len, ssl_index;
  9109. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9110. is_put_or_delete_request = 0, is_callback_resource = 0;
  9111. int i;
  9112. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9113. mg_request_handler callback_handler = NULL;
  9114. struct mg_websocket_subprotocols *subprotocols;
  9115. mg_websocket_connect_handler ws_connect_handler = NULL;
  9116. mg_websocket_ready_handler ws_ready_handler = NULL;
  9117. mg_websocket_data_handler ws_data_handler = NULL;
  9118. mg_websocket_close_handler ws_close_handler = NULL;
  9119. void *callback_data = NULL;
  9120. mg_authorization_handler auth_handler = NULL;
  9121. void *auth_callback_data = NULL;
  9122. #if !defined(NO_FILES)
  9123. time_t curtime = time(NULL);
  9124. char date[64];
  9125. #endif
  9126. path[0] = 0;
  9127. if (!ri) {
  9128. return;
  9129. }
  9130. /* 1. get the request url */
  9131. /* 1.1. split into url and query string */
  9132. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9133. != NULL) {
  9134. *((char *)conn->request_info.query_string++) = '\0';
  9135. }
  9136. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9137. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9138. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9139. if (ssl_index >= 0) {
  9140. redirect_to_https_port(conn, ssl_index);
  9141. } else {
  9142. /* A http to https forward port has been specified,
  9143. * but no https port to forward to. */
  9144. send_http_error(conn,
  9145. 503,
  9146. "%s",
  9147. "Error: SSL forward not configured properly");
  9148. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9149. }
  9150. return;
  9151. }
  9152. uri_len = (int)strlen(ri->local_uri);
  9153. /* 1.3. decode url (if config says so) */
  9154. if (should_decode_url(conn)) {
  9155. mg_url_decode(
  9156. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9157. }
  9158. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9159. * not possible */
  9160. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9161. /* step 1. completed, the url is known now */
  9162. uri_len = (int)strlen(ri->local_uri);
  9163. DEBUG_TRACE("URL: %s", ri->local_uri);
  9164. /* 3. if this ip has limited speed, set it for this connection */
  9165. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9166. get_remote_ip(conn),
  9167. ri->local_uri);
  9168. /* 4. call a "handle everything" callback, if registered */
  9169. if (conn->ctx->callbacks.begin_request != NULL) {
  9170. /* Note that since V1.7 the "begin_request" function is called
  9171. * before an authorization check. If an authorization check is
  9172. * required, use a request_handler instead. */
  9173. i = conn->ctx->callbacks.begin_request(conn);
  9174. if (i > 0) {
  9175. /* callback already processed the request. Store the
  9176. return value as a status code for the access log. */
  9177. conn->status_code = i;
  9178. discard_unread_request_data(conn);
  9179. return;
  9180. } else if (i == 0) {
  9181. /* civetweb should process the request */
  9182. } else {
  9183. /* unspecified - may change with the next version */
  9184. return;
  9185. }
  9186. }
  9187. /* request not yet handled by a handler or redirect, so the request
  9188. * is processed here */
  9189. /* 5. interpret the url to find out how the request must be handled
  9190. */
  9191. /* 5.1. first test, if the request targets the regular http(s)://
  9192. * protocol namespace or the websocket ws(s):// protocol namespace.
  9193. */
  9194. is_websocket_request = is_websocket_protocol(conn);
  9195. /* 5.2. check if the request will be handled by a callback */
  9196. if (get_request_handler(conn,
  9197. is_websocket_request ? WEBSOCKET_HANDLER
  9198. : REQUEST_HANDLER,
  9199. &callback_handler,
  9200. &subprotocols,
  9201. &ws_connect_handler,
  9202. &ws_ready_handler,
  9203. &ws_data_handler,
  9204. &ws_close_handler,
  9205. NULL,
  9206. &callback_data)) {
  9207. /* 5.2.1. A callback will handle this request. All requests
  9208. * handled
  9209. * by a callback have to be considered as requests to a script
  9210. * resource. */
  9211. is_callback_resource = 1;
  9212. is_script_resource = 1;
  9213. is_put_or_delete_request = is_put_or_delete_method(conn);
  9214. } else {
  9215. no_callback_resource:
  9216. /* 5.2.2. No callback is responsible for this request. The URI
  9217. * addresses a file based resource (static content or Lua/cgi
  9218. * scripts in the file system). */
  9219. is_callback_resource = 0;
  9220. interpret_uri(conn,
  9221. path,
  9222. sizeof(path),
  9223. &file.stat,
  9224. &is_found,
  9225. &is_script_resource,
  9226. &is_websocket_request,
  9227. &is_put_or_delete_request);
  9228. }
  9229. /* 6. authorization check */
  9230. /* 6.1. a custom authorization handler is installed */
  9231. if (get_request_handler(conn,
  9232. AUTH_HANDLER,
  9233. NULL,
  9234. NULL,
  9235. NULL,
  9236. NULL,
  9237. NULL,
  9238. NULL,
  9239. &auth_handler,
  9240. &auth_callback_data)) {
  9241. if (!auth_handler(conn, auth_callback_data)) {
  9242. return;
  9243. }
  9244. } else if (is_put_or_delete_request && !is_script_resource
  9245. && !is_callback_resource) {
  9246. /* 6.2. this request is a PUT/DELETE to a real file */
  9247. /* 6.2.1. thus, the server must have real files */
  9248. #if defined(NO_FILES)
  9249. if (1) {
  9250. #else
  9251. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9252. #endif
  9253. /* This server does not have any real files, thus the
  9254. * PUT/DELETE methods are not valid. */
  9255. send_http_error(conn,
  9256. 405,
  9257. "%s method not allowed",
  9258. conn->request_info.request_method);
  9259. return;
  9260. }
  9261. #if !defined(NO_FILES)
  9262. /* 6.2.2. Check if put authorization for static files is
  9263. * available.
  9264. */
  9265. if (!is_authorized_for_put(conn)) {
  9266. send_authorization_request(conn);
  9267. return;
  9268. }
  9269. #endif
  9270. } else {
  9271. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9272. * or it is a PUT or DELETE request to a resource that does not
  9273. * correspond to a file. Check authorization. */
  9274. if (!check_authorization(conn, path)) {
  9275. send_authorization_request(conn);
  9276. return;
  9277. }
  9278. }
  9279. /* request is authorized or does not need authorization */
  9280. /* 7. check if there are request handlers for this uri */
  9281. if (is_callback_resource) {
  9282. if (!is_websocket_request) {
  9283. i = callback_handler(conn, callback_data);
  9284. if (i > 0) {
  9285. /* Do nothing, callback has served the request. Store
  9286. * the
  9287. * return value as status code for the log and discard
  9288. * all
  9289. * data from the client not used by the callback. */
  9290. conn->status_code = i;
  9291. discard_unread_request_data(conn);
  9292. } else {
  9293. /* TODO (high): what if the handler did NOT handle the
  9294. * request */
  9295. /* The last version did handle this as a file request,
  9296. * but
  9297. * since a file request is not always a script resource,
  9298. * the authorization check might be different */
  9299. interpret_uri(conn,
  9300. path,
  9301. sizeof(path),
  9302. &file.stat,
  9303. &is_found,
  9304. &is_script_resource,
  9305. &is_websocket_request,
  9306. &is_put_or_delete_request);
  9307. callback_handler = NULL;
  9308. /* TODO (very low): goto is deprecated but for the
  9309. * moment,
  9310. * a goto is simpler than some curious loop. */
  9311. /* The situation "callback does not handle the request"
  9312. * needs to be reconsidered anyway. */
  9313. goto no_callback_resource;
  9314. }
  9315. } else {
  9316. #if defined(USE_WEBSOCKET)
  9317. handle_websocket_request(conn,
  9318. path,
  9319. is_callback_resource,
  9320. subprotocols,
  9321. ws_connect_handler,
  9322. ws_ready_handler,
  9323. ws_data_handler,
  9324. ws_close_handler,
  9325. callback_data);
  9326. #endif
  9327. }
  9328. return;
  9329. }
  9330. /* 8. handle websocket requests */
  9331. #if defined(USE_WEBSOCKET)
  9332. if (is_websocket_request) {
  9333. if (is_script_resource) {
  9334. /* Websocket Lua script */
  9335. handle_websocket_request(conn,
  9336. path,
  9337. 0 /* Lua Script */,
  9338. NULL,
  9339. NULL,
  9340. NULL,
  9341. NULL,
  9342. NULL,
  9343. &conn->ctx->callbacks);
  9344. } else {
  9345. #if defined(MG_LEGACY_INTERFACE)
  9346. handle_websocket_request(
  9347. conn,
  9348. path,
  9349. !is_script_resource /* could be deprecated global callback */,
  9350. NULL,
  9351. deprecated_websocket_connect_wrapper,
  9352. deprecated_websocket_ready_wrapper,
  9353. deprecated_websocket_data_wrapper,
  9354. NULL,
  9355. &conn->ctx->callbacks);
  9356. #else
  9357. send_http_error(conn, 404, "%s", "Not found");
  9358. #endif
  9359. }
  9360. return;
  9361. } else
  9362. #endif
  9363. #if defined(NO_FILES)
  9364. /* 9a. In case the server uses only callbacks, this uri is
  9365. * unknown.
  9366. * Then, all request handling ends here. */
  9367. send_http_error(conn, 404, "%s", "Not Found");
  9368. #else
  9369. /* 9b. This request is either for a static file or resource handled
  9370. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9371. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9372. send_http_error(conn, 404, "%s", "Not Found");
  9373. return;
  9374. }
  9375. /* 10. File is handled by a script. */
  9376. if (is_script_resource) {
  9377. handle_file_based_request(conn, path, &file);
  9378. return;
  9379. }
  9380. /* 11. Handle put/delete/mkcol requests */
  9381. if (is_put_or_delete_request) {
  9382. /* 11.1. PUT method */
  9383. if (!strcmp(ri->request_method, "PUT")) {
  9384. put_file(conn, path);
  9385. return;
  9386. }
  9387. /* 11.2. DELETE method */
  9388. if (!strcmp(ri->request_method, "DELETE")) {
  9389. delete_file(conn, path);
  9390. return;
  9391. }
  9392. /* 11.3. MKCOL method */
  9393. if (!strcmp(ri->request_method, "MKCOL")) {
  9394. mkcol(conn, path);
  9395. return;
  9396. }
  9397. /* 11.4. PATCH method
  9398. * This method is not supported for static resources,
  9399. * only for scripts (Lua, CGI) and callbacks. */
  9400. send_http_error(conn,
  9401. 405,
  9402. "%s method not allowed",
  9403. conn->request_info.request_method);
  9404. return;
  9405. }
  9406. /* 11. File does not exist, or it was configured that it should be
  9407. * hidden */
  9408. if (!is_found || (must_hide_file(conn, path))) {
  9409. send_http_error(conn, 404, "%s", "Not found");
  9410. return;
  9411. }
  9412. /* 12. Directory uris should end with a slash */
  9413. if (file.stat.is_directory && (uri_len > 0)
  9414. && (ri->local_uri[uri_len - 1] != '/')) {
  9415. gmt_time_string(date, sizeof(date), &curtime);
  9416. mg_printf(conn,
  9417. "HTTP/1.1 301 Moved Permanently\r\n"
  9418. "Location: %s/\r\n"
  9419. "Date: %s\r\n"
  9420. /* "Cache-Control: private\r\n" (= default) */
  9421. "Content-Length: 0\r\n"
  9422. "Connection: %s\r\n\r\n",
  9423. ri->request_uri,
  9424. date,
  9425. suggest_connection_header(conn));
  9426. return;
  9427. }
  9428. /* 13. Handle other methods than GET/HEAD */
  9429. /* 13.1. Handle PROPFIND */
  9430. if (!strcmp(ri->request_method, "PROPFIND")) {
  9431. handle_propfind(conn, path, &file.stat);
  9432. return;
  9433. }
  9434. /* 13.2. Handle OPTIONS for files */
  9435. if (!strcmp(ri->request_method, "OPTIONS")) {
  9436. /* This standard handler is only used for real files.
  9437. * Scripts should support the OPTIONS method themselves, to allow a
  9438. * maximum flexibility.
  9439. * Lua and CGI scripts may fully support CORS this way (including
  9440. * preflights). */
  9441. send_options(conn);
  9442. return;
  9443. }
  9444. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9445. if (0 != strcmp(ri->request_method, "GET")
  9446. && 0 != strcmp(ri->request_method, "HEAD")) {
  9447. send_http_error(conn,
  9448. 405,
  9449. "%s method not allowed",
  9450. conn->request_info.request_method);
  9451. return;
  9452. }
  9453. /* 14. directories */
  9454. if (file.stat.is_directory) {
  9455. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9456. /* 14.1. use a substitute file */
  9457. /* TODO (high): substitute index may be a script resource.
  9458. * define what should be possible in this case. */
  9459. } else {
  9460. /* 14.2. no substitute file */
  9461. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9462. "yes")) {
  9463. handle_directory_request(conn, path);
  9464. } else {
  9465. send_http_error(conn,
  9466. 403,
  9467. "%s",
  9468. "Error: Directory listing denied");
  9469. }
  9470. return;
  9471. }
  9472. }
  9473. handle_file_based_request(conn, path, &file);
  9474. #endif /* !defined(NO_FILES) */
  9475. #if 0
  9476. /* Perform redirect and auth checks before calling begin_request()
  9477. * handler.
  9478. * Otherwise, begin_request() would need to perform auth checks and
  9479. * redirects. */
  9480. #endif
  9481. }
  9482. return;
  9483. }
  9484. static void
  9485. handle_file_based_request(struct mg_connection *conn,
  9486. const char *path,
  9487. struct mg_file *file)
  9488. {
  9489. if (!conn || !conn->ctx) {
  9490. return;
  9491. }
  9492. if (0) {
  9493. #ifdef USE_LUA
  9494. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9495. strlen(
  9496. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9497. path) > 0) {
  9498. /* Lua server page: an SSI like page containing mostly plain html
  9499. * code
  9500. * plus some tags with server generated contents. */
  9501. handle_lsp_request(conn, path, file, NULL);
  9502. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9503. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9504. path) > 0) {
  9505. /* Lua in-server module script: a CGI like script used to generate
  9506. * the
  9507. * entire reply. */
  9508. mg_exec_lua_script(conn, path, NULL);
  9509. #endif
  9510. #if defined(USE_DUKTAPE)
  9511. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9512. strlen(
  9513. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9514. path) > 0) {
  9515. /* Call duktape to generate the page */
  9516. mg_exec_duktape_script(conn, path);
  9517. #endif
  9518. #if !defined(NO_CGI)
  9519. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9520. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9521. path) > 0) {
  9522. /* CGI scripts may support all HTTP methods */
  9523. handle_cgi_request(conn, path);
  9524. #endif /* !NO_CGI */
  9525. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9526. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9527. path) > 0) {
  9528. handle_ssi_file_request(conn, path, file);
  9529. #if !defined(NO_CACHING)
  9530. } else if ((!conn->in_error_handler)
  9531. && is_not_modified(conn, &file->stat)) {
  9532. /* Send 304 "Not Modified" - this must not send any body data */
  9533. handle_not_modified_static_file_request(conn, file);
  9534. #endif /* !NO_CACHING */
  9535. } else {
  9536. handle_static_file_request(conn, path, file, NULL, NULL);
  9537. }
  9538. }
  9539. static void
  9540. close_all_listening_sockets(struct mg_context *ctx)
  9541. {
  9542. unsigned int i;
  9543. if (!ctx) {
  9544. return;
  9545. }
  9546. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9547. closesocket(ctx->listening_sockets[i].sock);
  9548. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9549. }
  9550. mg_free(ctx->listening_sockets);
  9551. ctx->listening_sockets = NULL;
  9552. mg_free(ctx->listening_socket_fds);
  9553. ctx->listening_socket_fds = NULL;
  9554. }
  9555. /* Valid listening port specification is: [ip_address:]port[s]
  9556. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9557. * Examples for IPv6: [::]:80, [::1]:80,
  9558. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9559. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9560. * In order to bind to both, IPv4 and IPv6, you can either add
  9561. * both ports using 8080,[::]:8080, or the short form +8080.
  9562. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9563. * one only accepting IPv4 the other only IPv6. +8080 creates
  9564. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9565. * environment, they might work differently, or might not work
  9566. * at all - it must be tested what options work best in the
  9567. * relevant network environment.
  9568. */
  9569. static int
  9570. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9571. {
  9572. unsigned int a, b, c, d, port;
  9573. int ch, len;
  9574. #if defined(USE_IPV6)
  9575. char buf[100] = {0};
  9576. #endif
  9577. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9578. * Also, all-zeroes in the socket address means binding to all addresses
  9579. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9580. memset(so, 0, sizeof(*so));
  9581. so->lsa.sin.sin_family = AF_INET;
  9582. *ip_version = 0;
  9583. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9584. == 5) {
  9585. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9586. so->lsa.sin.sin_addr.s_addr =
  9587. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9588. so->lsa.sin.sin_port = htons((uint16_t)port);
  9589. *ip_version = 4;
  9590. #if defined(USE_IPV6)
  9591. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9592. && mg_inet_pton(
  9593. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9594. /* IPv6 address, examples: see above */
  9595. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9596. */
  9597. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9598. *ip_version = 6;
  9599. #endif
  9600. } else if ((vec->ptr[0] == '+')
  9601. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9602. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9603. /* Add 1 to len for the + character we skipped before */
  9604. len++;
  9605. #if defined(USE_IPV6)
  9606. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9607. so->lsa.sin6.sin6_family = AF_INET6;
  9608. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9609. *ip_version = 4 + 6;
  9610. #else
  9611. /* Bind to IPv4 only, since IPv6 is not built in. */
  9612. so->lsa.sin.sin_port = htons((uint16_t)port);
  9613. *ip_version = 4;
  9614. #endif
  9615. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9616. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9617. so->lsa.sin.sin_port = htons((uint16_t)port);
  9618. *ip_version = 4;
  9619. } else {
  9620. /* Parsing failure. Make port invalid. */
  9621. port = 0;
  9622. len = 0;
  9623. }
  9624. /* sscanf and the option splitting code ensure the following condition
  9625. */
  9626. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9627. *ip_version = 0;
  9628. return 0;
  9629. }
  9630. ch = vec->ptr[len]; /* Next character after the port number */
  9631. so->is_ssl = (ch == 's');
  9632. so->ssl_redir = (ch == 'r');
  9633. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9634. if (is_valid_port(port)
  9635. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9636. return 1;
  9637. }
  9638. /* Reset ip_version to 0 of there is an error */
  9639. *ip_version = 0;
  9640. return 0;
  9641. }
  9642. static int
  9643. set_ports_option(struct mg_context *ctx)
  9644. {
  9645. const char *list;
  9646. int on = 1;
  9647. #if defined(USE_IPV6)
  9648. int off = 0;
  9649. #endif
  9650. struct vec vec;
  9651. struct socket so, *ptr;
  9652. struct pollfd *pfd;
  9653. union usa usa;
  9654. socklen_t len;
  9655. int ip_version;
  9656. int portsTotal = 0;
  9657. int portsOk = 0;
  9658. if (!ctx) {
  9659. return 0;
  9660. }
  9661. memset(&so, 0, sizeof(so));
  9662. memset(&usa, 0, sizeof(usa));
  9663. len = sizeof(usa);
  9664. list = ctx->config[LISTENING_PORTS];
  9665. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9666. portsTotal++;
  9667. if (!parse_port_string(&vec, &so, &ip_version)) {
  9668. mg_cry(fc(ctx),
  9669. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9670. (int)vec.len,
  9671. vec.ptr,
  9672. portsTotal,
  9673. "[IP_ADDRESS:]PORT[s|r]");
  9674. continue;
  9675. }
  9676. #if !defined(NO_SSL)
  9677. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9678. mg_cry(fc(ctx),
  9679. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9680. "option set?",
  9681. portsTotal);
  9682. continue;
  9683. }
  9684. #endif
  9685. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9686. == INVALID_SOCKET) {
  9687. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9688. continue;
  9689. }
  9690. #ifdef _WIN32
  9691. /* Windows SO_REUSEADDR lets many procs binds to a
  9692. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9693. * if someone already has the socket -- DTL */
  9694. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9695. * Windows might need a few seconds before
  9696. * the same port can be used again in the
  9697. * same process, so a short Sleep may be
  9698. * required between mg_stop and mg_start.
  9699. */
  9700. if (setsockopt(so.sock,
  9701. SOL_SOCKET,
  9702. SO_EXCLUSIVEADDRUSE,
  9703. (SOCK_OPT_TYPE)&on,
  9704. sizeof(on)) != 0) {
  9705. /* Set reuse option, but don't abort on errors. */
  9706. mg_cry(fc(ctx),
  9707. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9708. portsTotal);
  9709. }
  9710. #else
  9711. if (setsockopt(so.sock,
  9712. SOL_SOCKET,
  9713. SO_REUSEADDR,
  9714. (SOCK_OPT_TYPE)&on,
  9715. sizeof(on)) != 0) {
  9716. /* Set reuse option, but don't abort on errors. */
  9717. mg_cry(fc(ctx),
  9718. "cannot set socket option SO_REUSEADDR (entry %i)",
  9719. portsTotal);
  9720. }
  9721. #endif
  9722. if (ip_version > 4) {
  9723. #if defined(USE_IPV6)
  9724. if (ip_version == 6) {
  9725. if (so.lsa.sa.sa_family == AF_INET6
  9726. && setsockopt(so.sock,
  9727. IPPROTO_IPV6,
  9728. IPV6_V6ONLY,
  9729. (void *)&off,
  9730. sizeof(off)) != 0) {
  9731. /* Set IPv6 only option, but don't abort on errors. */
  9732. mg_cry(fc(ctx),
  9733. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9734. portsTotal);
  9735. }
  9736. }
  9737. #else
  9738. mg_cry(fc(ctx), "IPv6 not available");
  9739. closesocket(so.sock);
  9740. so.sock = INVALID_SOCKET;
  9741. continue;
  9742. #endif
  9743. }
  9744. if (so.lsa.sa.sa_family == AF_INET) {
  9745. len = sizeof(so.lsa.sin);
  9746. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9747. mg_cry(fc(ctx),
  9748. "cannot bind to %.*s: %d (%s)",
  9749. (int)vec.len,
  9750. vec.ptr,
  9751. (int)ERRNO,
  9752. strerror(errno));
  9753. closesocket(so.sock);
  9754. so.sock = INVALID_SOCKET;
  9755. continue;
  9756. }
  9757. }
  9758. #if defined(USE_IPV6)
  9759. else if (so.lsa.sa.sa_family == AF_INET6) {
  9760. len = sizeof(so.lsa.sin6);
  9761. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9762. mg_cry(fc(ctx),
  9763. "cannot bind to IPv6 %.*s: %d (%s)",
  9764. (int)vec.len,
  9765. vec.ptr,
  9766. (int)ERRNO,
  9767. strerror(errno));
  9768. closesocket(so.sock);
  9769. so.sock = INVALID_SOCKET;
  9770. continue;
  9771. }
  9772. }
  9773. #endif
  9774. else {
  9775. mg_cry(fc(ctx),
  9776. "cannot bind: address family not supported (entry %i)",
  9777. portsTotal);
  9778. continue;
  9779. }
  9780. if (listen(so.sock, SOMAXCONN) != 0) {
  9781. mg_cry(fc(ctx),
  9782. "cannot listen to %.*s: %d (%s)",
  9783. (int)vec.len,
  9784. vec.ptr,
  9785. (int)ERRNO,
  9786. strerror(errno));
  9787. closesocket(so.sock);
  9788. so.sock = INVALID_SOCKET;
  9789. continue;
  9790. }
  9791. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9792. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9793. int err = (int)ERRNO;
  9794. mg_cry(fc(ctx),
  9795. "call to getsockname failed %.*s: %d (%s)",
  9796. (int)vec.len,
  9797. vec.ptr,
  9798. err,
  9799. strerror(errno));
  9800. closesocket(so.sock);
  9801. so.sock = INVALID_SOCKET;
  9802. continue;
  9803. }
  9804. /* Update lsa port in case of random free ports */
  9805. #if defined(USE_IPV6)
  9806. if (so.lsa.sa.sa_family == AF_INET6) {
  9807. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9808. } else
  9809. #endif
  9810. {
  9811. so.lsa.sin.sin_port = usa.sin.sin_port;
  9812. }
  9813. if ((ptr = (struct socket *)
  9814. mg_realloc(ctx->listening_sockets,
  9815. (ctx->num_listening_sockets + 1)
  9816. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9817. mg_cry(fc(ctx), "%s", "Out of memory");
  9818. closesocket(so.sock);
  9819. so.sock = INVALID_SOCKET;
  9820. continue;
  9821. }
  9822. if ((pfd = (struct pollfd *)mg_realloc(
  9823. ctx->listening_socket_fds,
  9824. (ctx->num_listening_sockets + 1)
  9825. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9826. mg_cry(fc(ctx), "%s", "Out of memory");
  9827. closesocket(so.sock);
  9828. so.sock = INVALID_SOCKET;
  9829. mg_free(ptr);
  9830. continue;
  9831. }
  9832. set_close_on_exec(so.sock, fc(ctx));
  9833. ctx->listening_sockets = ptr;
  9834. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9835. ctx->listening_socket_fds = pfd;
  9836. ctx->num_listening_sockets++;
  9837. portsOk++;
  9838. }
  9839. if (portsOk != portsTotal) {
  9840. close_all_listening_sockets(ctx);
  9841. portsOk = 0;
  9842. }
  9843. return portsOk;
  9844. }
  9845. static const char *
  9846. header_val(const struct mg_connection *conn, const char *header)
  9847. {
  9848. const char *header_value;
  9849. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9850. return "-";
  9851. } else {
  9852. return header_value;
  9853. }
  9854. }
  9855. static void
  9856. log_access(const struct mg_connection *conn)
  9857. {
  9858. const struct mg_request_info *ri;
  9859. struct mg_file fi;
  9860. char date[64], src_addr[IP_ADDR_STR_LEN];
  9861. struct tm *tm;
  9862. const char *referer;
  9863. const char *user_agent;
  9864. char buf[4096];
  9865. if (!conn || !conn->ctx) {
  9866. return;
  9867. }
  9868. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9869. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9870. == 0) {
  9871. fi.access.fp = NULL;
  9872. }
  9873. } else {
  9874. fi.access.fp = NULL;
  9875. }
  9876. /* Log is written to a file and/or a callback. If both are not set,
  9877. * executing the rest of the function is pointless. */
  9878. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9879. return;
  9880. }
  9881. tm = localtime(&conn->conn_birth_time);
  9882. if (tm != NULL) {
  9883. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9884. } else {
  9885. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9886. date[sizeof(date) - 1] = '\0';
  9887. }
  9888. ri = &conn->request_info;
  9889. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9890. referer = header_val(conn, "Referer");
  9891. user_agent = header_val(conn, "User-Agent");
  9892. mg_snprintf(conn,
  9893. NULL, /* Ignore truncation in access log */
  9894. buf,
  9895. sizeof(buf),
  9896. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9897. src_addr,
  9898. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9899. date,
  9900. ri->request_method ? ri->request_method : "-",
  9901. ri->request_uri ? ri->request_uri : "-",
  9902. ri->query_string ? "?" : "",
  9903. ri->query_string ? ri->query_string : "",
  9904. ri->http_version,
  9905. conn->status_code,
  9906. conn->num_bytes_sent,
  9907. referer,
  9908. user_agent);
  9909. if (conn->ctx->callbacks.log_access) {
  9910. conn->ctx->callbacks.log_access(conn, buf);
  9911. }
  9912. if (fi.access.fp) {
  9913. int ok = 1;
  9914. flockfile(fi.access.fp);
  9915. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9916. ok = 0;
  9917. }
  9918. if (fflush(fi.access.fp) != 0) {
  9919. ok = 0;
  9920. }
  9921. funlockfile(fi.access.fp);
  9922. if (mg_fclose(&fi.access) != 0) {
  9923. ok = 0;
  9924. }
  9925. if (!ok) {
  9926. mg_cry(conn,
  9927. "Error writing log file %s",
  9928. conn->ctx->config[ACCESS_LOG_FILE]);
  9929. }
  9930. }
  9931. }
  9932. /* Verify given socket address against the ACL.
  9933. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9934. */
  9935. static int
  9936. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9937. {
  9938. int allowed, flag;
  9939. uint32_t net, mask;
  9940. struct vec vec;
  9941. if (ctx) {
  9942. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9943. /* If any ACL is set, deny by default */
  9944. allowed = (list == NULL) ? '+' : '-';
  9945. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9946. flag = vec.ptr[0];
  9947. if ((flag != '+' && flag != '-')
  9948. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9949. mg_cry(fc(ctx),
  9950. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9951. __func__);
  9952. return -1;
  9953. }
  9954. if (net == (remote_ip & mask)) {
  9955. allowed = flag;
  9956. }
  9957. }
  9958. return allowed == '+';
  9959. }
  9960. return -1;
  9961. }
  9962. #if !defined(_WIN32)
  9963. static int
  9964. set_uid_option(struct mg_context *ctx)
  9965. {
  9966. struct passwd *pw;
  9967. if (ctx) {
  9968. const char *uid = ctx->config[RUN_AS_USER];
  9969. int success = 0;
  9970. if (uid == NULL) {
  9971. success = 1;
  9972. } else {
  9973. if ((pw = getpwnam(uid)) == NULL) {
  9974. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9975. } else if (setgid(pw->pw_gid) == -1) {
  9976. mg_cry(fc(ctx),
  9977. "%s: setgid(%s): %s",
  9978. __func__,
  9979. uid,
  9980. strerror(errno));
  9981. } else if (setgroups(0, NULL)) {
  9982. mg_cry(fc(ctx),
  9983. "%s: setgroups(): %s",
  9984. __func__,
  9985. strerror(errno));
  9986. } else if (setuid(pw->pw_uid) == -1) {
  9987. mg_cry(fc(ctx),
  9988. "%s: setuid(%s): %s",
  9989. __func__,
  9990. uid,
  9991. strerror(errno));
  9992. } else {
  9993. success = 1;
  9994. }
  9995. }
  9996. return success;
  9997. }
  9998. return 0;
  9999. }
  10000. #endif /* !_WIN32 */
  10001. static void
  10002. tls_dtor(void *key)
  10003. {
  10004. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10005. /* key == pthread_getspecific(sTlsKey); */
  10006. if (tls) {
  10007. if (tls->is_master == 2) {
  10008. tls->is_master = -3; /* Mark memory as dead */
  10009. mg_free(tls);
  10010. }
  10011. }
  10012. pthread_setspecific(sTlsKey, NULL);
  10013. }
  10014. #if !defined(NO_SSL)
  10015. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  10016. static unsigned long
  10017. ssl_id_callback(void)
  10018. {
  10019. #ifdef _WIN32
  10020. return GetCurrentThreadId();
  10021. #else
  10022. #ifdef __clang__
  10023. #pragma clang diagnostic push
  10024. #pragma clang diagnostic ignored "-Wunreachable-code"
  10025. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  10026. * or not, so one of the two conditions will be unreachable by construction.
  10027. * Unfortunately the C standard does not define a way to check this at
  10028. * compile time, since the #if preprocessor conditions can not use the sizeof
  10029. * operator as an argument. */
  10030. #endif
  10031. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  10032. /* This is the problematic case for CRYPTO_set_id_callback:
  10033. * The OS pthread_t can not be cast to unsigned long. */
  10034. struct mg_workerTLS *tls =
  10035. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  10036. if (tls == NULL) {
  10037. /* SSL called from an unknown thread: Create some thread index.
  10038. */
  10039. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  10040. tls->is_master = -2; /* -2 means "3rd party thread" */
  10041. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10042. pthread_setspecific(sTlsKey, tls);
  10043. }
  10044. return tls->thread_idx;
  10045. } else {
  10046. /* pthread_t may be any data type, so a simple cast to unsigned long
  10047. * can rise a warning/error, depending on the platform.
  10048. * Here memcpy is used as an anything-to-anything cast. */
  10049. unsigned long ret = 0;
  10050. pthread_t t = pthread_self();
  10051. memcpy(&ret, &t, sizeof(pthread_t));
  10052. return ret;
  10053. }
  10054. #ifdef __clang__
  10055. #pragma clang diagnostic pop
  10056. #endif
  10057. #endif
  10058. }
  10059. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10060. static const char *ssl_error(void);
  10061. static int
  10062. refresh_trust(struct mg_connection *conn)
  10063. {
  10064. static int reload_lock = 0;
  10065. static long int data_check = 0;
  10066. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10067. struct stat cert_buf;
  10068. long int t;
  10069. char *pem;
  10070. int should_verify_peer;
  10071. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10072. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10073. * refresh_trust still can not work. */
  10074. return 0;
  10075. }
  10076. t = data_check;
  10077. if (stat(pem, &cert_buf) != -1) {
  10078. t = (long int)cert_buf.st_mtime;
  10079. }
  10080. if (data_check != t) {
  10081. data_check = t;
  10082. should_verify_peer =
  10083. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10084. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10085. == 0);
  10086. if (should_verify_peer) {
  10087. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10088. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10089. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10090. ca_file,
  10091. ca_path) != 1) {
  10092. mg_cry(fc(conn->ctx),
  10093. "SSL_CTX_load_verify_locations error: %s "
  10094. "ssl_verify_peer requires setting "
  10095. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10096. "present in "
  10097. "the .conf file?",
  10098. ssl_error());
  10099. return 0;
  10100. }
  10101. }
  10102. if (1 == mg_atomic_inc(p_reload_lock)) {
  10103. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10104. return 0;
  10105. }
  10106. *p_reload_lock = 0;
  10107. }
  10108. }
  10109. /* lock while cert is reloading */
  10110. while (*p_reload_lock) {
  10111. sleep(1);
  10112. }
  10113. return 1;
  10114. }
  10115. static pthread_mutex_t *ssl_mutexes;
  10116. static int
  10117. sslize(struct mg_connection *conn,
  10118. SSL_CTX *s,
  10119. int (*func)(SSL *),
  10120. volatile int *stop_server)
  10121. {
  10122. int ret, err;
  10123. int short_trust;
  10124. unsigned i;
  10125. if (!conn) {
  10126. return 0;
  10127. }
  10128. short_trust =
  10129. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10130. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10131. if (short_trust) {
  10132. int trust_ret = refresh_trust(conn);
  10133. if (!trust_ret) {
  10134. return trust_ret;
  10135. }
  10136. }
  10137. conn->ssl = SSL_new(s);
  10138. if (conn->ssl == NULL) {
  10139. return 0;
  10140. }
  10141. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10142. if (ret != 1) {
  10143. err = SSL_get_error(conn->ssl, ret);
  10144. (void)err; /* TODO: set some error message */
  10145. SSL_free(conn->ssl);
  10146. conn->ssl = NULL;
  10147. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10148. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10149. ERR_remove_state(0);
  10150. return 0;
  10151. }
  10152. /* SSL functions may fail and require to be called again:
  10153. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10154. * Here "func" could be SSL_connect or SSL_accept. */
  10155. for (i = 16; i <= 1024; i *= 2) {
  10156. ret = func(conn->ssl);
  10157. if (ret != 1) {
  10158. err = SSL_get_error(conn->ssl, ret);
  10159. if ((err == SSL_ERROR_WANT_CONNECT)
  10160. || (err == SSL_ERROR_WANT_ACCEPT)
  10161. || (err == SSL_ERROR_WANT_READ)
  10162. || (err == SSL_ERROR_WANT_WRITE)) {
  10163. /* Need to retry the function call "later".
  10164. * See https://linux.die.net/man/3/ssl_get_error
  10165. * This is typical for non-blocking sockets. */
  10166. if (*stop_server) {
  10167. /* Don't wait if the server is going to be stopped. */
  10168. break;
  10169. }
  10170. mg_sleep(i);
  10171. } else if (err == SSL_ERROR_SYSCALL) {
  10172. /* This is an IO error. Look at errno. */
  10173. err = errno;
  10174. /* TODO: set some error message */
  10175. break;
  10176. } else {
  10177. /* This is an SSL specific error */
  10178. /* TODO: set some error message */
  10179. break;
  10180. }
  10181. } else {
  10182. /* success */
  10183. break;
  10184. }
  10185. }
  10186. if (ret != 1) {
  10187. SSL_free(conn->ssl);
  10188. conn->ssl = NULL;
  10189. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10190. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10191. ERR_remove_state(0);
  10192. return 0;
  10193. }
  10194. return 1;
  10195. }
  10196. /* Return OpenSSL error message (from CRYPTO lib) */
  10197. static const char *
  10198. ssl_error(void)
  10199. {
  10200. unsigned long err;
  10201. err = ERR_get_error();
  10202. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10203. }
  10204. static int
  10205. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10206. {
  10207. int i;
  10208. const char hexdigit[] = "0123456789abcdef";
  10209. if (memlen <= 0 || buflen <= 0) {
  10210. return 0;
  10211. }
  10212. if (buflen < (3 * memlen)) {
  10213. return 0;
  10214. }
  10215. for (i = 0; i < memlen; i++) {
  10216. if (i > 0) {
  10217. buf[3 * i - 1] = ' ';
  10218. }
  10219. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10220. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10221. }
  10222. buf[3 * memlen - 1] = 0;
  10223. return 1;
  10224. }
  10225. static void
  10226. ssl_get_client_cert_info(struct mg_connection *conn)
  10227. {
  10228. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10229. if (cert) {
  10230. char str_subject[1024];
  10231. char str_issuer[1024];
  10232. char str_serial[1024];
  10233. char str_finger[1024];
  10234. unsigned char buf[256];
  10235. int len;
  10236. unsigned int ulen;
  10237. /* Handle to algorithm used for fingerprint */
  10238. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10239. /* Get Subject and issuer */
  10240. X509_NAME *subj = X509_get_subject_name(cert);
  10241. X509_NAME *iss = X509_get_issuer_name(cert);
  10242. /* Get serial number */
  10243. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10244. /* Translate subject and issuer to a string */
  10245. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10246. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10247. /* Translate serial number to a hex string */
  10248. len = i2c_ASN1_INTEGER(serial, NULL);
  10249. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10250. unsigned char *pbuf = buf;
  10251. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10252. if (!hexdump2string(
  10253. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10254. *str_serial = 0;
  10255. }
  10256. } else {
  10257. *str_serial = 0;
  10258. }
  10259. /* Calculate SHA1 fingerprint and store as a hex string */
  10260. ulen = 0;
  10261. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10262. if (!hexdump2string(
  10263. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10264. *str_finger = 0;
  10265. }
  10266. conn->request_info.client_cert =
  10267. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10268. if (conn->request_info.client_cert) {
  10269. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10270. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10271. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10272. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10273. } else {
  10274. /* TODO: write some OOM message */
  10275. }
  10276. X509_free(cert);
  10277. }
  10278. }
  10279. static void
  10280. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10281. {
  10282. (void)line;
  10283. (void)file;
  10284. if (mode & 1) {
  10285. /* 1 is CRYPTO_LOCK */
  10286. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10287. } else {
  10288. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10289. }
  10290. }
  10291. #if !defined(NO_SSL_DL)
  10292. static void *
  10293. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10294. {
  10295. union {
  10296. void *p;
  10297. void (*fp)(void);
  10298. } u;
  10299. void *dll_handle;
  10300. struct ssl_func *fp;
  10301. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10302. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10303. return NULL;
  10304. }
  10305. for (fp = sw; fp->name != NULL; fp++) {
  10306. #ifdef _WIN32
  10307. /* GetProcAddress() returns pointer to function */
  10308. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10309. #else
  10310. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10311. * pointers to function pointers. We need to use a union to make a
  10312. * cast. */
  10313. u.p = dlsym(dll_handle, fp->name);
  10314. #endif /* _WIN32 */
  10315. if (u.fp == NULL) {
  10316. mg_cry(fc(ctx),
  10317. "%s: %s: cannot find %s",
  10318. __func__,
  10319. dll_name,
  10320. fp->name);
  10321. dlclose(dll_handle);
  10322. return NULL;
  10323. } else {
  10324. fp->ptr = u.fp;
  10325. }
  10326. }
  10327. return dll_handle;
  10328. }
  10329. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10330. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10331. #endif /* NO_SSL_DL */
  10332. #if defined(SSL_ALREADY_INITIALIZED)
  10333. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10334. #else
  10335. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10336. #endif
  10337. static int
  10338. initialize_ssl(struct mg_context *ctx)
  10339. {
  10340. int i;
  10341. size_t size;
  10342. #if !defined(NO_SSL_DL)
  10343. if (!cryptolib_dll_handle) {
  10344. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10345. if (!cryptolib_dll_handle) {
  10346. return 0;
  10347. }
  10348. }
  10349. #endif /* NO_SSL_DL */
  10350. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10351. return 1;
  10352. }
  10353. /* Initialize locking callbacks, needed for thread safety.
  10354. * http://www.openssl.org/support/faq.html#PROG1
  10355. */
  10356. i = CRYPTO_num_locks();
  10357. if (i < 0) {
  10358. i = 0;
  10359. }
  10360. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10361. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10362. mg_cry(fc(ctx),
  10363. "%s: cannot allocate mutexes: %s",
  10364. __func__,
  10365. ssl_error());
  10366. return 0;
  10367. }
  10368. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10369. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10370. }
  10371. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10372. CRYPTO_set_id_callback(&ssl_id_callback);
  10373. return 1;
  10374. }
  10375. static int
  10376. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10377. {
  10378. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10379. mg_cry(fc(ctx),
  10380. "%s: cannot open certificate file %s: %s",
  10381. __func__,
  10382. pem,
  10383. ssl_error());
  10384. return 0;
  10385. }
  10386. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10387. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10388. mg_cry(fc(ctx),
  10389. "%s: cannot open private key file %s: %s",
  10390. __func__,
  10391. pem,
  10392. ssl_error());
  10393. return 0;
  10394. }
  10395. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10396. mg_cry(fc(ctx),
  10397. "%s: certificate and private key do not match: %s",
  10398. __func__,
  10399. pem);
  10400. return 0;
  10401. }
  10402. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10403. mg_cry(fc(ctx),
  10404. "%s: cannot use certificate chain file %s: %s",
  10405. __func__,
  10406. pem,
  10407. ssl_error());
  10408. return 0;
  10409. }
  10410. return 1;
  10411. }
  10412. static long
  10413. ssl_get_protocol(int version_id)
  10414. {
  10415. long ret = SSL_OP_ALL;
  10416. if (version_id > 0)
  10417. ret |= SSL_OP_NO_SSLv2;
  10418. if (version_id > 1)
  10419. ret |= SSL_OP_NO_SSLv3;
  10420. if (version_id > 2)
  10421. ret |= SSL_OP_NO_TLSv1;
  10422. if (version_id > 3)
  10423. ret |= SSL_OP_NO_TLSv1_1;
  10424. return ret;
  10425. }
  10426. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10427. static int
  10428. set_ssl_option(struct mg_context *ctx)
  10429. {
  10430. const char *pem;
  10431. int callback_ret;
  10432. int should_verify_peer;
  10433. const char *ca_path;
  10434. const char *ca_file;
  10435. int use_default_verify_paths;
  10436. int verify_depth;
  10437. time_t now_rt = time(NULL);
  10438. struct timespec now_mt;
  10439. md5_byte_t ssl_context_id[16];
  10440. md5_state_t md5state;
  10441. int protocol_ver;
  10442. /* If PEM file is not specified and the init_ssl callback
  10443. * is not specified, skip SSL initialization. */
  10444. if (!ctx) {
  10445. return 0;
  10446. }
  10447. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10448. && ctx->callbacks.init_ssl == NULL) {
  10449. return 1;
  10450. }
  10451. if (!initialize_ssl(ctx)) {
  10452. return 0;
  10453. }
  10454. #if !defined(NO_SSL_DL)
  10455. if (!ssllib_dll_handle) {
  10456. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10457. if (!ssllib_dll_handle) {
  10458. return 0;
  10459. }
  10460. }
  10461. #endif /* NO_SSL_DL */
  10462. /* Initialize SSL library */
  10463. SSL_library_init();
  10464. SSL_load_error_strings();
  10465. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10466. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10467. return 0;
  10468. }
  10469. SSL_CTX_clear_options(ctx->ssl_ctx,
  10470. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10471. | SSL_OP_NO_TLSv1_1);
  10472. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10473. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10474. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10475. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10476. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10477. /* If a callback has been specified, call it. */
  10478. callback_ret =
  10479. (ctx->callbacks.init_ssl == NULL)
  10480. ? 0
  10481. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10482. /* If callback returns 0, civetweb sets up the SSL certificate.
  10483. * If it returns 1, civetweb assumes the calback already did this.
  10484. * If it returns -1, initializing ssl fails. */
  10485. if (callback_ret < 0) {
  10486. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10487. return 0;
  10488. }
  10489. if (callback_ret > 0) {
  10490. if (pem != NULL) {
  10491. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10492. }
  10493. return 1;
  10494. }
  10495. /* Use some UID as session context ID. */
  10496. md5_init(&md5state);
  10497. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10498. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10499. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10500. md5_append(&md5state,
  10501. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10502. strlen(ctx->config[LISTENING_PORTS]));
  10503. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10504. md5_finish(&md5state, ssl_context_id);
  10505. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10506. (const unsigned char *)&ssl_context_id,
  10507. sizeof(ssl_context_id));
  10508. if (pem != NULL) {
  10509. if (!ssl_use_pem_file(ctx, pem)) {
  10510. return 0;
  10511. }
  10512. }
  10513. should_verify_peer =
  10514. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10515. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10516. use_default_verify_paths =
  10517. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10518. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10519. if (should_verify_peer) {
  10520. ca_path = ctx->config[SSL_CA_PATH];
  10521. ca_file = ctx->config[SSL_CA_FILE];
  10522. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10523. != 1) {
  10524. mg_cry(fc(ctx),
  10525. "SSL_CTX_load_verify_locations error: %s "
  10526. "ssl_verify_peer requires setting "
  10527. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10528. "present in "
  10529. "the .conf file?",
  10530. ssl_error());
  10531. return 0;
  10532. }
  10533. SSL_CTX_set_verify(ctx->ssl_ctx,
  10534. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10535. NULL);
  10536. if (use_default_verify_paths
  10537. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10538. mg_cry(fc(ctx),
  10539. "SSL_CTX_set_default_verify_paths error: %s",
  10540. ssl_error());
  10541. return 0;
  10542. }
  10543. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10544. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10545. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10546. }
  10547. }
  10548. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10549. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10550. != 1) {
  10551. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10552. }
  10553. }
  10554. return 1;
  10555. }
  10556. static void
  10557. uninitialize_ssl(struct mg_context *ctx)
  10558. {
  10559. int i;
  10560. (void)ctx;
  10561. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10562. /* Shutdown according to
  10563. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10564. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10565. */
  10566. CRYPTO_set_locking_callback(NULL);
  10567. CRYPTO_set_id_callback(NULL);
  10568. ENGINE_cleanup();
  10569. CONF_modules_unload(1);
  10570. ERR_free_strings();
  10571. EVP_cleanup();
  10572. CRYPTO_cleanup_all_ex_data();
  10573. ERR_remove_state(0);
  10574. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10575. pthread_mutex_destroy(&ssl_mutexes[i]);
  10576. }
  10577. mg_free(ssl_mutexes);
  10578. ssl_mutexes = NULL;
  10579. }
  10580. }
  10581. #endif /* !NO_SSL */
  10582. static int
  10583. set_gpass_option(struct mg_context *ctx)
  10584. {
  10585. if (ctx) {
  10586. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10587. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10588. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10589. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10590. return 0;
  10591. }
  10592. return 1;
  10593. }
  10594. return 0;
  10595. }
  10596. static int
  10597. set_acl_option(struct mg_context *ctx)
  10598. {
  10599. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10600. }
  10601. static void
  10602. reset_per_request_attributes(struct mg_connection *conn)
  10603. {
  10604. if (!conn) {
  10605. return;
  10606. }
  10607. conn->path_info = NULL;
  10608. conn->num_bytes_sent = conn->consumed_content = 0;
  10609. conn->status_code = -1;
  10610. conn->is_chunked = 0;
  10611. conn->must_close = conn->request_len = conn->throttle = 0;
  10612. conn->request_info.content_length = -1;
  10613. conn->request_info.remote_user = NULL;
  10614. conn->request_info.request_method = NULL;
  10615. conn->request_info.request_uri = NULL;
  10616. conn->request_info.local_uri = NULL;
  10617. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10618. * local_uri and request_uri */
  10619. conn->request_info.http_version = NULL;
  10620. conn->request_info.num_headers = 0;
  10621. conn->data_len = 0;
  10622. conn->chunk_remainder = 0;
  10623. conn->internal_error = 0;
  10624. }
  10625. static int
  10626. set_sock_timeout(SOCKET sock, int milliseconds)
  10627. {
  10628. int r0 = 0, r1, r2;
  10629. #ifdef _WIN32
  10630. /* Windows specific */
  10631. DWORD tv = (DWORD)milliseconds;
  10632. #else
  10633. /* Linux, ... (not Windows) */
  10634. struct timeval tv;
  10635. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10636. * max. time waiting for the acknowledged of TCP data before the connection
  10637. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10638. * If this option is not set, the default timeout of 20-30 minutes is used.
  10639. */
  10640. /* #define TCP_USER_TIMEOUT (18) */
  10641. #if defined(TCP_USER_TIMEOUT)
  10642. unsigned int uto = (unsigned int)milliseconds;
  10643. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10644. #endif
  10645. memset(&tv, 0, sizeof(tv));
  10646. tv.tv_sec = milliseconds / 1000;
  10647. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10648. #endif /* _WIN32 */
  10649. r1 = setsockopt(
  10650. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10651. r2 = setsockopt(
  10652. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10653. return r0 || r1 || r2;
  10654. }
  10655. static int
  10656. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10657. {
  10658. if (setsockopt(sock,
  10659. IPPROTO_TCP,
  10660. TCP_NODELAY,
  10661. (SOCK_OPT_TYPE)&nodelay_on,
  10662. sizeof(nodelay_on)) != 0) {
  10663. /* Error */
  10664. return 1;
  10665. }
  10666. /* OK */
  10667. return 0;
  10668. }
  10669. static void
  10670. close_socket_gracefully(struct mg_connection *conn)
  10671. {
  10672. #if defined(_WIN32)
  10673. char buf[MG_BUF_LEN];
  10674. int n;
  10675. #endif
  10676. struct linger linger;
  10677. int error_code = 0;
  10678. socklen_t opt_len = sizeof(error_code);
  10679. if (!conn) {
  10680. return;
  10681. }
  10682. /* Set linger option to avoid socket hanging out after close. This
  10683. * prevent ephemeral port exhaust problem under high QPS. */
  10684. linger.l_onoff = 1;
  10685. linger.l_linger = 1;
  10686. if (getsockopt(conn->client.sock,
  10687. SOL_SOCKET,
  10688. SO_ERROR,
  10689. (char *)&error_code,
  10690. &opt_len) != 0) {
  10691. /* Cannot determine if socket is already closed. This should
  10692. * not occur and never did in a test. Log an error message
  10693. * and continue. */
  10694. mg_cry(conn,
  10695. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10696. __func__,
  10697. strerror(ERRNO));
  10698. } else if (error_code == ECONNRESET) {
  10699. /* Socket already closed by client/peer, close socket without linger */
  10700. } else {
  10701. if (setsockopt(conn->client.sock,
  10702. SOL_SOCKET,
  10703. SO_LINGER,
  10704. (char *)&linger,
  10705. sizeof(linger)) != 0) {
  10706. mg_cry(conn,
  10707. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10708. __func__,
  10709. strerror(ERRNO));
  10710. }
  10711. }
  10712. /* Send FIN to the client */
  10713. shutdown(conn->client.sock, SHUTDOWN_WR);
  10714. set_non_blocking_mode(conn->client.sock);
  10715. #if defined(_WIN32)
  10716. /* Read and discard pending incoming data. If we do not do that and
  10717. * close
  10718. * the socket, the data in the send buffer may be discarded. This
  10719. * behaviour is seen on Windows, when client keeps sending data
  10720. * when server decides to close the connection; then when client
  10721. * does recv() it gets no data back. */
  10722. do {
  10723. n = pull(
  10724. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10725. } while (n > 0);
  10726. #endif
  10727. /* Now we know that our FIN is ACK-ed, safe to close */
  10728. closesocket(conn->client.sock);
  10729. conn->client.sock = INVALID_SOCKET;
  10730. }
  10731. static void
  10732. close_connection(struct mg_connection *conn)
  10733. {
  10734. if (!conn || !conn->ctx) {
  10735. return;
  10736. }
  10737. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10738. if (conn->lua_websocket_state) {
  10739. lua_websocket_close(conn, conn->lua_websocket_state);
  10740. conn->lua_websocket_state = NULL;
  10741. }
  10742. #endif
  10743. /* call the connection_close callback if assigned */
  10744. if ((conn->ctx->callbacks.connection_close != NULL)
  10745. && (conn->ctx->context_type == 1)) {
  10746. conn->ctx->callbacks.connection_close(conn);
  10747. }
  10748. mg_lock_connection(conn);
  10749. conn->must_close = 1;
  10750. #ifndef NO_SSL
  10751. if (conn->ssl != NULL) {
  10752. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10753. */
  10754. SSL_shutdown(conn->ssl);
  10755. SSL_free(conn->ssl);
  10756. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10757. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10758. ERR_remove_state(0);
  10759. conn->ssl = NULL;
  10760. }
  10761. #endif
  10762. if (conn->client.sock != INVALID_SOCKET) {
  10763. close_socket_gracefully(conn);
  10764. conn->client.sock = INVALID_SOCKET;
  10765. }
  10766. mg_unlock_connection(conn);
  10767. }
  10768. void
  10769. mg_close_connection(struct mg_connection *conn)
  10770. {
  10771. struct mg_context *client_ctx = NULL;
  10772. if (conn == NULL) {
  10773. return;
  10774. }
  10775. #if defined(USE_WEBSOCKET)
  10776. if (conn->ctx->context_type == 2) {
  10777. unsigned int i;
  10778. /* ws/wss client */
  10779. client_ctx = conn->ctx;
  10780. /* client context: loops must end */
  10781. conn->ctx->stop_flag = 1;
  10782. /* We need to get the client thread out of the select/recv call here. */
  10783. /* Since we use a sleep quantum of some seconds to check for recv
  10784. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10785. /* join worker thread */
  10786. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10787. if (client_ctx->workerthreadids[i] != 0) {
  10788. mg_join_thread(client_ctx->workerthreadids[i]);
  10789. }
  10790. }
  10791. }
  10792. #else
  10793. (void)client_ctx;
  10794. #endif
  10795. close_connection(conn);
  10796. #ifndef NO_SSL
  10797. if (conn->client_ssl_ctx != NULL) {
  10798. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10799. }
  10800. #endif
  10801. if (client_ctx != NULL) {
  10802. /* free context */
  10803. mg_free(client_ctx->workerthreadids);
  10804. mg_free(client_ctx);
  10805. (void)pthread_mutex_destroy(&conn->mutex);
  10806. mg_free(conn);
  10807. }
  10808. }
  10809. static struct mg_connection *
  10810. mg_connect_client_impl(const struct mg_client_options *client_options,
  10811. int use_ssl,
  10812. char *ebuf,
  10813. size_t ebuf_len)
  10814. {
  10815. static struct mg_context fake_ctx;
  10816. struct mg_connection *conn = NULL;
  10817. SOCKET sock;
  10818. union usa sa;
  10819. if (!connect_socket(&fake_ctx,
  10820. client_options->host,
  10821. client_options->port,
  10822. use_ssl,
  10823. ebuf,
  10824. ebuf_len,
  10825. &sock,
  10826. &sa)) {
  10827. ;
  10828. } else if ((conn = (struct mg_connection *)
  10829. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10830. mg_snprintf(NULL,
  10831. NULL, /* No truncation check for ebuf */
  10832. ebuf,
  10833. ebuf_len,
  10834. "calloc(): %s",
  10835. strerror(ERRNO));
  10836. closesocket(sock);
  10837. #ifndef NO_SSL
  10838. } else if (use_ssl
  10839. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10840. == NULL) {
  10841. mg_snprintf(NULL,
  10842. NULL, /* No truncation check for ebuf */
  10843. ebuf,
  10844. ebuf_len,
  10845. "SSL_CTX_new error");
  10846. closesocket(sock);
  10847. mg_free(conn);
  10848. conn = NULL;
  10849. #endif /* NO_SSL */
  10850. } else {
  10851. #ifdef USE_IPV6
  10852. socklen_t len = (sa.sa.sa_family == AF_INET)
  10853. ? sizeof(conn->client.rsa.sin)
  10854. : sizeof(conn->client.rsa.sin6);
  10855. struct sockaddr *psa =
  10856. (sa.sa.sa_family == AF_INET)
  10857. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10858. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10859. #else
  10860. socklen_t len = sizeof(conn->client.rsa.sin);
  10861. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10862. #endif
  10863. conn->buf_size = MAX_REQUEST_SIZE;
  10864. conn->buf = (char *)(conn + 1);
  10865. conn->ctx = &fake_ctx;
  10866. conn->client.sock = sock;
  10867. conn->client.lsa = sa;
  10868. if (getsockname(sock, psa, &len) != 0) {
  10869. mg_cry(conn,
  10870. "%s: getsockname() failed: %s",
  10871. __func__,
  10872. strerror(ERRNO));
  10873. }
  10874. conn->client.is_ssl = use_ssl ? 1 : 0;
  10875. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10876. #ifndef NO_SSL
  10877. if (use_ssl) {
  10878. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10879. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10880. * SSL_CTX_set_verify call is needed to switch off server
  10881. * certificate checking, which is off by default in OpenSSL and
  10882. * on in yaSSL. */
  10883. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10884. * SSL_VERIFY_PEER, verify_ssl_server); */
  10885. if (client_options->client_cert) {
  10886. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10887. mg_snprintf(NULL,
  10888. NULL, /* No truncation check for ebuf */
  10889. ebuf,
  10890. ebuf_len,
  10891. "Can not use SSL client certificate");
  10892. SSL_CTX_free(conn->client_ssl_ctx);
  10893. closesocket(sock);
  10894. mg_free(conn);
  10895. conn = NULL;
  10896. }
  10897. }
  10898. if (client_options->server_cert) {
  10899. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10900. client_options->server_cert,
  10901. NULL);
  10902. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10903. } else {
  10904. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10905. }
  10906. if (!sslize(conn,
  10907. conn->client_ssl_ctx,
  10908. SSL_connect,
  10909. &(conn->ctx->stop_flag))) {
  10910. mg_snprintf(NULL,
  10911. NULL, /* No truncation check for ebuf */
  10912. ebuf,
  10913. ebuf_len,
  10914. "SSL connection error");
  10915. SSL_CTX_free(conn->client_ssl_ctx);
  10916. closesocket(sock);
  10917. mg_free(conn);
  10918. conn = NULL;
  10919. }
  10920. }
  10921. #endif
  10922. }
  10923. return conn;
  10924. }
  10925. CIVETWEB_API struct mg_connection *
  10926. mg_connect_client_secure(const struct mg_client_options *client_options,
  10927. char *error_buffer,
  10928. size_t error_buffer_size)
  10929. {
  10930. return mg_connect_client_impl(client_options,
  10931. 1,
  10932. error_buffer,
  10933. error_buffer_size);
  10934. }
  10935. struct mg_connection *
  10936. mg_connect_client(const char *host,
  10937. int port,
  10938. int use_ssl,
  10939. char *error_buffer,
  10940. size_t error_buffer_size)
  10941. {
  10942. struct mg_client_options opts;
  10943. memset(&opts, 0, sizeof(opts));
  10944. opts.host = host;
  10945. opts.port = port;
  10946. return mg_connect_client_impl(&opts,
  10947. use_ssl,
  10948. error_buffer,
  10949. error_buffer_size);
  10950. }
  10951. static const struct {
  10952. const char *proto;
  10953. size_t proto_len;
  10954. unsigned default_port;
  10955. } abs_uri_protocols[] = {{"http://", 7, 80},
  10956. {"https://", 8, 443},
  10957. {"ws://", 5, 80},
  10958. {"wss://", 6, 443},
  10959. {NULL, 0, 0}};
  10960. /* Check if the uri is valid.
  10961. * return 0 for invalid uri,
  10962. * return 1 for *,
  10963. * return 2 for relative uri,
  10964. * return 3 for absolute uri without port,
  10965. * return 4 for absolute uri with port */
  10966. static int
  10967. get_uri_type(const char *uri)
  10968. {
  10969. int i;
  10970. char *hostend, *portbegin, *portend;
  10971. unsigned long port;
  10972. /* According to the HTTP standard
  10973. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10974. * URI can be an asterisk (*) or should start with slash (relative uri),
  10975. * or it should start with the protocol (absolute uri). */
  10976. if (uri[0] == '*' && uri[1] == '\0') {
  10977. /* asterisk */
  10978. return 1;
  10979. }
  10980. /* Valid URIs according to RFC 3986
  10981. * (https://www.ietf.org/rfc/rfc3986.txt)
  10982. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10983. * and unreserved characters A-Z a-z 0-9 and -._~
  10984. * and % encoded symbols.
  10985. */
  10986. for (i = 0; uri[i] != 0; i++) {
  10987. if (uri[i] < 33) {
  10988. /* control characters and spaces are invalid */
  10989. return 0;
  10990. }
  10991. if (uri[i] > 126) {
  10992. /* non-ascii characters must be % encoded */
  10993. return 0;
  10994. } else {
  10995. switch (uri[i]) {
  10996. case '"': /* 34 */
  10997. case '<': /* 60 */
  10998. case '>': /* 62 */
  10999. case '\\': /* 92 */
  11000. case '^': /* 94 */
  11001. case '`': /* 96 */
  11002. case '{': /* 123 */
  11003. case '|': /* 124 */
  11004. case '}': /* 125 */
  11005. return 0;
  11006. default:
  11007. /* character is ok */
  11008. break;
  11009. }
  11010. }
  11011. }
  11012. /* A relative uri starts with a / character */
  11013. if (uri[0] == '/') {
  11014. /* relative uri */
  11015. return 2;
  11016. }
  11017. /* It could be an absolute uri: */
  11018. /* This function only checks if the uri is valid, not if it is
  11019. * addressing the current server. So civetweb can also be used
  11020. * as a proxy server. */
  11021. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11022. if (mg_strncasecmp(uri,
  11023. abs_uri_protocols[i].proto,
  11024. abs_uri_protocols[i].proto_len) == 0) {
  11025. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11026. if (!hostend) {
  11027. return 0;
  11028. }
  11029. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11030. if (!portbegin) {
  11031. return 3;
  11032. }
  11033. port = strtoul(portbegin + 1, &portend, 10);
  11034. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11035. return 0;
  11036. }
  11037. return 4;
  11038. }
  11039. }
  11040. return 0;
  11041. }
  11042. /* Return NULL or the relative uri at the current server */
  11043. static const char *
  11044. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11045. {
  11046. const char *server_domain;
  11047. size_t server_domain_len;
  11048. size_t request_domain_len = 0;
  11049. unsigned long port = 0;
  11050. int i;
  11051. const char *hostbegin = NULL;
  11052. const char *hostend = NULL;
  11053. const char *portbegin;
  11054. char *portend;
  11055. /* DNS is case insensitive, so use case insensitive string compare here
  11056. */
  11057. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11058. if (!server_domain) {
  11059. return 0;
  11060. }
  11061. server_domain_len = strlen(server_domain);
  11062. if (!server_domain_len) {
  11063. return 0;
  11064. }
  11065. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11066. if (mg_strncasecmp(uri,
  11067. abs_uri_protocols[i].proto,
  11068. abs_uri_protocols[i].proto_len) == 0) {
  11069. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11070. hostend = strchr(hostbegin, '/');
  11071. if (!hostend) {
  11072. return 0;
  11073. }
  11074. portbegin = strchr(hostbegin, ':');
  11075. if ((!portbegin) || (portbegin > hostend)) {
  11076. port = abs_uri_protocols[i].default_port;
  11077. request_domain_len = (size_t)(hostend - hostbegin);
  11078. } else {
  11079. port = strtoul(portbegin + 1, &portend, 10);
  11080. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11081. return 0;
  11082. }
  11083. request_domain_len = (size_t)(portbegin - hostbegin);
  11084. }
  11085. /* protocol found, port set */
  11086. break;
  11087. }
  11088. }
  11089. if (!port) {
  11090. /* port remains 0 if the protocol is not found */
  11091. return 0;
  11092. }
  11093. /* Check if the request is directed to a different server. */
  11094. /* First check if the port is the same (IPv4 and IPv6). */
  11095. #if defined(USE_IPV6)
  11096. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11097. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11098. /* Request is directed to a different port */
  11099. return 0;
  11100. }
  11101. } else
  11102. #endif
  11103. {
  11104. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11105. /* Request is directed to a different port */
  11106. return 0;
  11107. }
  11108. }
  11109. /* Finally check if the server corresponds to the authentication
  11110. * domain of the server (the server domain).
  11111. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11112. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11113. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11114. * or http://mydomain.com.fake/path/file.ext).
  11115. */
  11116. if ((request_domain_len == server_domain_len)
  11117. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11118. /* Request is directed to this server - full name match. */
  11119. } else {
  11120. if (request_domain_len < (server_domain_len + 2)) {
  11121. /* Request is directed to another server: The server name is longer
  11122. * than
  11123. * the request name. Drop this case here to avoid overflows in the
  11124. * following checks. */
  11125. return 0;
  11126. }
  11127. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11128. /* Request is directed to another server: It could be a substring
  11129. * like notmyserver.com */
  11130. return 0;
  11131. }
  11132. if (0 != memcmp(server_domain,
  11133. hostbegin + request_domain_len - server_domain_len,
  11134. server_domain_len)) {
  11135. /* Request is directed to another server:
  11136. * The server name is different. */
  11137. return 0;
  11138. }
  11139. }
  11140. return hostend;
  11141. }
  11142. static int
  11143. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11144. {
  11145. const char *cl;
  11146. if (ebuf_len > 0) {
  11147. ebuf[0] = '\0';
  11148. }
  11149. *err = 0;
  11150. reset_per_request_attributes(conn);
  11151. if (!conn) {
  11152. mg_snprintf(conn,
  11153. NULL, /* No truncation check for ebuf */
  11154. ebuf,
  11155. ebuf_len,
  11156. "%s",
  11157. "Internal error");
  11158. *err = 500;
  11159. return 0;
  11160. }
  11161. /* Set the time the request was received. This value should be used for
  11162. * timeouts. */
  11163. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11164. conn->request_len =
  11165. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11166. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11167. */
  11168. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11169. mg_snprintf(conn,
  11170. NULL, /* No truncation check for ebuf */
  11171. ebuf,
  11172. ebuf_len,
  11173. "%s",
  11174. "Invalid request size");
  11175. *err = 500;
  11176. return 0;
  11177. }
  11178. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11179. mg_snprintf(conn,
  11180. NULL, /* No truncation check for ebuf */
  11181. ebuf,
  11182. ebuf_len,
  11183. "%s",
  11184. "Request Too Large");
  11185. *err = 413;
  11186. return 0;
  11187. } else if (conn->request_len <= 0) {
  11188. if (conn->data_len > 0) {
  11189. mg_snprintf(conn,
  11190. NULL, /* No truncation check for ebuf */
  11191. ebuf,
  11192. ebuf_len,
  11193. "%s",
  11194. "Client sent malformed request");
  11195. *err = 400;
  11196. } else {
  11197. /* Server did not recv anything -> just close the connection */
  11198. conn->must_close = 1;
  11199. mg_snprintf(conn,
  11200. NULL, /* No truncation check for ebuf */
  11201. ebuf,
  11202. ebuf_len,
  11203. "%s",
  11204. "Client did not send a request");
  11205. *err = 0;
  11206. }
  11207. return 0;
  11208. } else if (parse_http_message(conn->buf,
  11209. conn->buf_size,
  11210. &conn->request_info) <= 0) {
  11211. mg_snprintf(conn,
  11212. NULL, /* No truncation check for ebuf */
  11213. ebuf,
  11214. ebuf_len,
  11215. "%s",
  11216. "Bad Request");
  11217. *err = 400;
  11218. return 0;
  11219. } else {
  11220. /* Message is a valid request or response */
  11221. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11222. /* Request/response has content length set */
  11223. char *endptr = NULL;
  11224. conn->content_len = strtoll(cl, &endptr, 10);
  11225. if (endptr == cl) {
  11226. mg_snprintf(conn,
  11227. NULL, /* No truncation check for ebuf */
  11228. ebuf,
  11229. ebuf_len,
  11230. "%s",
  11231. "Bad Request");
  11232. *err = 411;
  11233. return 0;
  11234. }
  11235. /* Publish the content length back to the request info. */
  11236. conn->request_info.content_length = conn->content_len;
  11237. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11238. != NULL
  11239. && !mg_strcasecmp(cl, "chunked")) {
  11240. conn->is_chunked = 1;
  11241. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11242. || !mg_strcasecmp(conn->request_info.request_method,
  11243. "PUT")) {
  11244. /* POST or PUT request without content length set */
  11245. conn->content_len = -1;
  11246. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11247. "HTTP/",
  11248. 5)) {
  11249. /* Response without content length set */
  11250. conn->content_len = -1;
  11251. } else {
  11252. /* Other request */
  11253. conn->content_len = 0;
  11254. }
  11255. }
  11256. return 1;
  11257. }
  11258. int
  11259. mg_get_response(struct mg_connection *conn,
  11260. char *ebuf,
  11261. size_t ebuf_len,
  11262. int timeout)
  11263. {
  11264. if (conn) {
  11265. /* Implementation of API function for HTTP clients */
  11266. int err, ret;
  11267. struct mg_context *octx = conn->ctx;
  11268. struct mg_context rctx = *(conn->ctx);
  11269. char txt[32]; /* will not overflow */
  11270. if (timeout >= 0) {
  11271. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11272. rctx.config[REQUEST_TIMEOUT] = txt;
  11273. set_sock_timeout(conn->client.sock, timeout);
  11274. } else {
  11275. rctx.config[REQUEST_TIMEOUT] = NULL;
  11276. }
  11277. conn->ctx = &rctx;
  11278. ret = getreq(conn, ebuf, ebuf_len, &err);
  11279. conn->ctx = octx;
  11280. /* TODO: 1) uri is deprecated;
  11281. * 2) here, ri.uri is the http response code */
  11282. conn->request_info.uri = conn->request_info.request_uri;
  11283. /* TODO (mid): Define proper return values - maybe return length?
  11284. * For the first test use <0 for error and >0 for OK */
  11285. return (ret == 0) ? -1 : +1;
  11286. }
  11287. return -1;
  11288. }
  11289. struct mg_connection *
  11290. mg_download(const char *host,
  11291. int port,
  11292. int use_ssl,
  11293. char *ebuf,
  11294. size_t ebuf_len,
  11295. const char *fmt,
  11296. ...)
  11297. {
  11298. struct mg_connection *conn;
  11299. va_list ap;
  11300. int i;
  11301. int reqerr;
  11302. va_start(ap, fmt);
  11303. ebuf[0] = '\0';
  11304. /* open a connection */
  11305. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11306. if (conn != NULL) {
  11307. i = mg_vprintf(conn, fmt, ap);
  11308. if (i <= 0) {
  11309. mg_snprintf(conn,
  11310. NULL, /* No truncation check for ebuf */
  11311. ebuf,
  11312. ebuf_len,
  11313. "%s",
  11314. "Error sending request");
  11315. } else {
  11316. getreq(conn, ebuf, ebuf_len, &reqerr);
  11317. /* TODO: 1) uri is deprecated;
  11318. * 2) here, ri.uri is the http response code */
  11319. conn->request_info.uri = conn->request_info.request_uri;
  11320. }
  11321. }
  11322. /* if an error occured, close the connection */
  11323. if (ebuf[0] != '\0' && conn != NULL) {
  11324. mg_close_connection(conn);
  11325. conn = NULL;
  11326. }
  11327. va_end(ap);
  11328. return conn;
  11329. }
  11330. struct websocket_client_thread_data {
  11331. struct mg_connection *conn;
  11332. mg_websocket_data_handler data_handler;
  11333. mg_websocket_close_handler close_handler;
  11334. void *callback_data;
  11335. };
  11336. #if defined(USE_WEBSOCKET)
  11337. #ifdef _WIN32
  11338. static unsigned __stdcall websocket_client_thread(void *data)
  11339. #else
  11340. static void *
  11341. websocket_client_thread(void *data)
  11342. #endif
  11343. {
  11344. struct websocket_client_thread_data *cdata =
  11345. (struct websocket_client_thread_data *)data;
  11346. mg_set_thread_name("ws-clnt");
  11347. if (cdata->conn->ctx) {
  11348. if (cdata->conn->ctx->callbacks.init_thread) {
  11349. /* 3 indicates a websocket client thread */
  11350. /* TODO: check if conn->ctx can be set */
  11351. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11352. }
  11353. }
  11354. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11355. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11356. if (cdata->close_handler != NULL) {
  11357. cdata->close_handler(cdata->conn, cdata->callback_data);
  11358. }
  11359. /* The websocket_client context has only this thread. If it runs out,
  11360. set the stop_flag to 2 (= "stopped"). */
  11361. cdata->conn->ctx->stop_flag = 2;
  11362. mg_free((void *)cdata);
  11363. #ifdef _WIN32
  11364. return 0;
  11365. #else
  11366. return NULL;
  11367. #endif
  11368. }
  11369. #endif
  11370. struct mg_connection *
  11371. mg_connect_websocket_client(const char *host,
  11372. int port,
  11373. int use_ssl,
  11374. char *error_buffer,
  11375. size_t error_buffer_size,
  11376. const char *path,
  11377. const char *origin,
  11378. mg_websocket_data_handler data_func,
  11379. mg_websocket_close_handler close_func,
  11380. void *user_data)
  11381. {
  11382. struct mg_connection *conn = NULL;
  11383. #if defined(USE_WEBSOCKET)
  11384. struct mg_context *newctx = NULL;
  11385. struct websocket_client_thread_data *thread_data;
  11386. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11387. static const char *handshake_req;
  11388. if (origin != NULL) {
  11389. handshake_req = "GET %s HTTP/1.1\r\n"
  11390. "Host: %s\r\n"
  11391. "Upgrade: websocket\r\n"
  11392. "Connection: Upgrade\r\n"
  11393. "Sec-WebSocket-Key: %s\r\n"
  11394. "Sec-WebSocket-Version: 13\r\n"
  11395. "Origin: %s\r\n"
  11396. "\r\n";
  11397. } else {
  11398. handshake_req = "GET %s HTTP/1.1\r\n"
  11399. "Host: %s\r\n"
  11400. "Upgrade: websocket\r\n"
  11401. "Connection: Upgrade\r\n"
  11402. "Sec-WebSocket-Key: %s\r\n"
  11403. "Sec-WebSocket-Version: 13\r\n"
  11404. "\r\n";
  11405. }
  11406. /* Establish the client connection and request upgrade */
  11407. conn = mg_download(host,
  11408. port,
  11409. use_ssl,
  11410. error_buffer,
  11411. error_buffer_size,
  11412. handshake_req,
  11413. path,
  11414. host,
  11415. magic,
  11416. origin);
  11417. /* Connection object will be null if something goes wrong */
  11418. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11419. if (!*error_buffer) {
  11420. /* if there is a connection, but it did not return 101,
  11421. * error_buffer is not yet set */
  11422. mg_snprintf(conn,
  11423. NULL, /* No truncation check for ebuf */
  11424. error_buffer,
  11425. error_buffer_size,
  11426. "Unexpected server reply");
  11427. }
  11428. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11429. if (conn != NULL) {
  11430. mg_free(conn);
  11431. conn = NULL;
  11432. }
  11433. return conn;
  11434. }
  11435. /* For client connections, mg_context is fake. Since we need to set a
  11436. * callback function, we need to create a copy and modify it. */
  11437. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11438. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11439. newctx->user_data = user_data;
  11440. newctx->context_type = 2; /* ws/wss client context type */
  11441. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11442. newctx->workerthreadids =
  11443. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11444. conn->ctx = newctx;
  11445. thread_data = (struct websocket_client_thread_data *)
  11446. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11447. thread_data->conn = conn;
  11448. thread_data->data_handler = data_func;
  11449. thread_data->close_handler = close_func;
  11450. thread_data->callback_data = NULL;
  11451. /* Start a thread to read the websocket client connection
  11452. * This thread will automatically stop when mg_disconnect is
  11453. * called on the client connection */
  11454. if (mg_start_thread_with_id(websocket_client_thread,
  11455. (void *)thread_data,
  11456. newctx->workerthreadids) != 0) {
  11457. mg_free((void *)thread_data);
  11458. mg_free((void *)newctx->workerthreadids);
  11459. mg_free((void *)newctx);
  11460. mg_free((void *)conn);
  11461. conn = NULL;
  11462. DEBUG_TRACE("%s",
  11463. "Websocket client connect thread could not be started\r\n");
  11464. }
  11465. #else
  11466. /* Appease "unused parameter" warnings */
  11467. (void)host;
  11468. (void)port;
  11469. (void)use_ssl;
  11470. (void)error_buffer;
  11471. (void)error_buffer_size;
  11472. (void)path;
  11473. (void)origin;
  11474. (void)user_data;
  11475. (void)data_func;
  11476. (void)close_func;
  11477. #endif
  11478. return conn;
  11479. }
  11480. static void
  11481. process_new_connection(struct mg_connection *conn)
  11482. {
  11483. if (conn && conn->ctx) {
  11484. struct mg_request_info *ri = &conn->request_info;
  11485. int keep_alive_enabled, keep_alive, discard_len;
  11486. char ebuf[100];
  11487. const char *hostend;
  11488. int reqerr, uri_type;
  11489. keep_alive_enabled =
  11490. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11491. /* Important: on new connection, reset the receiving buffer. Credit
  11492. * goes to crule42. */
  11493. conn->data_len = 0;
  11494. do {
  11495. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11496. /* The request sent by the client could not be understood by
  11497. * the server, or it was incomplete or a timeout. Send an
  11498. * error message and close the connection. */
  11499. if (reqerr > 0) {
  11500. /*assert(ebuf[0] != '\0');*/
  11501. send_http_error(conn, reqerr, "%s", ebuf);
  11502. }
  11503. } else if (strcmp(ri->http_version, "1.0")
  11504. && strcmp(ri->http_version, "1.1")) {
  11505. mg_snprintf(conn,
  11506. NULL, /* No truncation check for ebuf */
  11507. ebuf,
  11508. sizeof(ebuf),
  11509. "Bad HTTP version: [%s]",
  11510. ri->http_version);
  11511. send_http_error(conn, 505, "%s", ebuf);
  11512. }
  11513. if (ebuf[0] == '\0') {
  11514. uri_type = get_uri_type(conn->request_info.request_uri);
  11515. switch (uri_type) {
  11516. case 1:
  11517. /* Asterisk */
  11518. conn->request_info.local_uri = NULL;
  11519. break;
  11520. case 2:
  11521. /* relative uri */
  11522. conn->request_info.local_uri =
  11523. conn->request_info.request_uri;
  11524. break;
  11525. case 3:
  11526. case 4:
  11527. /* absolute uri (with/without port) */
  11528. hostend = get_rel_url_at_current_server(
  11529. conn->request_info.request_uri, conn);
  11530. if (hostend) {
  11531. conn->request_info.local_uri = hostend;
  11532. } else {
  11533. conn->request_info.local_uri = NULL;
  11534. }
  11535. break;
  11536. default:
  11537. mg_snprintf(conn,
  11538. NULL, /* No truncation check for ebuf */
  11539. ebuf,
  11540. sizeof(ebuf),
  11541. "Invalid URI");
  11542. send_http_error(conn, 400, "%s", ebuf);
  11543. conn->request_info.local_uri = NULL;
  11544. break;
  11545. }
  11546. /* TODO: cleanup uri, local_uri and request_uri */
  11547. conn->request_info.uri = conn->request_info.local_uri;
  11548. }
  11549. if (ebuf[0] == '\0') {
  11550. if (conn->request_info.local_uri) {
  11551. /* handle request to local server */
  11552. handle_request(conn);
  11553. if (conn->ctx->callbacks.end_request != NULL) {
  11554. conn->ctx->callbacks.end_request(conn,
  11555. conn->status_code);
  11556. }
  11557. log_access(conn);
  11558. } else {
  11559. /* TODO: handle non-local request (PROXY) */
  11560. conn->must_close = 1;
  11561. }
  11562. } else {
  11563. conn->must_close = 1;
  11564. }
  11565. if (ri->remote_user != NULL) {
  11566. mg_free((void *)ri->remote_user);
  11567. /* Important! When having connections with and without auth
  11568. * would cause double free and then crash */
  11569. ri->remote_user = NULL;
  11570. }
  11571. /* NOTE(lsm): order is important here. should_keep_alive() call
  11572. * is
  11573. * using parsed request, which will be invalid after memmove's
  11574. * below.
  11575. * Therefore, memorize should_keep_alive() result now for later
  11576. * use
  11577. * in loop exit condition. */
  11578. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11579. && conn->content_len >= 0 && should_keep_alive(conn);
  11580. /* Discard all buffered data for this request */
  11581. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11582. && ((conn->request_len + conn->content_len)
  11583. < (int64_t)conn->data_len))
  11584. ? (int)(conn->request_len + conn->content_len)
  11585. : conn->data_len;
  11586. /*assert(discard_len >= 0);*/
  11587. if (discard_len < 0)
  11588. break;
  11589. conn->data_len -= discard_len;
  11590. if (conn->data_len > 0) {
  11591. memmove(conn->buf,
  11592. conn->buf + discard_len,
  11593. (size_t)conn->data_len);
  11594. }
  11595. /* assert(conn->data_len >= 0); */
  11596. /* assert(conn->data_len <= conn->buf_size); */
  11597. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11598. break;
  11599. }
  11600. } while (keep_alive);
  11601. }
  11602. }
  11603. #if defined(ALTERNATIVE_QUEUE)
  11604. static void
  11605. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11606. {
  11607. unsigned int i;
  11608. for (;;) {
  11609. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11610. /* find a free worker slot and signal it */
  11611. if (ctx->client_socks[i].in_use == 0) {
  11612. ctx->client_socks[i] = *sp;
  11613. ctx->client_socks[i].in_use = 1;
  11614. event_signal(ctx->client_wait_events[i]);
  11615. return;
  11616. }
  11617. }
  11618. /* queue is full */
  11619. mg_sleep(1);
  11620. }
  11621. }
  11622. static int
  11623. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11624. {
  11625. ctx->client_socks[thread_index].in_use = 0;
  11626. event_wait(ctx->client_wait_events[thread_index]);
  11627. *sp = ctx->client_socks[thread_index];
  11628. return !ctx->stop_flag;
  11629. }
  11630. #else /* ALTERNATIVE_QUEUE */
  11631. /* Worker threads take accepted socket from the queue */
  11632. static int
  11633. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11634. {
  11635. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11636. (void)thread_index;
  11637. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11638. DEBUG_TRACE("%s", "going idle");
  11639. /* If the queue is empty, wait. We're idle at this point. */
  11640. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11641. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11642. }
  11643. /* If we're stopping, sq_head may be equal to sq_tail. */
  11644. if (ctx->sq_head > ctx->sq_tail) {
  11645. /* Copy socket from the queue and increment tail */
  11646. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11647. ctx->sq_tail++;
  11648. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11649. /* Wrap pointers if needed */
  11650. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11651. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11652. ctx->sq_head -= QUEUE_SIZE(ctx);
  11653. }
  11654. }
  11655. (void)pthread_cond_signal(&ctx->sq_empty);
  11656. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11657. return !ctx->stop_flag;
  11658. #undef QUEUE_SIZE
  11659. }
  11660. /* Master thread adds accepted socket to a queue */
  11661. static void
  11662. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11663. {
  11664. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11665. if (!ctx) {
  11666. return;
  11667. }
  11668. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11669. /* If the queue is full, wait */
  11670. while (ctx->stop_flag == 0
  11671. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11672. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11673. }
  11674. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11675. /* Copy socket to the queue and increment head */
  11676. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11677. ctx->sq_head++;
  11678. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11679. }
  11680. (void)pthread_cond_signal(&ctx->sq_full);
  11681. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11682. #undef QUEUE_SIZE
  11683. }
  11684. #endif /* ALTERNATIVE_QUEUE */
  11685. struct worker_thread_args {
  11686. struct mg_context *ctx;
  11687. int index;
  11688. };
  11689. static void *
  11690. worker_thread_run(struct worker_thread_args *thread_args)
  11691. {
  11692. struct mg_context *ctx = thread_args->ctx;
  11693. struct mg_connection *conn;
  11694. struct mg_workerTLS tls;
  11695. #if defined(MG_LEGACY_INTERFACE)
  11696. uint32_t addr;
  11697. #endif
  11698. mg_set_thread_name("worker");
  11699. tls.is_master = 0;
  11700. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11701. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11702. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11703. #endif
  11704. if (ctx->callbacks.init_thread) {
  11705. /* call init_thread for a worker thread (type 1) */
  11706. ctx->callbacks.init_thread(ctx, 1);
  11707. }
  11708. conn =
  11709. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11710. if (conn == NULL) {
  11711. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11712. } else {
  11713. pthread_setspecific(sTlsKey, &tls);
  11714. conn->buf_size = MAX_REQUEST_SIZE;
  11715. conn->buf = (char *)(conn + 1);
  11716. conn->ctx = ctx;
  11717. conn->thread_index = thread_args->index;
  11718. conn->request_info.user_data = ctx->user_data;
  11719. /* Allocate a mutex for this connection to allow communication both
  11720. * within the request handler and from elsewhere in the application
  11721. */
  11722. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11723. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11724. * signal sq_empty condvar to wake up the master waiting in
  11725. * produce_socket() */
  11726. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11727. conn->conn_birth_time = time(NULL);
  11728. /* Fill in IP, port info early so even if SSL setup below fails,
  11729. * error handler would have the corresponding info.
  11730. * Thanks to Johannes Winkelmann for the patch.
  11731. */
  11732. #if defined(USE_IPV6)
  11733. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11734. conn->request_info.remote_port =
  11735. ntohs(conn->client.rsa.sin6.sin6_port);
  11736. } else
  11737. #endif
  11738. {
  11739. conn->request_info.remote_port =
  11740. ntohs(conn->client.rsa.sin.sin_port);
  11741. }
  11742. sockaddr_to_string(conn->request_info.remote_addr,
  11743. sizeof(conn->request_info.remote_addr),
  11744. &conn->client.rsa);
  11745. #if defined(MG_LEGACY_INTERFACE)
  11746. /* This legacy interface only works for the IPv4 case */
  11747. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11748. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11749. #endif
  11750. conn->request_info.is_ssl = conn->client.is_ssl;
  11751. if (conn->client.is_ssl) {
  11752. #ifndef NO_SSL
  11753. /* HTTPS connection */
  11754. if (sslize(conn,
  11755. conn->ctx->ssl_ctx,
  11756. SSL_accept,
  11757. &(conn->ctx->stop_flag))) {
  11758. /* Get SSL client certificate information (if set) */
  11759. ssl_get_client_cert_info(conn);
  11760. /* process HTTPS connection */
  11761. process_new_connection(conn);
  11762. /* Free client certificate info */
  11763. if (conn->request_info.client_cert) {
  11764. mg_free(
  11765. (void *)(conn->request_info.client_cert->subject));
  11766. mg_free(
  11767. (void *)(conn->request_info.client_cert->issuer));
  11768. mg_free(
  11769. (void *)(conn->request_info.client_cert->serial));
  11770. mg_free(
  11771. (void *)(conn->request_info.client_cert->finger));
  11772. conn->request_info.client_cert->subject = 0;
  11773. conn->request_info.client_cert->issuer = 0;
  11774. conn->request_info.client_cert->serial = 0;
  11775. conn->request_info.client_cert->finger = 0;
  11776. mg_free(conn->request_info.client_cert);
  11777. conn->request_info.client_cert = 0;
  11778. }
  11779. }
  11780. #endif
  11781. } else {
  11782. /* process HTTP connection */
  11783. process_new_connection(conn);
  11784. }
  11785. close_connection(conn);
  11786. }
  11787. }
  11788. pthread_setspecific(sTlsKey, NULL);
  11789. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11790. CloseHandle(tls.pthread_cond_helper_mutex);
  11791. #endif
  11792. pthread_mutex_destroy(&conn->mutex);
  11793. mg_free(conn);
  11794. DEBUG_TRACE("%s", "exiting");
  11795. return NULL;
  11796. }
  11797. /* Threads have different return types on Windows and Unix. */
  11798. #ifdef _WIN32
  11799. static unsigned __stdcall worker_thread(void *thread_func_param)
  11800. {
  11801. struct worker_thread_args *pwta =
  11802. (struct worker_thread_args *)thread_func_param;
  11803. worker_thread_run(pwta);
  11804. mg_free(thread_func_param);
  11805. return 0;
  11806. }
  11807. #else
  11808. static void *
  11809. worker_thread(void *thread_func_param)
  11810. {
  11811. struct worker_thread_args *pwta =
  11812. (struct worker_thread_args *)thread_func_param;
  11813. worker_thread_run(pwta);
  11814. mg_free(thread_func_param);
  11815. return NULL;
  11816. }
  11817. #endif /* _WIN32 */
  11818. static void
  11819. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11820. {
  11821. struct socket so;
  11822. char src_addr[IP_ADDR_STR_LEN];
  11823. socklen_t len = sizeof(so.rsa);
  11824. int on = 1;
  11825. int timeout;
  11826. if (!listener) {
  11827. return;
  11828. }
  11829. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11830. == INVALID_SOCKET) {
  11831. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11832. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11833. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11834. closesocket(so.sock);
  11835. so.sock = INVALID_SOCKET;
  11836. } else {
  11837. /* Put so socket structure into the queue */
  11838. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11839. set_close_on_exec(so.sock, fc(ctx));
  11840. so.is_ssl = listener->is_ssl;
  11841. so.ssl_redir = listener->ssl_redir;
  11842. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11843. mg_cry(fc(ctx),
  11844. "%s: getsockname() failed: %s",
  11845. __func__,
  11846. strerror(ERRNO));
  11847. }
  11848. /* Set TCP keep-alive. This is needed because if HTTP-level
  11849. * keep-alive
  11850. * is enabled, and client resets the connection, server won't get
  11851. * TCP FIN or RST and will keep the connection open forever. With
  11852. * TCP keep-alive, next keep-alive handshake will figure out that
  11853. * the client is down and will close the server end.
  11854. * Thanks to Igor Klopov who suggested the patch. */
  11855. if (setsockopt(so.sock,
  11856. SOL_SOCKET,
  11857. SO_KEEPALIVE,
  11858. (SOCK_OPT_TYPE)&on,
  11859. sizeof(on)) != 0) {
  11860. mg_cry(fc(ctx),
  11861. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11862. __func__,
  11863. strerror(ERRNO));
  11864. }
  11865. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11866. * to effectively fill up the underlying IP packet payload and
  11867. * reduce the overhead of sending lots of small buffers. However
  11868. * this hurts the server's throughput (ie. operations per second)
  11869. * when HTTP 1.1 persistent connections are used and the responses
  11870. * are relatively small (eg. less than 1400 bytes).
  11871. */
  11872. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11873. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11874. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11875. mg_cry(fc(ctx),
  11876. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11877. __func__,
  11878. strerror(ERRNO));
  11879. }
  11880. }
  11881. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11882. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11883. } else {
  11884. timeout = -1;
  11885. }
  11886. /* TODO: if non blocking sockets are used, timeouts are implemented
  11887. * differently */
  11888. // if (timeout > 0) {
  11889. // set_sock_timeout(so.sock, timeout);
  11890. //}
  11891. (void)timeout;
  11892. set_non_blocking_mode(so.sock);
  11893. produce_socket(ctx, &so);
  11894. }
  11895. }
  11896. static void
  11897. master_thread_run(void *thread_func_param)
  11898. {
  11899. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11900. struct mg_workerTLS tls;
  11901. struct pollfd *pfd;
  11902. unsigned int i;
  11903. unsigned int workerthreadcount;
  11904. if (!ctx) {
  11905. return;
  11906. }
  11907. mg_set_thread_name("master");
  11908. /* Increase priority of the master thread */
  11909. #if defined(_WIN32)
  11910. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11911. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11912. int min_prio = sched_get_priority_min(SCHED_RR);
  11913. int max_prio = sched_get_priority_max(SCHED_RR);
  11914. if ((min_prio >= 0) && (max_prio >= 0)
  11915. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11916. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11917. struct sched_param sched_param = {0};
  11918. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11919. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11920. }
  11921. #endif
  11922. /* Initialize thread local storage */
  11923. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11924. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11925. #endif
  11926. tls.is_master = 1;
  11927. pthread_setspecific(sTlsKey, &tls);
  11928. if (ctx->callbacks.init_thread) {
  11929. /* Callback for the master thread (type 0) */
  11930. ctx->callbacks.init_thread(ctx, 0);
  11931. }
  11932. /* Server starts *now* */
  11933. ctx->start_time = time(NULL);
  11934. /* Start the server */
  11935. pfd = ctx->listening_socket_fds;
  11936. while (ctx->stop_flag == 0) {
  11937. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11938. pfd[i].fd = ctx->listening_sockets[i].sock;
  11939. pfd[i].events = POLLIN;
  11940. }
  11941. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11942. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11943. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11944. * successful poll, and POLLIN is defined as
  11945. * (POLLRDNORM | POLLRDBAND)
  11946. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11947. * pfd[i].revents == POLLIN. */
  11948. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11949. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11950. }
  11951. }
  11952. }
  11953. }
  11954. /* Here stop_flag is 1 - Initiate shutdown. */
  11955. DEBUG_TRACE("%s", "stopping workers");
  11956. /* Stop signal received: somebody called mg_stop. Quit. */
  11957. close_all_listening_sockets(ctx);
  11958. /* Wakeup workers that are waiting for connections to handle. */
  11959. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11960. #if defined(ALTERNATIVE_QUEUE)
  11961. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11962. event_signal(ctx->client_wait_events[i]);
  11963. /* Since we know all sockets, we can shutdown the connections. */
  11964. if (ctx->client_socks[i].in_use) {
  11965. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11966. }
  11967. }
  11968. #else
  11969. pthread_cond_broadcast(&ctx->sq_full);
  11970. #endif
  11971. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11972. /* Join all worker threads to avoid leaking threads. */
  11973. workerthreadcount = ctx->cfg_worker_threads;
  11974. for (i = 0; i < workerthreadcount; i++) {
  11975. if (ctx->workerthreadids[i] != 0) {
  11976. mg_join_thread(ctx->workerthreadids[i]);
  11977. }
  11978. }
  11979. #if !defined(NO_SSL)
  11980. if (ctx->ssl_ctx != NULL) {
  11981. uninitialize_ssl(ctx);
  11982. }
  11983. #endif
  11984. DEBUG_TRACE("%s", "exiting");
  11985. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11986. CloseHandle(tls.pthread_cond_helper_mutex);
  11987. #endif
  11988. pthread_setspecific(sTlsKey, NULL);
  11989. /* Signal mg_stop() that we're done.
  11990. * WARNING: This must be the very last thing this
  11991. * thread does, as ctx becomes invalid after this line. */
  11992. ctx->stop_flag = 2;
  11993. }
  11994. /* Threads have different return types on Windows and Unix. */
  11995. #ifdef _WIN32
  11996. static unsigned __stdcall master_thread(void *thread_func_param)
  11997. {
  11998. master_thread_run(thread_func_param);
  11999. return 0;
  12000. }
  12001. #else
  12002. static void *
  12003. master_thread(void *thread_func_param)
  12004. {
  12005. master_thread_run(thread_func_param);
  12006. return NULL;
  12007. }
  12008. #endif /* _WIN32 */
  12009. static void
  12010. free_context(struct mg_context *ctx)
  12011. {
  12012. int i;
  12013. struct mg_handler_info *tmp_rh;
  12014. if (ctx == NULL) {
  12015. return;
  12016. }
  12017. if (ctx->callbacks.exit_context) {
  12018. ctx->callbacks.exit_context(ctx);
  12019. }
  12020. /* All threads exited, no sync is needed. Destroy thread mutex and
  12021. * condvars
  12022. */
  12023. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12024. #if defined(ALTERNATIVE_QUEUE)
  12025. mg_free(ctx->client_socks);
  12026. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12027. event_destroy(ctx->client_wait_events[i]);
  12028. }
  12029. mg_free(ctx->client_wait_events);
  12030. #else
  12031. (void)pthread_cond_destroy(&ctx->sq_empty);
  12032. (void)pthread_cond_destroy(&ctx->sq_full);
  12033. #endif
  12034. /* Destroy other context global data structures mutex */
  12035. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12036. #if defined(USE_TIMERS)
  12037. timers_exit(ctx);
  12038. #endif
  12039. /* Deallocate config parameters */
  12040. for (i = 0; i < NUM_OPTIONS; i++) {
  12041. if (ctx->config[i] != NULL) {
  12042. #if defined(_MSC_VER)
  12043. #pragma warning(suppress : 6001)
  12044. #endif
  12045. mg_free(ctx->config[i]);
  12046. }
  12047. }
  12048. /* Deallocate request handlers */
  12049. while (ctx->handlers) {
  12050. tmp_rh = ctx->handlers;
  12051. ctx->handlers = tmp_rh->next;
  12052. mg_free(tmp_rh->uri);
  12053. mg_free(tmp_rh);
  12054. }
  12055. #ifndef NO_SSL
  12056. /* Deallocate SSL context */
  12057. if (ctx->ssl_ctx != NULL) {
  12058. SSL_CTX_free(ctx->ssl_ctx);
  12059. }
  12060. #endif /* !NO_SSL */
  12061. /* Deallocate worker thread ID array */
  12062. if (ctx->workerthreadids != NULL) {
  12063. mg_free(ctx->workerthreadids);
  12064. }
  12065. /* Deallocate the tls variable */
  12066. if (mg_atomic_dec(&sTlsInit) == 0) {
  12067. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12068. DeleteCriticalSection(&global_log_file_lock);
  12069. #endif /* _WIN32 && !__SYMBIAN32__ */
  12070. #if !defined(_WIN32)
  12071. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12072. #endif
  12073. pthread_key_delete(sTlsKey);
  12074. #if defined(USE_LUA)
  12075. lua_exit_optional_libraries();
  12076. #endif
  12077. }
  12078. /* deallocate system name string */
  12079. mg_free(ctx->systemName);
  12080. /* Deallocate context itself */
  12081. mg_free(ctx);
  12082. }
  12083. void
  12084. mg_stop(struct mg_context *ctx)
  12085. {
  12086. pthread_t mt;
  12087. if (!ctx) {
  12088. return;
  12089. }
  12090. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12091. * two threads is not allowed. */
  12092. mt = ctx->masterthreadid;
  12093. if (mt == 0) {
  12094. return;
  12095. }
  12096. ctx->masterthreadid = 0;
  12097. /* Set stop flag, so all threads know they have to exit. */
  12098. ctx->stop_flag = 1;
  12099. /* Wait until everything has stopped. */
  12100. while (ctx->stop_flag != 2) {
  12101. (void)mg_sleep(10);
  12102. }
  12103. mg_join_thread(mt);
  12104. free_context(ctx);
  12105. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12106. (void)WSACleanup();
  12107. #endif /* _WIN32 && !__SYMBIAN32__ */
  12108. }
  12109. static void
  12110. get_system_name(char **sysName)
  12111. {
  12112. #if defined(_WIN32)
  12113. #if !defined(__SYMBIAN32__)
  12114. #if defined(_WIN32_WCE)
  12115. *sysName = mg_strdup("WinCE");
  12116. #else
  12117. char name[128];
  12118. DWORD dwVersion = 0;
  12119. DWORD dwMajorVersion = 0;
  12120. DWORD dwMinorVersion = 0;
  12121. DWORD dwBuild = 0;
  12122. #ifdef _MSC_VER
  12123. #pragma warning(push)
  12124. /* GetVersion was declared deprecated */
  12125. #pragma warning(disable : 4996)
  12126. #endif
  12127. dwVersion = GetVersion();
  12128. #ifdef _MSC_VER
  12129. #pragma warning(pop)
  12130. #endif
  12131. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12132. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12133. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12134. (void)dwBuild;
  12135. sprintf(name,
  12136. "Windows %u.%u",
  12137. (unsigned)dwMajorVersion,
  12138. (unsigned)dwMinorVersion);
  12139. *sysName = mg_strdup(name);
  12140. #endif
  12141. #else
  12142. *sysName = mg_strdup("Symbian");
  12143. #endif
  12144. #else
  12145. struct utsname name;
  12146. memset(&name, 0, sizeof(name));
  12147. uname(&name);
  12148. *sysName = mg_strdup(name.sysname);
  12149. #endif
  12150. }
  12151. struct mg_context *
  12152. mg_start(const struct mg_callbacks *callbacks,
  12153. void *user_data,
  12154. const char **options)
  12155. {
  12156. struct mg_context *ctx;
  12157. const char *name, *value, *default_value;
  12158. int idx, ok, workerthreadcount;
  12159. unsigned int i;
  12160. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12161. struct mg_workerTLS tls;
  12162. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12163. WSADATA data;
  12164. WSAStartup(MAKEWORD(2, 2), &data);
  12165. #endif /* _WIN32 && !__SYMBIAN32__ */
  12166. /* Allocate context and initialize reasonable general case defaults. */
  12167. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12168. return NULL;
  12169. }
  12170. /* Random number generator will initialize at the first call */
  12171. ctx->auth_nonce_mask =
  12172. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12173. if (mg_atomic_inc(&sTlsInit) == 1) {
  12174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12175. InitializeCriticalSection(&global_log_file_lock);
  12176. #endif /* _WIN32 && !__SYMBIAN32__ */
  12177. #if !defined(_WIN32)
  12178. pthread_mutexattr_init(&pthread_mutex_attr);
  12179. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12180. #endif
  12181. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12182. /* Fatal error - abort start. However, this situation should
  12183. * never
  12184. * occur in practice. */
  12185. mg_atomic_dec(&sTlsInit);
  12186. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12187. mg_free(ctx);
  12188. return NULL;
  12189. }
  12190. #if defined(USE_LUA)
  12191. lua_init_optional_libraries();
  12192. #endif
  12193. } else {
  12194. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12195. * initialized. */
  12196. mg_sleep(1);
  12197. }
  12198. tls.is_master = -1;
  12199. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12200. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12201. tls.pthread_cond_helper_mutex = NULL;
  12202. #endif
  12203. pthread_setspecific(sTlsKey, &tls);
  12204. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12205. #if !defined(ALTERNATIVE_QUEUE)
  12206. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12207. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12208. #endif
  12209. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12210. if (!ok) {
  12211. /* Fatal error - abort start. However, this situation should never
  12212. * occur in practice. */
  12213. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12214. mg_free(ctx);
  12215. pthread_setspecific(sTlsKey, NULL);
  12216. return NULL;
  12217. }
  12218. if (callbacks) {
  12219. ctx->callbacks = *callbacks;
  12220. exit_callback = callbacks->exit_context;
  12221. ctx->callbacks.exit_context = 0;
  12222. }
  12223. ctx->user_data = user_data;
  12224. ctx->handlers = NULL;
  12225. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12226. ctx->shared_lua_websockets = 0;
  12227. #endif
  12228. while (options && (name = *options++) != NULL) {
  12229. if ((idx = get_option_index(name)) == -1) {
  12230. mg_cry(fc(ctx), "Invalid option: %s", name);
  12231. free_context(ctx);
  12232. pthread_setspecific(sTlsKey, NULL);
  12233. return NULL;
  12234. } else if ((value = *options++) == NULL) {
  12235. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12236. free_context(ctx);
  12237. pthread_setspecific(sTlsKey, NULL);
  12238. return NULL;
  12239. }
  12240. if (ctx->config[idx] != NULL) {
  12241. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12242. mg_free(ctx->config[idx]);
  12243. }
  12244. ctx->config[idx] = mg_strdup(value);
  12245. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12246. }
  12247. /* Set default value if needed */
  12248. for (i = 0; config_options[i].name != NULL; i++) {
  12249. default_value = config_options[i].default_value;
  12250. if (ctx->config[i] == NULL && default_value != NULL) {
  12251. ctx->config[i] = mg_strdup(default_value);
  12252. }
  12253. }
  12254. #if defined(NO_FILES)
  12255. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12256. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12257. free_context(ctx);
  12258. pthread_setspecific(sTlsKey, NULL);
  12259. return NULL;
  12260. }
  12261. #endif
  12262. get_system_name(&ctx->systemName);
  12263. /* NOTE(lsm): order is important here. SSL certificates must
  12264. * be initialized before listening ports. UID must be set last. */
  12265. if (!set_gpass_option(ctx) ||
  12266. #if !defined(NO_SSL)
  12267. !set_ssl_option(ctx) ||
  12268. #endif
  12269. !set_ports_option(ctx) ||
  12270. #if !defined(_WIN32)
  12271. !set_uid_option(ctx) ||
  12272. #endif
  12273. !set_acl_option(ctx)) {
  12274. free_context(ctx);
  12275. pthread_setspecific(sTlsKey, NULL);
  12276. return NULL;
  12277. }
  12278. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12279. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12280. * won't kill the whole process. */
  12281. (void)signal(SIGPIPE, SIG_IGN);
  12282. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12283. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12284. if (workerthreadcount > MAX_WORKER_THREADS) {
  12285. mg_cry(fc(ctx), "Too many worker threads");
  12286. free_context(ctx);
  12287. pthread_setspecific(sTlsKey, NULL);
  12288. return NULL;
  12289. }
  12290. if (workerthreadcount > 0) {
  12291. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12292. ctx->workerthreadids =
  12293. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12294. if (ctx->workerthreadids == NULL) {
  12295. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12296. free_context(ctx);
  12297. pthread_setspecific(sTlsKey, NULL);
  12298. return NULL;
  12299. }
  12300. #if defined(ALTERNATIVE_QUEUE)
  12301. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  12302. ctx->cfg_worker_threads);
  12303. if (ctx->client_wait_events == NULL) {
  12304. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12305. mg_free(ctx->workerthreadids);
  12306. free_context(ctx);
  12307. pthread_setspecific(sTlsKey, NULL);
  12308. return NULL;
  12309. }
  12310. ctx->client_socks =
  12311. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12312. if (ctx->client_wait_events == NULL) {
  12313. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12314. mg_free(ctx->client_socks);
  12315. mg_free(ctx->workerthreadids);
  12316. free_context(ctx);
  12317. pthread_setspecific(sTlsKey, NULL);
  12318. return NULL;
  12319. }
  12320. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12321. ctx->client_wait_events[i] = event_create();
  12322. if (ctx->client_wait_events[i] == 0) {
  12323. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12324. /* TODO: clean all and exit */
  12325. }
  12326. }
  12327. #endif
  12328. }
  12329. #if defined(USE_TIMERS)
  12330. if (timers_init(ctx) != 0) {
  12331. mg_cry(fc(ctx), "Error creating timers");
  12332. free_context(ctx);
  12333. pthread_setspecific(sTlsKey, NULL);
  12334. return NULL;
  12335. }
  12336. #endif
  12337. /* Context has been created - init user libraries */
  12338. if (ctx->callbacks.init_context) {
  12339. ctx->callbacks.init_context(ctx);
  12340. }
  12341. ctx->callbacks.exit_context = exit_callback;
  12342. ctx->context_type = 1; /* server context */
  12343. /* Start master (listening) thread */
  12344. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12345. /* Start worker threads */
  12346. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12347. struct worker_thread_args *wta =
  12348. mg_malloc(sizeof(struct worker_thread_args));
  12349. if (wta) {
  12350. wta->ctx = ctx;
  12351. wta->index = (int)i;
  12352. }
  12353. if ((wta == NULL)
  12354. || (mg_start_thread_with_id(worker_thread,
  12355. wta,
  12356. &ctx->workerthreadids[i]) != 0)) {
  12357. /* thread was not created */
  12358. if (wta != NULL) {
  12359. mg_free(wta);
  12360. }
  12361. if (i > 0) {
  12362. mg_cry(fc(ctx),
  12363. "Cannot start worker thread %i: error %ld",
  12364. i + 1,
  12365. (long)ERRNO);
  12366. } else {
  12367. mg_cry(fc(ctx),
  12368. "Cannot create threads: error %ld",
  12369. (long)ERRNO);
  12370. free_context(ctx);
  12371. pthread_setspecific(sTlsKey, NULL);
  12372. return NULL;
  12373. }
  12374. break;
  12375. }
  12376. }
  12377. pthread_setspecific(sTlsKey, NULL);
  12378. return ctx;
  12379. }
  12380. /* Feature check API function */
  12381. unsigned
  12382. mg_check_feature(unsigned feature)
  12383. {
  12384. static const unsigned feature_set = 0
  12385. /* Set bits for available features according to API documentation.
  12386. * This bit mask is created at compile time, according to the active
  12387. * preprocessor defines. It is a single const value at runtime. */
  12388. #if !defined(NO_FILES)
  12389. | 0x0001u
  12390. #endif
  12391. #if !defined(NO_SSL)
  12392. | 0x0002u
  12393. #endif
  12394. #if !defined(NO_CGI)
  12395. | 0x0004u
  12396. #endif
  12397. #if defined(USE_IPV6)
  12398. | 0x0008u
  12399. #endif
  12400. #if defined(USE_WEBSOCKET)
  12401. | 0x0010u
  12402. #endif
  12403. #if defined(USE_LUA)
  12404. | 0x0020u
  12405. #endif
  12406. #if defined(USE_DUKTAPE)
  12407. | 0x0040u
  12408. #endif
  12409. #if !defined(NO_CACHING)
  12410. | 0x0080u
  12411. #endif
  12412. /* Set some extra bits not defined in the API documentation.
  12413. * These bits may change without further notice. */
  12414. #if defined(MG_LEGACY_INTERFACE)
  12415. | 0x8000u
  12416. #endif
  12417. #if defined(MEMORY_DEBUGGING)
  12418. | 0x0100u
  12419. #endif
  12420. #if defined(USE_TIMERS)
  12421. | 0x0200u
  12422. #endif
  12423. #if !defined(NO_NONCE_CHECK)
  12424. | 0x0400u
  12425. #endif
  12426. #if !defined(NO_POPEN)
  12427. | 0x0800u
  12428. #endif
  12429. ;
  12430. return (feature & feature_set);
  12431. }