civetweb.c 368 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193
  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. #ifndef MAX_WORKER_THREADS
  200. #define MAX_WORKER_THREADS (1024 * 64)
  201. #endif
  202. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  203. #define SOCKET_TIMEOUT_QUANTUM (2000)
  204. #endif
  205. #define SHUTDOWN_RD (0)
  206. #define SHUTDOWN_WR (1)
  207. #define SHUTDOWN_BOTH (2)
  208. mg_static_assert(MAX_WORKER_THREADS >= 1,
  209. "worker threads must be a positive number");
  210. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  211. "size_t data type size check");
  212. #if defined(_WIN32) \
  213. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  214. #include <windows.h>
  215. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  216. #include <ws2tcpip.h>
  217. typedef const char *SOCK_OPT_TYPE;
  218. #if !defined(PATH_MAX)
  219. #define PATH_MAX (MAX_PATH)
  220. #endif
  221. #if !defined(PATH_MAX)
  222. #define PATH_MAX (4096)
  223. #endif
  224. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  225. #ifndef _IN_PORT_T
  226. #ifndef in_port_t
  227. #define in_port_t u_short
  228. #endif
  229. #endif
  230. #ifndef _WIN32_WCE
  231. #include <process.h>
  232. #include <direct.h>
  233. #include <io.h>
  234. #else /* _WIN32_WCE */
  235. #define NO_CGI /* WinCE has no pipes */
  236. #define NO_POPEN /* WinCE has no popen */
  237. typedef long off_t;
  238. #define errno ((int)(GetLastError()))
  239. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  240. #endif /* _WIN32_WCE */
  241. #define MAKEUQUAD(lo, hi) \
  242. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  243. #define RATE_DIFF (10000000) /* 100 nsecs */
  244. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  245. #define SYS2UNIX_TIME(lo, hi) \
  246. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  247. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  248. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  249. * Also use _strtoui64 on modern M$ compilers */
  250. #if defined(_MSC_VER)
  251. #if (_MSC_VER < 1300)
  252. #define STRX(x) #x
  253. #define STR(x) STRX(x)
  254. #define __func__ __FILE__ ":" STR(__LINE__)
  255. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  256. #define strtoll(x, y, z) (_atoi64(x))
  257. #else
  258. #define __func__ __FUNCTION__
  259. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  260. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  261. #endif
  262. #endif /* _MSC_VER */
  263. #define ERRNO ((int)(GetLastError()))
  264. #define NO_SOCKLEN_T
  265. #if defined(_WIN64) || defined(__MINGW64__)
  266. #define SSL_LIB "ssleay64.dll"
  267. #define CRYPTO_LIB "libeay64.dll"
  268. #else
  269. #define SSL_LIB "ssleay32.dll"
  270. #define CRYPTO_LIB "libeay32.dll"
  271. #endif
  272. #define O_NONBLOCK (0)
  273. #ifndef W_OK
  274. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  275. #endif
  276. #if !defined(EWOULDBLOCK)
  277. #define EWOULDBLOCK WSAEWOULDBLOCK
  278. #endif /* !EWOULDBLOCK */
  279. #define _POSIX_
  280. #define INT64_FMT "I64d"
  281. #define UINT64_FMT "I64u"
  282. #define WINCDECL __cdecl
  283. #define vsnprintf_impl _vsnprintf
  284. #define access _access
  285. #define mg_sleep(x) (Sleep(x))
  286. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  287. #ifndef popen
  288. #define popen(x, y) (_popen(x, y))
  289. #endif
  290. #ifndef pclose
  291. #define pclose(x) (_pclose(x))
  292. #endif
  293. #define close(x) (_close(x))
  294. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  295. #define RTLD_LAZY (0)
  296. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  297. #define fdopen(x, y) (_fdopen((x), (y)))
  298. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  299. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  300. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  301. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  302. #define sleep(x) (Sleep((x)*1000))
  303. #define rmdir(x) (_rmdir(x))
  304. #define timegm(x) (_mkgmtime(x))
  305. #if !defined(fileno)
  306. #define fileno(x) (_fileno(x))
  307. #endif /* !fileno MINGW #defines fileno */
  308. typedef HANDLE pthread_mutex_t;
  309. typedef DWORD pthread_key_t;
  310. typedef HANDLE pthread_t;
  311. typedef struct {
  312. CRITICAL_SECTION threadIdSec;
  313. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  314. } pthread_cond_t;
  315. #ifndef __clockid_t_defined
  316. typedef DWORD clockid_t;
  317. #endif
  318. #ifndef CLOCK_MONOTONIC
  319. #define CLOCK_MONOTONIC (1)
  320. #endif
  321. #ifndef CLOCK_REALTIME
  322. #define CLOCK_REALTIME (2)
  323. #endif
  324. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  325. #define _TIMESPEC_DEFINED
  326. #endif
  327. #ifndef _TIMESPEC_DEFINED
  328. struct timespec {
  329. time_t tv_sec; /* seconds */
  330. long tv_nsec; /* nanoseconds */
  331. };
  332. #endif
  333. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  334. static int pthread_mutex_lock(pthread_mutex_t *);
  335. static int pthread_mutex_unlock(pthread_mutex_t *);
  336. static void path_to_unicode(const struct mg_connection *conn,
  337. const char *path,
  338. wchar_t *wbuf,
  339. size_t wbuf_len);
  340. struct file;
  341. static const char *
  342. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  343. #if defined(HAVE_STDINT)
  344. #include <stdint.h>
  345. #else
  346. typedef unsigned char uint8_t;
  347. typedef unsigned short uint16_t;
  348. typedef unsigned int uint32_t;
  349. typedef unsigned __int64 uint64_t;
  350. typedef __int64 int64_t;
  351. #ifndef INT64_MAX
  352. #define INT64_MAX (9223372036854775807)
  353. #endif
  354. #endif /* HAVE_STDINT */
  355. /* POSIX dirent interface */
  356. struct dirent {
  357. char d_name[PATH_MAX];
  358. };
  359. typedef struct DIR {
  360. HANDLE handle;
  361. WIN32_FIND_DATAW info;
  362. struct dirent result;
  363. } DIR;
  364. #if defined(_WIN32) && !defined(POLLIN)
  365. #ifndef HAVE_POLL
  366. struct pollfd {
  367. SOCKET fd;
  368. short events;
  369. short revents;
  370. };
  371. #define POLLIN (0x0300)
  372. #endif
  373. #endif
  374. /* Mark required libraries */
  375. #if defined(_MSC_VER)
  376. #pragma comment(lib, "Ws2_32.lib")
  377. #endif
  378. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  379. WINDOWS / UNIX include block */
  380. #include <sys/wait.h>
  381. #include <sys/socket.h>
  382. #include <sys/poll.h>
  383. #include <netinet/in.h>
  384. #include <arpa/inet.h>
  385. #include <sys/time.h>
  386. #include <sys/utsname.h>
  387. #include <stdint.h>
  388. #include <inttypes.h>
  389. #include <netdb.h>
  390. #include <netinet/tcp.h>
  391. typedef const void *SOCK_OPT_TYPE;
  392. #if defined(ANDROID)
  393. typedef unsigned short int in_port_t;
  394. #endif
  395. #include <pwd.h>
  396. #include <unistd.h>
  397. #include <grp.h>
  398. #include <dirent.h>
  399. #define vsnprintf_impl vsnprintf
  400. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  401. #include <dlfcn.h>
  402. #endif
  403. #include <pthread.h>
  404. #if defined(__MACH__)
  405. #define SSL_LIB "libssl.dylib"
  406. #define CRYPTO_LIB "libcrypto.dylib"
  407. #else
  408. #if !defined(SSL_LIB)
  409. #define SSL_LIB "libssl.so"
  410. #endif
  411. #if !defined(CRYPTO_LIB)
  412. #define CRYPTO_LIB "libcrypto.so"
  413. #endif
  414. #endif
  415. #ifndef O_BINARY
  416. #define O_BINARY (0)
  417. #endif /* O_BINARY */
  418. #define closesocket(a) (close(a))
  419. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  420. #define mg_remove(conn, x) (remove(x))
  421. #define mg_sleep(x) (usleep((x)*1000))
  422. #define mg_opendir(conn, x) (opendir(x))
  423. #define mg_closedir(x) (closedir(x))
  424. #define mg_readdir(x) (readdir(x))
  425. #define ERRNO (errno)
  426. #define INVALID_SOCKET (-1)
  427. #define INT64_FMT PRId64
  428. #define UINT64_FMT PRIu64
  429. typedef int SOCKET;
  430. #define WINCDECL
  431. #if defined(__hpux)
  432. /* HPUX 11 does not have monotonic, fall back to realtime */
  433. #ifndef CLOCK_MONOTONIC
  434. #define CLOCK_MONOTONIC CLOCK_REALTIME
  435. #endif
  436. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  437. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  438. * the prototypes use int* rather than socklen_t* which matches the
  439. * actual library expectation. When called with the wrong size arg
  440. * accept() returns a zero client inet addr and check_acl() always
  441. * fails. Since socklen_t is widely used below, just force replace
  442. * their typedef with int. - DTL
  443. */
  444. #define socklen_t int
  445. #endif /* hpux */
  446. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  447. WINDOWS / UNIX include block */
  448. /* va_copy should always be a macro, C99 and C++11 - DTL */
  449. #ifndef va_copy
  450. #define va_copy(x, y) ((x) = (y))
  451. #endif
  452. #ifdef _WIN32
  453. /* Create substitutes for POSIX functions in Win32. */
  454. #if defined(__MINGW32__)
  455. /* Show no warning in case system functions are not used. */
  456. #pragma GCC diagnostic push
  457. #pragma GCC diagnostic ignored "-Wunused-function"
  458. #endif
  459. static CRITICAL_SECTION global_log_file_lock;
  460. static DWORD
  461. pthread_self(void)
  462. {
  463. return GetCurrentThreadId();
  464. }
  465. static int
  466. pthread_key_create(
  467. pthread_key_t *key,
  468. void (*_ignored)(void *) /* destructor not supported for Windows */
  469. )
  470. {
  471. (void)_ignored;
  472. if ((key != 0)) {
  473. *key = TlsAlloc();
  474. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  475. }
  476. return -2;
  477. }
  478. static int
  479. pthread_key_delete(pthread_key_t key)
  480. {
  481. return TlsFree(key) ? 0 : 1;
  482. }
  483. static int
  484. pthread_setspecific(pthread_key_t key, void *value)
  485. {
  486. return TlsSetValue(key, value) ? 0 : 1;
  487. }
  488. static void *
  489. pthread_getspecific(pthread_key_t key)
  490. {
  491. return TlsGetValue(key);
  492. }
  493. #if defined(__MINGW32__)
  494. /* Enable unused function warning again */
  495. #pragma GCC diagnostic pop
  496. #endif
  497. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  498. #else
  499. static pthread_mutexattr_t pthread_mutex_attr;
  500. #endif /* _WIN32 */
  501. #define PASSWORDS_FILE_NAME ".htpasswd"
  502. #define CGI_ENVIRONMENT_SIZE (4096)
  503. #define MAX_CGI_ENVIR_VARS (256)
  504. #define MG_BUF_LEN (8192)
  505. #ifndef MAX_REQUEST_SIZE
  506. #define MAX_REQUEST_SIZE (16384)
  507. #endif
  508. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  509. "request size length must be a positive number");
  510. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  511. #if !defined(DEBUG_TRACE)
  512. #if defined(DEBUG)
  513. #if defined(_WIN32_WCE)
  514. /* Create substitutes for POSIX functions in Win32. */
  515. #if defined(__MINGW32__)
  516. /* Show no warning in case system functions are not used. */
  517. #pragma GCC diagnostic push
  518. #pragma GCC diagnostic ignored "-Wunused-function"
  519. #endif
  520. static time_t
  521. time(time_t *ptime)
  522. {
  523. time_t t;
  524. SYSTEMTIME st;
  525. FILETIME ft;
  526. GetSystemTime(&st);
  527. SystemTimeToFileTime(&st, &ft);
  528. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  529. if (ptime != NULL) {
  530. *ptime = t;
  531. }
  532. return t;
  533. }
  534. static struct tm *
  535. localtime_s(const time_t *ptime, struct tm *ptm)
  536. {
  537. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  538. FILETIME ft, lft;
  539. SYSTEMTIME st;
  540. TIME_ZONE_INFORMATION tzinfo;
  541. if (ptm == NULL) {
  542. return NULL;
  543. }
  544. *(int64_t *)&ft = t;
  545. FileTimeToLocalFileTime(&ft, &lft);
  546. FileTimeToSystemTime(&lft, &st);
  547. ptm->tm_year = st.wYear - 1900;
  548. ptm->tm_mon = st.wMonth - 1;
  549. ptm->tm_wday = st.wDayOfWeek;
  550. ptm->tm_mday = st.wDay;
  551. ptm->tm_hour = st.wHour;
  552. ptm->tm_min = st.wMinute;
  553. ptm->tm_sec = st.wSecond;
  554. ptm->tm_yday = 0; /* hope nobody uses this */
  555. ptm->tm_isdst =
  556. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  557. return ptm;
  558. }
  559. static struct tm *
  560. gmtime_s(const time_t *ptime, struct tm *ptm)
  561. {
  562. /* FIXME(lsm): fix this. */
  563. return localtime_s(ptime, ptm);
  564. }
  565. static int mg_atomic_inc(volatile int *addr);
  566. static struct tm tm_array[MAX_WORKER_THREADS];
  567. static int tm_index = 0;
  568. static struct tm *
  569. localtime(const time_t *ptime)
  570. {
  571. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  572. return localtime_s(ptime, tm_array + i);
  573. }
  574. static struct tm *
  575. gmtime(const time_t *ptime)
  576. {
  577. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  578. return gmtime_s(ptime, tm_array + i);
  579. }
  580. static size_t
  581. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  582. {
  583. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  584. // for WinCE");
  585. return 0;
  586. }
  587. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  588. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  589. #define remove(f) mg_remove(NULL, f)
  590. static int
  591. rename(const char *a, const char *b)
  592. {
  593. wchar_t wa[PATH_MAX];
  594. wchar_t wb[PATH_MAX];
  595. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  596. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  597. return MoveFileW(wa, wb) ? 0 : -1;
  598. }
  599. struct stat {
  600. int64_t st_size;
  601. time_t st_mtime;
  602. };
  603. static int
  604. stat(const char *name, struct stat *st)
  605. {
  606. wchar_t wbuf[PATH_MAX];
  607. WIN32_FILE_ATTRIBUTE_DATA attr;
  608. time_t creation_time, write_time;
  609. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  610. memset(&attr, 0, sizeof(attr));
  611. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  612. st->st_size =
  613. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  614. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  615. attr.ftLastWriteTime.dwHighDateTime);
  616. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  617. attr.ftCreationTime.dwHighDateTime);
  618. if (creation_time > write_time) {
  619. st->st_mtime = creation_time;
  620. } else {
  621. st->st_mtime = write_time;
  622. }
  623. return 0;
  624. }
  625. #define access(x, a) 1 /* not required anyway */
  626. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  627. #define EEXIST 1 /* TODO: See Windows error codes */
  628. #define EACCES 2 /* TODO: See Windows error codes */
  629. #define ENOENT 3 /* TODO: See Windows Error codes */
  630. #if defined(__MINGW32__)
  631. /* Enable unused function warning again */
  632. #pragma GCC diagnostic pop
  633. #endif
  634. #endif /* defined(_WIN32_WCE) */
  635. static void DEBUG_TRACE_FUNC(const char *func,
  636. unsigned line,
  637. PRINTF_FORMAT_STRING(const char *fmt),
  638. ...) PRINTF_ARGS(3, 4);
  639. static void
  640. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  641. {
  642. va_list args;
  643. flockfile(stdout);
  644. printf("*** %lu.%p.%s.%u: ",
  645. (unsigned long)time(NULL),
  646. (void *)pthread_self(),
  647. func,
  648. line);
  649. va_start(args, fmt);
  650. vprintf(fmt, args);
  651. va_end(args);
  652. putchar('\n');
  653. fflush(stdout);
  654. funlockfile(stdout);
  655. }
  656. #define DEBUG_TRACE(fmt, ...) \
  657. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  658. #else
  659. #define DEBUG_TRACE(fmt, ...) \
  660. do { \
  661. } while (0)
  662. #endif /* DEBUG */
  663. #endif /* DEBUG_TRACE */
  664. #if defined(MEMORY_DEBUGGING)
  665. unsigned long mg_memory_debug_blockCount = 0;
  666. unsigned long mg_memory_debug_totalMemUsed = 0;
  667. static void *
  668. mg_malloc_ex(size_t size, const char *file, unsigned line)
  669. {
  670. void *data = malloc(size + sizeof(size_t));
  671. void *memory = 0;
  672. char mallocStr[256];
  673. if (data) {
  674. *(size_t *)data = size;
  675. mg_memory_debug_totalMemUsed += size;
  676. mg_memory_debug_blockCount++;
  677. memory = (void *)(((char *)data) + sizeof(size_t));
  678. }
  679. sprintf(mallocStr,
  680. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  681. memory,
  682. (unsigned long)size,
  683. mg_memory_debug_totalMemUsed,
  684. mg_memory_debug_blockCount,
  685. file,
  686. line);
  687. #if defined(_WIN32)
  688. OutputDebugStringA(mallocStr);
  689. #else
  690. DEBUG_TRACE("%s", mallocStr);
  691. #endif
  692. return memory;
  693. }
  694. static void *
  695. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  696. {
  697. void *data = mg_malloc_ex(size * count, file, line);
  698. if (data) {
  699. memset(data, 0, size * count);
  700. }
  701. return data;
  702. }
  703. static void
  704. mg_free_ex(void *memory, const char *file, unsigned line)
  705. {
  706. char mallocStr[256];
  707. void *data = (void *)(((char *)memory) - sizeof(size_t));
  708. size_t size;
  709. if (memory) {
  710. size = *(size_t *)data;
  711. mg_memory_debug_totalMemUsed -= size;
  712. mg_memory_debug_blockCount--;
  713. sprintf(mallocStr,
  714. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  715. memory,
  716. (unsigned long)size,
  717. mg_memory_debug_totalMemUsed,
  718. mg_memory_debug_blockCount,
  719. file,
  720. line);
  721. #if defined(_WIN32)
  722. OutputDebugStringA(mallocStr);
  723. #else
  724. DEBUG_TRACE("%s", mallocStr);
  725. #endif
  726. free(data);
  727. }
  728. }
  729. static void *
  730. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  731. {
  732. char mallocStr[256];
  733. void *data;
  734. void *_realloc;
  735. size_t oldsize;
  736. if (newsize) {
  737. if (memory) {
  738. data = (void *)(((char *)memory) - sizeof(size_t));
  739. oldsize = *(size_t *)data;
  740. _realloc = realloc(data, newsize + sizeof(size_t));
  741. if (_realloc) {
  742. data = _realloc;
  743. mg_memory_debug_totalMemUsed -= oldsize;
  744. sprintf(mallocStr,
  745. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  746. memory,
  747. (unsigned long)oldsize,
  748. mg_memory_debug_totalMemUsed,
  749. mg_memory_debug_blockCount,
  750. file,
  751. line);
  752. #if defined(_WIN32)
  753. OutputDebugStringA(mallocStr);
  754. #else
  755. DEBUG_TRACE("%s", mallocStr);
  756. #endif
  757. mg_memory_debug_totalMemUsed += newsize;
  758. sprintf(mallocStr,
  759. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  760. memory,
  761. (unsigned long)newsize,
  762. mg_memory_debug_totalMemUsed,
  763. mg_memory_debug_blockCount,
  764. file,
  765. line);
  766. #if defined(_WIN32)
  767. OutputDebugStringA(mallocStr);
  768. #else
  769. DEBUG_TRACE("%s", mallocStr);
  770. #endif
  771. *(size_t *)data = newsize;
  772. data = (void *)(((char *)data) + sizeof(size_t));
  773. } else {
  774. #if defined(_WIN32)
  775. OutputDebugStringA("MEM: realloc failed\n");
  776. #else
  777. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  778. #endif
  779. return _realloc;
  780. }
  781. } else {
  782. data = mg_malloc_ex(newsize, file, line);
  783. }
  784. } else {
  785. data = 0;
  786. mg_free_ex(memory, file, line);
  787. }
  788. return data;
  789. }
  790. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  791. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  792. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  793. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  794. #else
  795. static __inline void *
  796. mg_malloc(size_t a)
  797. {
  798. return malloc(a);
  799. }
  800. static __inline void *
  801. mg_calloc(size_t a, size_t b)
  802. {
  803. return calloc(a, b);
  804. }
  805. static __inline void *
  806. mg_realloc(void *a, size_t b)
  807. {
  808. return realloc(a, b);
  809. }
  810. static __inline void
  811. mg_free(void *a)
  812. {
  813. free(a);
  814. }
  815. #endif
  816. static void mg_vsnprintf(const struct mg_connection *conn,
  817. int *truncated,
  818. char *buf,
  819. size_t buflen,
  820. const char *fmt,
  821. va_list ap);
  822. static void mg_snprintf(const struct mg_connection *conn,
  823. int *truncated,
  824. char *buf,
  825. size_t buflen,
  826. PRINTF_FORMAT_STRING(const char *fmt),
  827. ...) PRINTF_ARGS(5, 6);
  828. /* This following lines are just meant as a reminder to use the mg-functions
  829. * for memory management */
  830. #ifdef malloc
  831. #undef malloc
  832. #endif
  833. #ifdef calloc
  834. #undef calloc
  835. #endif
  836. #ifdef realloc
  837. #undef realloc
  838. #endif
  839. #ifdef free
  840. #undef free
  841. #endif
  842. #ifdef snprintf
  843. #undef snprintf
  844. #endif
  845. #ifdef vsnprintf
  846. #undef vsnprintf
  847. #endif
  848. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  849. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  850. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  851. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  852. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  853. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  854. * but this define only works well for Windows. */
  855. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  856. #endif
  857. #define MD5_STATIC static
  858. #include "md5.inl"
  859. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  860. #ifdef NO_SOCKLEN_T
  861. typedef int socklen_t;
  862. #endif /* NO_SOCKLEN_T */
  863. #define _DARWIN_UNLIMITED_SELECT
  864. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  865. #if !defined(MSG_NOSIGNAL)
  866. #define MSG_NOSIGNAL (0)
  867. #endif
  868. #if !defined(SOMAXCONN)
  869. #define SOMAXCONN (100)
  870. #endif
  871. /* Size of the accepted socket queue */
  872. #if !defined(MGSQLEN)
  873. #define MGSQLEN (20)
  874. #endif
  875. #if defined(NO_SSL)
  876. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  877. typedef struct SSL_CTX SSL_CTX;
  878. #else
  879. #if defined(NO_SSL_DL)
  880. #include <openssl/ssl.h>
  881. #include <openssl/err.h>
  882. #include <openssl/crypto.h>
  883. #include <openssl/x509.h>
  884. #include <openssl/pem.h>
  885. #include <openssl/engine.h>
  886. #include <openssl/conf.h>
  887. #include <openssl/dh.h>
  888. #else
  889. /* SSL loaded dynamically from DLL.
  890. * I put the prototypes here to be independent from OpenSSL source
  891. * installation. */
  892. typedef struct ssl_st SSL;
  893. typedef struct ssl_method_st SSL_METHOD;
  894. typedef struct ssl_ctx_st SSL_CTX;
  895. typedef struct x509_store_ctx_st X509_STORE_CTX;
  896. typedef struct x509_name X509_NAME;
  897. typedef struct asn1_integer ASN1_INTEGER;
  898. typedef struct evp_md EVP_MD;
  899. typedef struct x509 X509;
  900. #define SSL_CTRL_OPTIONS (32)
  901. #define SSL_CTRL_CLEAR_OPTIONS (77)
  902. #define SSL_CTRL_SET_ECDH_AUTO (94)
  903. #define SSL_VERIFY_NONE (0)
  904. #define SSL_VERIFY_PEER (1)
  905. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  906. #define SSL_VERIFY_CLIENT_ONCE (4)
  907. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  908. #define SSL_OP_NO_SSLv2 (0x01000000L)
  909. #define SSL_OP_NO_SSLv3 (0x02000000L)
  910. #define SSL_OP_NO_TLSv1 (0x04000000L)
  911. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  912. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  913. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  914. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  915. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  916. #define SSL_ERROR_NONE (0)
  917. #define SSL_ERROR_SSL (1)
  918. #define SSL_ERROR_WANT_READ (2)
  919. #define SSL_ERROR_WANT_WRITE (3)
  920. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  921. #define SSL_ERROR_SYSCALL (5) /* see errno */
  922. #define SSL_ERROR_ZERO_RETURN (6)
  923. #define SSL_ERROR_WANT_CONNECT (7)
  924. #define SSL_ERROR_WANT_ACCEPT (8)
  925. struct ssl_func {
  926. const char *name; /* SSL function name */
  927. void (*ptr)(void); /* Function pointer */
  928. };
  929. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  930. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  931. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  932. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  933. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  934. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  935. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  936. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  937. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  938. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  939. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  940. #define SSL_CTX_use_PrivateKey_file \
  941. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  942. #define SSL_CTX_use_certificate_file \
  943. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  944. #define SSL_CTX_set_default_passwd_cb \
  945. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  946. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  947. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  948. #define SSL_CTX_use_certificate_chain_file \
  949. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  950. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  951. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  952. #define SSL_CTX_set_verify \
  953. (*(void (*)(SSL_CTX *, \
  954. int, \
  955. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  956. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  957. #define SSL_CTX_load_verify_locations \
  958. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  959. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  960. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  961. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  962. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  963. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  964. #define SSL_CIPHER_get_name \
  965. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  966. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  967. #define SSL_CTX_set_session_id_context \
  968. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  969. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  970. #define SSL_CTX_set_cipher_list \
  971. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  972. #define SSL_CTX_set_options(ctx, op) \
  973. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  974. #define SSL_CTX_clear_options(ctx, op) \
  975. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  976. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  977. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  978. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  979. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  980. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  981. #define CRYPTO_set_locking_callback \
  982. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  983. #define CRYPTO_set_id_callback \
  984. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  985. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  986. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  987. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  988. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  989. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  990. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  991. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  992. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  993. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  994. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  995. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  996. #define X509_NAME_oneline \
  997. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  998. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  999. #define i2c_ASN1_INTEGER \
  1000. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1001. #define EVP_get_digestbyname \
  1002. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1003. #define ASN1_digest \
  1004. (*(int (*)(int (*)(), \
  1005. const EVP_MD *, \
  1006. char *, \
  1007. unsigned char *, \
  1008. unsigned int *))crypto_sw[18].ptr)
  1009. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1010. /* set_ssl_option() function updates this array.
  1011. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1012. * of respective functions. The macros above (like SSL_connect()) are really
  1013. * just calling these functions indirectly via the pointer. */
  1014. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1015. {"SSL_accept", NULL},
  1016. {"SSL_connect", NULL},
  1017. {"SSL_read", NULL},
  1018. {"SSL_write", NULL},
  1019. {"SSL_get_error", NULL},
  1020. {"SSL_set_fd", NULL},
  1021. {"SSL_new", NULL},
  1022. {"SSL_CTX_new", NULL},
  1023. {"SSLv23_server_method", NULL},
  1024. {"SSL_library_init", NULL},
  1025. {"SSL_CTX_use_PrivateKey_file", NULL},
  1026. {"SSL_CTX_use_certificate_file", NULL},
  1027. {"SSL_CTX_set_default_passwd_cb", NULL},
  1028. {"SSL_CTX_free", NULL},
  1029. {"SSL_load_error_strings", NULL},
  1030. {"SSL_CTX_use_certificate_chain_file", NULL},
  1031. {"SSLv23_client_method", NULL},
  1032. {"SSL_pending", NULL},
  1033. {"SSL_CTX_set_verify", NULL},
  1034. {"SSL_shutdown", NULL},
  1035. {"SSL_CTX_load_verify_locations", NULL},
  1036. {"SSL_CTX_set_default_verify_paths", NULL},
  1037. {"SSL_CTX_set_verify_depth", NULL},
  1038. {"SSL_get_peer_certificate", NULL},
  1039. {"SSL_get_version", NULL},
  1040. {"SSL_get_current_cipher", NULL},
  1041. {"SSL_CIPHER_get_name", NULL},
  1042. {"SSL_CTX_check_private_key", NULL},
  1043. {"SSL_CTX_set_session_id_context", NULL},
  1044. {"SSL_CTX_ctrl", NULL},
  1045. {"SSL_CTX_set_cipher_list", NULL},
  1046. {NULL, NULL}};
  1047. /* Similar array as ssl_sw. These functions could be located in different
  1048. * lib. */
  1049. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1050. {"CRYPTO_set_locking_callback", NULL},
  1051. {"CRYPTO_set_id_callback", NULL},
  1052. {"ERR_get_error", NULL},
  1053. {"ERR_error_string", NULL},
  1054. {"ERR_remove_state", NULL},
  1055. {"ERR_free_strings", NULL},
  1056. {"ENGINE_cleanup", NULL},
  1057. {"CONF_modules_unload", NULL},
  1058. {"CRYPTO_cleanup_all_ex_data", NULL},
  1059. {"EVP_cleanup", NULL},
  1060. {"X509_free", NULL},
  1061. {"X509_get_subject_name", NULL},
  1062. {"X509_get_issuer_name", NULL},
  1063. {"X509_NAME_oneline", NULL},
  1064. {"X509_get_serialNumber", NULL},
  1065. {"i2c_ASN1_INTEGER", NULL},
  1066. {"EVP_get_digestbyname", NULL},
  1067. {"ASN1_digest", NULL},
  1068. {"i2d_X509", NULL},
  1069. {NULL, NULL}};
  1070. #endif /* NO_SSL_DL */
  1071. #endif /* NO_SSL */
  1072. #if !defined(NO_CACHING)
  1073. static const char *month_names[] = {"Jan",
  1074. "Feb",
  1075. "Mar",
  1076. "Apr",
  1077. "May",
  1078. "Jun",
  1079. "Jul",
  1080. "Aug",
  1081. "Sep",
  1082. "Oct",
  1083. "Nov",
  1084. "Dec"};
  1085. #endif /* !NO_CACHING */
  1086. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1087. * union u. */
  1088. union usa {
  1089. struct sockaddr sa;
  1090. struct sockaddr_in sin;
  1091. #if defined(USE_IPV6)
  1092. struct sockaddr_in6 sin6;
  1093. #endif
  1094. };
  1095. /* Describes a string (chunk of memory). */
  1096. struct vec {
  1097. const char *ptr;
  1098. size_t len;
  1099. };
  1100. struct file {
  1101. uint64_t size;
  1102. time_t last_modified;
  1103. FILE *fp;
  1104. const char *membuf; /* Non-NULL if file data is in memory */
  1105. int is_directory;
  1106. int gzipped; /* set to 1 if the content is gzipped
  1107. * in which case we need a content-encoding: gzip header */
  1108. };
  1109. #define STRUCT_FILE_INITIALIZER \
  1110. { \
  1111. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1112. }
  1113. /* Describes listening socket, or socket which was accept()-ed by the master
  1114. * thread and queued for future handling by the worker thread. */
  1115. struct socket {
  1116. SOCKET sock; /* Listening socket */
  1117. union usa lsa; /* Local socket address */
  1118. union usa rsa; /* Remote socket address */
  1119. unsigned char is_ssl; /* Is port SSL-ed */
  1120. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1121. * port */
  1122. unsigned char in_use; /* Is valid */
  1123. };
  1124. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1125. enum {
  1126. CGI_EXTENSIONS,
  1127. CGI_ENVIRONMENT,
  1128. PUT_DELETE_PASSWORDS_FILE,
  1129. CGI_INTERPRETER,
  1130. PROTECT_URI,
  1131. AUTHENTICATION_DOMAIN,
  1132. SSI_EXTENSIONS,
  1133. THROTTLE,
  1134. ACCESS_LOG_FILE,
  1135. ENABLE_DIRECTORY_LISTING,
  1136. ERROR_LOG_FILE,
  1137. GLOBAL_PASSWORDS_FILE,
  1138. INDEX_FILES,
  1139. ENABLE_KEEP_ALIVE,
  1140. ACCESS_CONTROL_LIST,
  1141. EXTRA_MIME_TYPES,
  1142. LISTENING_PORTS,
  1143. DOCUMENT_ROOT,
  1144. SSL_CERTIFICATE,
  1145. NUM_THREADS,
  1146. RUN_AS_USER,
  1147. REWRITE,
  1148. HIDE_FILES,
  1149. REQUEST_TIMEOUT,
  1150. SSL_DO_VERIFY_PEER,
  1151. SSL_CA_PATH,
  1152. SSL_CA_FILE,
  1153. SSL_VERIFY_DEPTH,
  1154. SSL_DEFAULT_VERIFY_PATHS,
  1155. SSL_CIPHER_LIST,
  1156. SSL_PROTOCOL_VERSION,
  1157. SSL_SHORT_TRUST,
  1158. #if defined(USE_WEBSOCKET)
  1159. WEBSOCKET_TIMEOUT,
  1160. #endif
  1161. DECODE_URL,
  1162. #if defined(USE_LUA)
  1163. LUA_PRELOAD_FILE,
  1164. LUA_SCRIPT_EXTENSIONS,
  1165. LUA_SERVER_PAGE_EXTENSIONS,
  1166. #endif
  1167. #if defined(USE_DUKTAPE)
  1168. DUKTAPE_SCRIPT_EXTENSIONS,
  1169. #endif
  1170. #if defined(USE_WEBSOCKET)
  1171. WEBSOCKET_ROOT,
  1172. #endif
  1173. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1174. LUA_WEBSOCKET_EXTENSIONS,
  1175. #endif
  1176. ACCESS_CONTROL_ALLOW_ORIGIN,
  1177. ERROR_PAGES,
  1178. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1179. * socket option typedef TCP_NODELAY. */
  1180. #if !defined(NO_CACHING)
  1181. STATIC_FILE_MAX_AGE,
  1182. #endif
  1183. #if defined(__linux__)
  1184. ALLOW_SENDFILE_CALL,
  1185. #endif
  1186. #if defined(_WIN32)
  1187. CASE_SENSITIVE_FILES,
  1188. #endif
  1189. NUM_OPTIONS
  1190. };
  1191. /* Config option name, config types, default value */
  1192. static struct mg_option config_options[] = {
  1193. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1194. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1195. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1196. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1197. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1198. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1199. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1200. {"throttle", CONFIG_TYPE_STRING, NULL},
  1201. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1202. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1203. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1204. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1205. {"index_files",
  1206. CONFIG_TYPE_STRING,
  1207. #ifdef USE_LUA
  1208. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1209. "index.shtml,index.php"},
  1210. #else
  1211. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1212. #endif
  1213. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1214. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1215. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1216. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1217. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1218. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1219. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1220. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1221. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1222. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1223. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1224. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1225. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1226. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1227. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1228. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1229. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1230. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1231. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1232. #if defined(USE_WEBSOCKET)
  1233. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1234. #endif
  1235. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1236. #if defined(USE_LUA)
  1237. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1238. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1239. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1240. #endif
  1241. #if defined(USE_DUKTAPE)
  1242. /* The support for duktape is still in alpha version state.
  1243. * The name of this config option might change. */
  1244. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1245. #endif
  1246. #if defined(USE_WEBSOCKET)
  1247. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1248. #endif
  1249. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1250. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1251. #endif
  1252. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1253. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1254. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1255. #if !defined(NO_CACHING)
  1256. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1257. #endif
  1258. #if defined(__linux__)
  1259. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1260. #endif
  1261. #if defined(_WIN32)
  1262. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1263. #endif
  1264. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1265. /* Check if the config_options and the corresponding enum have compatible
  1266. * sizes. */
  1267. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1268. == (NUM_OPTIONS + 1),
  1269. "config_options and enum not sync");
  1270. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1271. struct mg_handler_info {
  1272. /* Name/Pattern of the URI. */
  1273. char *uri;
  1274. size_t uri_len;
  1275. /* handler type */
  1276. int handler_type;
  1277. /* Handler for http/https or authorization requests. */
  1278. mg_request_handler handler;
  1279. /* Handler for ws/wss (websocket) requests. */
  1280. mg_websocket_connect_handler connect_handler;
  1281. mg_websocket_ready_handler ready_handler;
  1282. mg_websocket_data_handler data_handler;
  1283. mg_websocket_close_handler close_handler;
  1284. /* Handler for authorization requests */
  1285. mg_authorization_handler auth_handler;
  1286. /* User supplied argument for the handler function. */
  1287. void *cbdata;
  1288. /* next handler in a linked list */
  1289. struct mg_handler_info *next;
  1290. };
  1291. struct mg_context {
  1292. volatile int stop_flag; /* Should we stop event loop */
  1293. SSL_CTX *ssl_ctx; /* SSL context */
  1294. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1295. struct mg_callbacks callbacks; /* User-defined callback function */
  1296. void *user_data; /* User-defined data */
  1297. int context_type; /* 1 = server context,
  1298. * 2 = ws/wss client context,
  1299. */
  1300. struct socket *listening_sockets;
  1301. struct pollfd *listening_socket_fds;
  1302. unsigned int num_listening_sockets;
  1303. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1304. #ifdef ALTERNATIVE_QUEUE
  1305. struct socket *client_socks;
  1306. void **client_wait_events;
  1307. #else
  1308. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1309. volatile int sq_head; /* Head of the socket queue */
  1310. volatile int sq_tail; /* Tail of the socket queue */
  1311. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1312. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1313. #endif
  1314. pthread_t masterthreadid; /* The master thread ID */
  1315. unsigned int
  1316. cfg_worker_threads; /* The number of configured worker threads. */
  1317. pthread_t *workerthreadids; /* The worker thread IDs */
  1318. time_t start_time; /* Server start time, used for authentication */
  1319. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1320. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1321. unsigned long nonce_count; /* Used nonces, used for authentication */
  1322. char *systemName; /* What operating system is running */
  1323. /* linked list of uri handlers */
  1324. struct mg_handler_info *handlers;
  1325. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1326. /* linked list of shared lua websockets */
  1327. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1328. #endif
  1329. #ifdef USE_TIMERS
  1330. struct ttimers *timers;
  1331. #endif
  1332. };
  1333. struct mg_connection {
  1334. struct mg_request_info request_info;
  1335. struct mg_context *ctx;
  1336. SSL *ssl; /* SSL descriptor */
  1337. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1338. struct socket client; /* Connected client */
  1339. time_t conn_birth_time; /* Time (wall clock) when connection was
  1340. * established */
  1341. struct timespec req_time; /* Time (since system start) when the request
  1342. * was received */
  1343. int64_t num_bytes_sent; /* Total bytes sent to client */
  1344. int64_t content_len; /* Content-Length header value */
  1345. int64_t consumed_content; /* How many bytes of content have been read */
  1346. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1347. * data available, 2: all data read */
  1348. size_t chunk_remainder; /* Unread data from the last chunk */
  1349. char *buf; /* Buffer for received data */
  1350. char *path_info; /* PATH_INFO part of the URL */
  1351. int must_close; /* 1 if connection must be closed */
  1352. int in_error_handler; /* 1 if in handler for user defined error
  1353. * pages */
  1354. int internal_error; /* 1 if an error occured while processing the
  1355. * request */
  1356. int buf_size; /* Buffer size */
  1357. int request_len; /* Size of the request + headers in a buffer */
  1358. int data_len; /* Total size of data in a buffer */
  1359. int status_code; /* HTTP reply status code, e.g. 200 */
  1360. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1361. * throttle */
  1362. time_t last_throttle_time; /* Last time throttled data was sent */
  1363. int64_t last_throttle_bytes; /* Bytes sent this second */
  1364. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1365. * atomic transmissions for websockets */
  1366. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1367. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1368. #endif
  1369. int thread_index; /* Thread index within ctx */
  1370. };
  1371. static pthread_key_t sTlsKey; /* Thread local storage index */
  1372. static int sTlsInit = 0;
  1373. static int thread_idx_max = 0;
  1374. struct mg_workerTLS {
  1375. int is_master;
  1376. unsigned long thread_idx;
  1377. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1378. HANDLE pthread_cond_helper_mutex;
  1379. struct mg_workerTLS *next_waiting_thread;
  1380. #endif
  1381. };
  1382. /* Directory entry */
  1383. struct de {
  1384. struct mg_connection *conn;
  1385. char *file_name;
  1386. struct file file;
  1387. };
  1388. #if defined(USE_WEBSOCKET)
  1389. static int is_websocket_protocol(const struct mg_connection *conn);
  1390. #else
  1391. #define is_websocket_protocol(conn) (0)
  1392. #endif
  1393. static int
  1394. mg_atomic_inc(volatile int *addr)
  1395. {
  1396. int ret;
  1397. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1398. /* Depending on the SDK, this function uses either
  1399. * (volatile unsigned int *) or (volatile LONG *),
  1400. * so whatever you use, the other SDK is likely to raise a warning. */
  1401. ret = InterlockedIncrement((volatile long *)addr);
  1402. #elif defined(__GNUC__) \
  1403. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1404. ret = __sync_add_and_fetch(addr, 1);
  1405. #else
  1406. ret = (++(*addr));
  1407. #endif
  1408. return ret;
  1409. }
  1410. static int
  1411. mg_atomic_dec(volatile int *addr)
  1412. {
  1413. int ret;
  1414. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1415. /* Depending on the SDK, this function uses either
  1416. * (volatile unsigned int *) or (volatile LONG *),
  1417. * so whatever you use, the other SDK is likely to raise a warning. */
  1418. ret = InterlockedDecrement((volatile long *)addr);
  1419. #elif defined(__GNUC__) \
  1420. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1421. ret = __sync_sub_and_fetch(addr, 1);
  1422. #else
  1423. ret = (--(*addr));
  1424. #endif
  1425. return ret;
  1426. }
  1427. #if !defined(NO_THREAD_NAME)
  1428. #if defined(_WIN32) && defined(_MSC_VER)
  1429. /* Set the thread name for debugging purposes in Visual Studio
  1430. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1431. */
  1432. #pragma pack(push, 8)
  1433. typedef struct tagTHREADNAME_INFO {
  1434. DWORD dwType; /* Must be 0x1000. */
  1435. LPCSTR szName; /* Pointer to name (in user addr space). */
  1436. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1437. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1438. } THREADNAME_INFO;
  1439. #pragma pack(pop)
  1440. #elif defined(__linux__)
  1441. #include <sys/prctl.h>
  1442. #include <sys/sendfile.h>
  1443. #include <sys/eventfd.h>
  1444. #if defined(ALTERNATIVE_QUEUE)
  1445. static void *
  1446. event_create(void)
  1447. {
  1448. int ret = eventfd(0, EFD_CLOEXEC);
  1449. if (ret == -1) {
  1450. /* Linux uses -1 on error, Windows NULL. */
  1451. /* However, Linux does not return 0 on success either. */
  1452. return 0;
  1453. }
  1454. return (void *)ret;
  1455. }
  1456. static int
  1457. event_wait(void *eventhdl)
  1458. {
  1459. uint64_t u;
  1460. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1461. if (s != sizeof(uint64_t)) {
  1462. /* error */
  1463. return 0;
  1464. }
  1465. (void)u; /* the value is not required */
  1466. return 1;
  1467. }
  1468. static int
  1469. event_signal(void *eventhdl)
  1470. {
  1471. uint64_t u = 1;
  1472. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1473. if (s != sizeof(uint64_t)) {
  1474. /* error */
  1475. return 0;
  1476. }
  1477. return 1;
  1478. }
  1479. static void
  1480. event_destroy(void *eventhdl)
  1481. {
  1482. close((int)eventhdl);
  1483. }
  1484. #endif
  1485. #endif
  1486. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1487. struct posix_event {
  1488. pthread_mutex_t mutex;
  1489. pthread_cond_t cond;
  1490. };
  1491. static void *
  1492. event_create(void)
  1493. {
  1494. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1495. if (ret == 0) {
  1496. /* out of memory */
  1497. return 0;
  1498. }
  1499. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1500. /* pthread mutex not available */
  1501. mg_free(ret);
  1502. return 0;
  1503. }
  1504. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1505. /* pthread cond not available */
  1506. pthread_mutex_destroy(&(ret->mutex));
  1507. mg_free(ret);
  1508. return 0;
  1509. }
  1510. return (void *)ret;
  1511. }
  1512. static int
  1513. event_wait(void *eventhdl)
  1514. {
  1515. struct posix_event *ev = (struct posix_event *)eventhdl;
  1516. pthread_mutex_lock(&(ev->mutex));
  1517. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1518. pthread_mutex_unlock(&(ev->mutex));
  1519. return 1;
  1520. }
  1521. static int
  1522. event_signal(void *eventhdl)
  1523. {
  1524. struct posix_event *ev = (struct posix_event *)eventhdl;
  1525. pthread_mutex_lock(&(ev->mutex));
  1526. pthread_cond_signal(&(ev->cond));
  1527. pthread_mutex_unlock(&(ev->mutex));
  1528. return 1;
  1529. }
  1530. static void
  1531. event_destroy(void *eventhdl)
  1532. {
  1533. struct posix_event *ev = (struct posix_event *)eventhdl;
  1534. pthread_cond_destroy(&(ev->cond));
  1535. pthread_mutex_destroy(&(ev->mutex));
  1536. mg_free(ev);
  1537. }
  1538. #endif
  1539. static void
  1540. mg_set_thread_name(const char *name)
  1541. {
  1542. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1543. mg_snprintf(
  1544. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1545. #if defined(_WIN32)
  1546. #if defined(_MSC_VER)
  1547. /* Windows and Visual Studio Compiler */
  1548. __try
  1549. {
  1550. THREADNAME_INFO info;
  1551. info.dwType = 0x1000;
  1552. info.szName = threadName;
  1553. info.dwThreadID = ~0U;
  1554. info.dwFlags = 0;
  1555. RaiseException(0x406D1388,
  1556. 0,
  1557. sizeof(info) / sizeof(ULONG_PTR),
  1558. (ULONG_PTR *)&info);
  1559. }
  1560. __except(EXCEPTION_EXECUTE_HANDLER)
  1561. {
  1562. }
  1563. #elif defined(__MINGW32__)
  1564. /* No option known to set thread name for MinGW */
  1565. #endif
  1566. #elif defined(__GLIBC__) \
  1567. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1568. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1569. (void)pthread_setname_np(pthread_self(), threadName);
  1570. #elif defined(__linux__)
  1571. /* on linux we can use the old prctl function */
  1572. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1573. #endif
  1574. }
  1575. #else /* !defined(NO_THREAD_NAME) */
  1576. void
  1577. mg_set_thread_name(const char *threadName)
  1578. {
  1579. }
  1580. #endif
  1581. #if defined(MG_LEGACY_INTERFACE)
  1582. const char **
  1583. mg_get_valid_option_names(void)
  1584. {
  1585. /* This function is deprecated. Use mg_get_valid_options instead. */
  1586. static const char *
  1587. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1588. int i;
  1589. for (i = 0; config_options[i].name != NULL; i++) {
  1590. data[i * 2] = config_options[i].name;
  1591. data[i * 2 + 1] = config_options[i].default_value;
  1592. }
  1593. return data;
  1594. }
  1595. #endif
  1596. const struct mg_option *
  1597. mg_get_valid_options(void)
  1598. {
  1599. return config_options;
  1600. }
  1601. static int
  1602. is_file_in_memory(const struct mg_connection *conn,
  1603. const char *path,
  1604. struct file *filep)
  1605. {
  1606. size_t size = 0;
  1607. if (!conn || !filep) {
  1608. return 0;
  1609. }
  1610. if (conn->ctx->callbacks.open_file) {
  1611. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1612. if (filep->membuf != NULL) {
  1613. /* NOTE: override filep->size only on success. Otherwise, it might
  1614. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1615. filep->size = size;
  1616. }
  1617. }
  1618. return filep->membuf != NULL;
  1619. }
  1620. static int
  1621. is_file_opened(const struct file *filep)
  1622. {
  1623. if (!filep) {
  1624. return 0;
  1625. }
  1626. return filep->membuf != NULL || filep->fp != NULL;
  1627. }
  1628. /* mg_fopen will open a file either in memory or on the disk.
  1629. * The input parameter path is a string in UTF-8 encoding.
  1630. * The input parameter mode is the same as for fopen.
  1631. * Either fp or membuf will be set in the output struct filep.
  1632. * The function returns 1 on success, 0 on error. */
  1633. static int
  1634. mg_fopen(const struct mg_connection *conn,
  1635. const char *path,
  1636. const char *mode,
  1637. struct file *filep)
  1638. {
  1639. struct stat st;
  1640. if (!filep) {
  1641. return 0;
  1642. }
  1643. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1644. * only get the file status. They should not work on different members of
  1645. * the same structure (bad cohesion). */
  1646. memset(filep, 0, sizeof(*filep));
  1647. if (stat(path, &st) == 0) {
  1648. filep->size = (uint64_t)(st.st_size);
  1649. }
  1650. if (!is_file_in_memory(conn, path, filep)) {
  1651. #ifdef _WIN32
  1652. wchar_t wbuf[PATH_MAX], wmode[20];
  1653. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1654. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1655. filep->fp = _wfopen(wbuf, wmode);
  1656. #else
  1657. /* Linux et al already use unicode. No need to convert. */
  1658. filep->fp = fopen(path, mode);
  1659. #endif
  1660. }
  1661. return is_file_opened(filep);
  1662. }
  1663. static void
  1664. mg_fclose(struct file *filep)
  1665. {
  1666. if (filep != NULL && filep->fp != NULL) {
  1667. fclose(filep->fp);
  1668. }
  1669. }
  1670. static void
  1671. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1672. {
  1673. for (; *src != '\0' && n > 1; n--) {
  1674. *dst++ = *src++;
  1675. }
  1676. *dst = '\0';
  1677. }
  1678. static int
  1679. lowercase(const char *s)
  1680. {
  1681. return tolower(*(const unsigned char *)s);
  1682. }
  1683. int
  1684. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1685. {
  1686. int diff = 0;
  1687. if (len > 0) {
  1688. do {
  1689. diff = lowercase(s1++) - lowercase(s2++);
  1690. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1691. }
  1692. return diff;
  1693. }
  1694. int
  1695. mg_strcasecmp(const char *s1, const char *s2)
  1696. {
  1697. int diff;
  1698. do {
  1699. diff = lowercase(s1++) - lowercase(s2++);
  1700. } while (diff == 0 && s1[-1] != '\0');
  1701. return diff;
  1702. }
  1703. static char *
  1704. mg_strndup(const char *ptr, size_t len)
  1705. {
  1706. char *p;
  1707. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1708. mg_strlcpy(p, ptr, len + 1);
  1709. }
  1710. return p;
  1711. }
  1712. static char *
  1713. mg_strdup(const char *str)
  1714. {
  1715. return mg_strndup(str, strlen(str));
  1716. }
  1717. static const char *
  1718. mg_strcasestr(const char *big_str, const char *small_str)
  1719. {
  1720. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1721. if (big_len >= small_len) {
  1722. for (i = 0; i <= (big_len - small_len); i++) {
  1723. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1724. return big_str + i;
  1725. }
  1726. }
  1727. }
  1728. return NULL;
  1729. }
  1730. /* Return null terminated string of given maximum length.
  1731. * Report errors if length is exceeded. */
  1732. static void
  1733. mg_vsnprintf(const struct mg_connection *conn,
  1734. int *truncated,
  1735. char *buf,
  1736. size_t buflen,
  1737. const char *fmt,
  1738. va_list ap)
  1739. {
  1740. int n, ok;
  1741. if (buflen == 0) {
  1742. return;
  1743. }
  1744. #ifdef __clang__
  1745. #pragma clang diagnostic push
  1746. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1747. /* Using fmt as a non-literal is intended here, since it is mostly called
  1748. * indirectly by mg_snprintf */
  1749. #endif
  1750. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1751. ok = (n >= 0) && ((size_t)n < buflen);
  1752. #ifdef __clang__
  1753. #pragma clang diagnostic pop
  1754. #endif
  1755. if (ok) {
  1756. if (truncated) {
  1757. *truncated = 0;
  1758. }
  1759. } else {
  1760. if (truncated) {
  1761. *truncated = 1;
  1762. }
  1763. mg_cry(conn,
  1764. "truncating vsnprintf buffer: [%.*s]",
  1765. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1766. buf);
  1767. n = (int)buflen - 1;
  1768. }
  1769. buf[n] = '\0';
  1770. }
  1771. static void
  1772. mg_snprintf(const struct mg_connection *conn,
  1773. int *truncated,
  1774. char *buf,
  1775. size_t buflen,
  1776. const char *fmt,
  1777. ...)
  1778. {
  1779. va_list ap;
  1780. va_start(ap, fmt);
  1781. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1782. va_end(ap);
  1783. }
  1784. static int
  1785. get_option_index(const char *name)
  1786. {
  1787. int i;
  1788. for (i = 0; config_options[i].name != NULL; i++) {
  1789. if (strcmp(config_options[i].name, name) == 0) {
  1790. return i;
  1791. }
  1792. }
  1793. return -1;
  1794. }
  1795. const char *
  1796. mg_get_option(const struct mg_context *ctx, const char *name)
  1797. {
  1798. int i;
  1799. if ((i = get_option_index(name)) == -1) {
  1800. return NULL;
  1801. } else if (!ctx || ctx->config[i] == NULL) {
  1802. return "";
  1803. } else {
  1804. return ctx->config[i];
  1805. }
  1806. }
  1807. struct mg_context *
  1808. mg_get_context(const struct mg_connection *conn)
  1809. {
  1810. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1811. }
  1812. void *
  1813. mg_get_user_data(const struct mg_context *ctx)
  1814. {
  1815. return (ctx == NULL) ? NULL : ctx->user_data;
  1816. }
  1817. void
  1818. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1819. {
  1820. if (conn != NULL) {
  1821. conn->request_info.conn_data = data;
  1822. }
  1823. }
  1824. void *
  1825. mg_get_user_connection_data(const struct mg_connection *conn)
  1826. {
  1827. if (conn != NULL) {
  1828. return conn->request_info.conn_data;
  1829. }
  1830. return NULL;
  1831. }
  1832. size_t
  1833. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1834. {
  1835. size_t i;
  1836. if (!ctx) {
  1837. return 0;
  1838. }
  1839. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1840. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1841. ports[i] =
  1842. #if defined(USE_IPV6)
  1843. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1844. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1845. :
  1846. #endif
  1847. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1848. }
  1849. return i;
  1850. }
  1851. int
  1852. mg_get_server_ports(const struct mg_context *ctx,
  1853. int size,
  1854. struct mg_server_ports *ports)
  1855. {
  1856. int i, cnt = 0;
  1857. if (size <= 0) {
  1858. return -1;
  1859. }
  1860. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1861. if (!ctx) {
  1862. return -1;
  1863. }
  1864. if (!ctx->listening_sockets) {
  1865. return -1;
  1866. }
  1867. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1868. ports[cnt].port =
  1869. #if defined(USE_IPV6)
  1870. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1871. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1872. :
  1873. #endif
  1874. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1875. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1876. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1877. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1878. /* IPv4 */
  1879. ports[cnt].protocol = 1;
  1880. cnt++;
  1881. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1882. /* IPv6 */
  1883. ports[cnt].protocol = 3;
  1884. cnt++;
  1885. }
  1886. }
  1887. return cnt;
  1888. }
  1889. static void
  1890. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1891. {
  1892. buf[0] = '\0';
  1893. if (!usa) {
  1894. return;
  1895. }
  1896. if (usa->sa.sa_family == AF_INET) {
  1897. getnameinfo(&usa->sa,
  1898. sizeof(usa->sin),
  1899. buf,
  1900. (unsigned)len,
  1901. NULL,
  1902. 0,
  1903. NI_NUMERICHOST);
  1904. }
  1905. #if defined(USE_IPV6)
  1906. else if (usa->sa.sa_family == AF_INET6) {
  1907. getnameinfo(&usa->sa,
  1908. sizeof(usa->sin6),
  1909. buf,
  1910. (unsigned)len,
  1911. NULL,
  1912. 0,
  1913. NI_NUMERICHOST);
  1914. }
  1915. #endif
  1916. }
  1917. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1918. * included in all responses other than 100, 101, 5xx. */
  1919. static void
  1920. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1921. {
  1922. struct tm *tm;
  1923. tm = ((t != NULL) ? gmtime(t) : NULL);
  1924. if (tm != NULL) {
  1925. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1926. } else {
  1927. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1928. buf[buf_len - 1] = '\0';
  1929. }
  1930. }
  1931. /* difftime for struct timespec. Return value is in seconds. */
  1932. static double
  1933. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1934. {
  1935. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1936. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1937. }
  1938. /* Print error message to the opened error log stream. */
  1939. void
  1940. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1941. {
  1942. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1943. va_list ap;
  1944. struct file fi;
  1945. time_t timestamp;
  1946. va_start(ap, fmt);
  1947. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1948. va_end(ap);
  1949. buf[sizeof(buf) - 1] = 0;
  1950. if (!conn) {
  1951. puts(buf);
  1952. return;
  1953. }
  1954. /* Do not lock when getting the callback value, here and below.
  1955. * I suppose this is fine, since function cannot disappear in the
  1956. * same way string option can. */
  1957. if ((conn->ctx->callbacks.log_message == NULL)
  1958. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1959. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1960. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1961. == 0) {
  1962. fi.fp = NULL;
  1963. }
  1964. } else {
  1965. fi.fp = NULL;
  1966. }
  1967. if (fi.fp != NULL) {
  1968. flockfile(fi.fp);
  1969. timestamp = time(NULL);
  1970. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1971. fprintf(fi.fp,
  1972. "[%010lu] [error] [client %s] ",
  1973. (unsigned long)timestamp,
  1974. src_addr);
  1975. if (conn->request_info.request_method != NULL) {
  1976. fprintf(fi.fp,
  1977. "%s %s: ",
  1978. conn->request_info.request_method,
  1979. conn->request_info.request_uri);
  1980. }
  1981. fprintf(fi.fp, "%s", buf);
  1982. fputc('\n', fi.fp);
  1983. fflush(fi.fp);
  1984. funlockfile(fi.fp);
  1985. mg_fclose(&fi);
  1986. }
  1987. }
  1988. }
  1989. /* Return fake connection structure. Used for logging, if connection
  1990. * is not applicable at the moment of logging. */
  1991. static struct mg_connection *
  1992. fc(struct mg_context *ctx)
  1993. {
  1994. static struct mg_connection fake_connection;
  1995. fake_connection.ctx = ctx;
  1996. return &fake_connection;
  1997. }
  1998. const char *
  1999. mg_version(void)
  2000. {
  2001. return CIVETWEB_VERSION;
  2002. }
  2003. const struct mg_request_info *
  2004. mg_get_request_info(const struct mg_connection *conn)
  2005. {
  2006. if (!conn) {
  2007. return NULL;
  2008. }
  2009. return &conn->request_info;
  2010. }
  2011. /* Skip the characters until one of the delimiters characters found.
  2012. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2013. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2014. * Delimiters can be quoted with quotechar. */
  2015. static char *
  2016. skip_quoted(char **buf,
  2017. const char *delimiters,
  2018. const char *whitespace,
  2019. char quotechar)
  2020. {
  2021. char *p, *begin_word, *end_word, *end_whitespace;
  2022. begin_word = *buf;
  2023. end_word = begin_word + strcspn(begin_word, delimiters);
  2024. /* Check for quotechar */
  2025. if (end_word > begin_word) {
  2026. p = end_word - 1;
  2027. while (*p == quotechar) {
  2028. /* While the delimiter is quoted, look for the next delimiter. */
  2029. /* This happens, e.g., in calls from parse_auth_header,
  2030. * if the user name contains a " character. */
  2031. /* If there is anything beyond end_word, copy it. */
  2032. if (*end_word != '\0') {
  2033. size_t end_off = strcspn(end_word + 1, delimiters);
  2034. memmove(p, end_word, end_off + 1);
  2035. p += end_off; /* p must correspond to end_word - 1 */
  2036. end_word += end_off + 1;
  2037. } else {
  2038. *p = '\0';
  2039. break;
  2040. }
  2041. }
  2042. for (p++; p < end_word; p++) {
  2043. *p = '\0';
  2044. }
  2045. }
  2046. if (*end_word == '\0') {
  2047. *buf = end_word;
  2048. } else {
  2049. #if defined(__GNUC__) || defined(__MINGW32__)
  2050. /* Disable spurious conversion warning for GCC */
  2051. #pragma GCC diagnostic push
  2052. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2053. #endif
  2054. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2055. #if defined(__GNUC__) || defined(__MINGW32__)
  2056. #pragma GCC diagnostic pop
  2057. #endif
  2058. for (p = end_word; p < end_whitespace; p++) {
  2059. *p = '\0';
  2060. }
  2061. *buf = end_whitespace;
  2062. }
  2063. return begin_word;
  2064. }
  2065. /* Simplified version of skip_quoted without quote char
  2066. * and whitespace == delimiters */
  2067. static char *
  2068. skip(char **buf, const char *delimiters)
  2069. {
  2070. return skip_quoted(buf, delimiters, delimiters, 0);
  2071. }
  2072. /* Return HTTP header value, or NULL if not found. */
  2073. static const char *
  2074. get_header(const struct mg_request_info *ri, const char *name)
  2075. {
  2076. int i;
  2077. if (ri) {
  2078. for (i = 0; i < ri->num_headers; i++) {
  2079. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2080. return ri->http_headers[i].value;
  2081. }
  2082. }
  2083. }
  2084. return NULL;
  2085. }
  2086. const char *
  2087. mg_get_header(const struct mg_connection *conn, const char *name)
  2088. {
  2089. if (!conn) {
  2090. return NULL;
  2091. }
  2092. return get_header(&conn->request_info, name);
  2093. }
  2094. /* A helper function for traversing a comma separated list of values.
  2095. * It returns a list pointer shifted to the next value, or NULL if the end
  2096. * of the list found.
  2097. * Value is stored in val vector. If value has form "x=y", then eq_val
  2098. * vector is initialized to point to the "y" part, and val vector length
  2099. * is adjusted to point only to "x". */
  2100. static const char *
  2101. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2102. {
  2103. int end;
  2104. reparse:
  2105. if (val == NULL || list == NULL || *list == '\0') {
  2106. /* End of the list */
  2107. list = NULL;
  2108. } else {
  2109. /* Skip over leading LWS */
  2110. while (*list == ' ' || *list == '\t')
  2111. list++;
  2112. val->ptr = list;
  2113. if ((list = strchr(val->ptr, ',')) != NULL) {
  2114. /* Comma found. Store length and shift the list ptr */
  2115. val->len = ((size_t)(list - val->ptr));
  2116. list++;
  2117. } else {
  2118. /* This value is the last one */
  2119. list = val->ptr + strlen(val->ptr);
  2120. val->len = ((size_t)(list - val->ptr));
  2121. }
  2122. /* Adjust length for trailing LWS */
  2123. end = (int)val->len - 1;
  2124. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2125. end--;
  2126. val->len = (size_t)(end + 1);
  2127. if (val->len == 0) {
  2128. /* Ignore any empty entries. */
  2129. goto reparse;
  2130. }
  2131. if (eq_val != NULL) {
  2132. /* Value has form "x=y", adjust pointers and lengths
  2133. * so that val points to "x", and eq_val points to "y". */
  2134. eq_val->len = 0;
  2135. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2136. if (eq_val->ptr != NULL) {
  2137. eq_val->ptr++; /* Skip over '=' character */
  2138. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2139. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2140. }
  2141. }
  2142. }
  2143. return list;
  2144. }
  2145. /* A helper function for checking if a comma separated list of values contains
  2146. * the given option (case insensitvely).
  2147. * 'header' can be NULL, in which case false is returned. */
  2148. static int
  2149. header_has_option(const char *header, const char *option)
  2150. {
  2151. struct vec opt_vec;
  2152. struct vec eq_vec;
  2153. assert(option != NULL);
  2154. assert(option[0] != '\0');
  2155. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2156. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2157. return 1;
  2158. }
  2159. return 0;
  2160. }
  2161. /* Perform case-insensitive match of string against pattern */
  2162. static int
  2163. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2164. {
  2165. const char *or_str;
  2166. size_t i;
  2167. int j, len, res;
  2168. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2169. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2170. return (res > 0) ? res : match_prefix(or_str + 1,
  2171. (size_t)((pattern + pattern_len)
  2172. - (or_str + 1)),
  2173. str);
  2174. }
  2175. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2176. if (pattern[i] == '?' && str[j] != '\0') {
  2177. continue;
  2178. } else if (pattern[i] == '$') {
  2179. return (str[j] == '\0') ? j : -1;
  2180. } else if (pattern[i] == '*') {
  2181. i++;
  2182. if (pattern[i] == '*') {
  2183. i++;
  2184. len = (int)strlen(str + j);
  2185. } else {
  2186. len = (int)strcspn(str + j, "/");
  2187. }
  2188. if (i == pattern_len) {
  2189. return j + len;
  2190. }
  2191. do {
  2192. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2193. } while (res == -1 && len-- > 0);
  2194. return (res == -1) ? -1 : j + res + len;
  2195. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2196. return -1;
  2197. }
  2198. }
  2199. return j;
  2200. }
  2201. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2202. * This function must tolerate situations when connection info is not
  2203. * set up, for example if request parsing failed. */
  2204. static int
  2205. should_keep_alive(const struct mg_connection *conn)
  2206. {
  2207. if (conn != NULL) {
  2208. const char *http_version = conn->request_info.http_version;
  2209. const char *header = mg_get_header(conn, "Connection");
  2210. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2211. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2212. || (header != NULL && !header_has_option(header, "keep-alive"))
  2213. || (header == NULL && http_version
  2214. && 0 != strcmp(http_version, "1.1"))) {
  2215. return 0;
  2216. }
  2217. return 1;
  2218. }
  2219. return 0;
  2220. }
  2221. static int
  2222. should_decode_url(const struct mg_connection *conn)
  2223. {
  2224. if (!conn || !conn->ctx) {
  2225. return 0;
  2226. }
  2227. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2228. }
  2229. static const char *
  2230. suggest_connection_header(const struct mg_connection *conn)
  2231. {
  2232. return should_keep_alive(conn) ? "keep-alive" : "close";
  2233. }
  2234. static int
  2235. send_no_cache_header(struct mg_connection *conn)
  2236. {
  2237. /* Send all current and obsolete cache opt-out directives. */
  2238. return mg_printf(conn,
  2239. "Cache-Control: no-cache, no-store, "
  2240. "must-revalidate, private, max-age=0\r\n"
  2241. "Pragma: no-cache\r\n"
  2242. "Expires: 0\r\n");
  2243. }
  2244. static int
  2245. send_static_cache_header(struct mg_connection *conn)
  2246. {
  2247. #if !defined(NO_CACHING)
  2248. /* Read the server config to check how long a file may be cached.
  2249. * The configuration is in seconds. */
  2250. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2251. if (max_age <= 0) {
  2252. /* 0 means "do not cache". All values <0 are reserved
  2253. * and may be used differently in the future. */
  2254. /* If a file should not be cached, do not only send
  2255. * max-age=0, but also pragmas and Expires headers. */
  2256. return send_no_cache_header(conn);
  2257. }
  2258. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2259. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2260. /* See also https://www.mnot.net/cache_docs/ */
  2261. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2262. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2263. * year to 31622400 seconds. For the moment, we just send whatever has
  2264. * been configured, still the behavior for >1 year should be considered
  2265. * as undefined. */
  2266. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2267. #else /* NO_CACHING */
  2268. return send_no_cache_header(conn);
  2269. #endif /* !NO_CACHING */
  2270. }
  2271. static void handle_file_based_request(struct mg_connection *conn,
  2272. const char *path,
  2273. struct file *filep);
  2274. static int
  2275. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2276. const char *
  2277. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2278. {
  2279. /* See IANA HTTP status code assignment:
  2280. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2281. */
  2282. switch (response_code) {
  2283. /* RFC2616 Section 10.1 - Informational 1xx */
  2284. case 100:
  2285. return "Continue"; /* RFC2616 Section 10.1.1 */
  2286. case 101:
  2287. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2288. case 102:
  2289. return "Processing"; /* RFC2518 Section 10.1 */
  2290. /* RFC2616 Section 10.2 - Successful 2xx */
  2291. case 200:
  2292. return "OK"; /* RFC2616 Section 10.2.1 */
  2293. case 201:
  2294. return "Created"; /* RFC2616 Section 10.2.2 */
  2295. case 202:
  2296. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2297. case 203:
  2298. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2299. case 204:
  2300. return "No Content"; /* RFC2616 Section 10.2.5 */
  2301. case 205:
  2302. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2303. case 206:
  2304. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2305. case 207:
  2306. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2307. case 208:
  2308. return "Already Reported"; /* RFC5842 Section 7.1 */
  2309. case 226:
  2310. return "IM used"; /* RFC3229 Section 10.4.1 */
  2311. /* RFC2616 Section 10.3 - Redirection 3xx */
  2312. case 300:
  2313. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2314. case 301:
  2315. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2316. case 302:
  2317. return "Found"; /* RFC2616 Section 10.3.3 */
  2318. case 303:
  2319. return "See Other"; /* RFC2616 Section 10.3.4 */
  2320. case 304:
  2321. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2322. case 305:
  2323. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2324. case 307:
  2325. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2326. case 308:
  2327. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2328. /* RFC2616 Section 10.4 - Client Error 4xx */
  2329. case 400:
  2330. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2331. case 401:
  2332. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2333. case 402:
  2334. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2335. case 403:
  2336. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2337. case 404:
  2338. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2339. case 405:
  2340. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2341. case 406:
  2342. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2343. case 407:
  2344. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2345. case 408:
  2346. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2347. case 409:
  2348. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2349. case 410:
  2350. return "Gone"; /* RFC2616 Section 10.4.11 */
  2351. case 411:
  2352. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2353. case 412:
  2354. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2355. case 413:
  2356. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2357. case 414:
  2358. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2359. case 415:
  2360. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2361. case 416:
  2362. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2363. case 417:
  2364. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2365. case 421:
  2366. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2367. case 422:
  2368. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2369. * Section 11.2 */
  2370. case 423:
  2371. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2372. case 424:
  2373. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2374. * Section 11.4 */
  2375. case 426:
  2376. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2377. case 428:
  2378. return "Precondition Required"; /* RFC 6585, Section 3 */
  2379. case 429:
  2380. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2381. case 431:
  2382. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2383. case 451:
  2384. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2385. * Section 3 */
  2386. /* RFC2616 Section 10.5 - Server Error 5xx */
  2387. case 500:
  2388. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2389. case 501:
  2390. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2391. case 502:
  2392. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2393. case 503:
  2394. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2395. case 504:
  2396. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2397. case 505:
  2398. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2399. case 506:
  2400. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2401. case 507:
  2402. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2403. * Section 11.5 */
  2404. case 508:
  2405. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2406. case 510:
  2407. return "Not Extended"; /* RFC 2774, Section 7 */
  2408. case 511:
  2409. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2410. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2411. * E.g., "de facto" standards due to common use, ... */
  2412. case 418:
  2413. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2414. case 419:
  2415. return "Authentication Timeout"; /* common use */
  2416. case 420:
  2417. return "Enhance Your Calm"; /* common use */
  2418. case 440:
  2419. return "Login Timeout"; /* common use */
  2420. case 509:
  2421. return "Bandwidth Limit Exceeded"; /* common use */
  2422. default:
  2423. /* This error code is unknown. This should not happen. */
  2424. if (conn) {
  2425. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2426. }
  2427. /* Return at least a category according to RFC 2616 Section 10. */
  2428. if (response_code >= 100 && response_code < 200) {
  2429. /* Unknown informational status code */
  2430. return "Information";
  2431. }
  2432. if (response_code >= 200 && response_code < 300) {
  2433. /* Unknown success code */
  2434. return "Success";
  2435. }
  2436. if (response_code >= 300 && response_code < 400) {
  2437. /* Unknown redirection code */
  2438. return "Redirection";
  2439. }
  2440. if (response_code >= 400 && response_code < 500) {
  2441. /* Unknown request error code */
  2442. return "Client Error";
  2443. }
  2444. if (response_code >= 500 && response_code < 600) {
  2445. /* Unknown server error code */
  2446. return "Server Error";
  2447. }
  2448. /* Response code not even within reasonable range */
  2449. return "";
  2450. }
  2451. }
  2452. static void send_http_error(struct mg_connection *,
  2453. int,
  2454. PRINTF_FORMAT_STRING(const char *fmt),
  2455. ...) PRINTF_ARGS(3, 4);
  2456. static void
  2457. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2458. {
  2459. char buf[MG_BUF_LEN];
  2460. va_list ap;
  2461. int len, i, page_handler_found, scope, truncated, has_body;
  2462. char date[64];
  2463. time_t curtime = time(NULL);
  2464. const char *error_handler = NULL;
  2465. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2466. const char *error_page_file_ext, *tstr;
  2467. const char *status_text = mg_get_response_code_text(conn, status);
  2468. if (conn == NULL) {
  2469. return;
  2470. }
  2471. conn->status_code = status;
  2472. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2473. || conn->ctx->callbacks.http_error(conn, status)) {
  2474. if (!conn->in_error_handler) {
  2475. /* Send user defined error pages, if defined */
  2476. error_handler = conn->ctx->config[ERROR_PAGES];
  2477. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2478. page_handler_found = 0;
  2479. if (error_handler != NULL) {
  2480. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2481. switch (scope) {
  2482. case 1: /* Handler for specific error, e.g. 404 error */
  2483. mg_snprintf(conn,
  2484. &truncated,
  2485. buf,
  2486. sizeof(buf) - 32,
  2487. "%serror%03u.",
  2488. error_handler,
  2489. status);
  2490. break;
  2491. case 2: /* Handler for error group, e.g., 5xx error handler
  2492. * for all server errors (500-599) */
  2493. mg_snprintf(conn,
  2494. &truncated,
  2495. buf,
  2496. sizeof(buf) - 32,
  2497. "%serror%01uxx.",
  2498. error_handler,
  2499. status / 100);
  2500. break;
  2501. default: /* Handler for all errors */
  2502. mg_snprintf(conn,
  2503. &truncated,
  2504. buf,
  2505. sizeof(buf) - 32,
  2506. "%serror.",
  2507. error_handler);
  2508. break;
  2509. }
  2510. /* String truncation in buf may only occur if error_handler
  2511. * is too long. This string is from the config, not from a
  2512. * client. */
  2513. (void)truncated;
  2514. len = (int)strlen(buf);
  2515. tstr = strchr(error_page_file_ext, '.');
  2516. while (tstr) {
  2517. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2518. i++)
  2519. buf[len + i - 1] = tstr[i];
  2520. buf[len + i - 1] = 0;
  2521. if (mg_stat(conn, buf, &error_page_file)) {
  2522. page_handler_found = 1;
  2523. break;
  2524. }
  2525. tstr = strchr(tstr + i, '.');
  2526. }
  2527. }
  2528. }
  2529. if (page_handler_found) {
  2530. conn->in_error_handler = 1;
  2531. handle_file_based_request(conn, buf, &error_page_file);
  2532. conn->in_error_handler = 0;
  2533. return;
  2534. }
  2535. }
  2536. /* No custom error page. Send default error page. */
  2537. gmt_time_string(date, sizeof(date), &curtime);
  2538. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2539. has_body = (status > 199 && status != 204 && status != 304);
  2540. conn->must_close = 1;
  2541. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2542. send_no_cache_header(conn);
  2543. if (has_body) {
  2544. mg_printf(conn,
  2545. "%s",
  2546. "Content-Type: text/plain; charset=utf-8\r\n");
  2547. }
  2548. mg_printf(conn,
  2549. "Date: %s\r\n"
  2550. "Connection: close\r\n\r\n",
  2551. date);
  2552. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2553. if (has_body) {
  2554. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2555. if (fmt != NULL) {
  2556. va_start(ap, fmt);
  2557. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2558. va_end(ap);
  2559. mg_write(conn, buf, strlen(buf));
  2560. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2561. }
  2562. } else {
  2563. /* No body allowed. Close the connection. */
  2564. DEBUG_TRACE("Error %i", status);
  2565. }
  2566. }
  2567. }
  2568. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2569. /* Create substitutes for POSIX functions in Win32. */
  2570. #if defined(__MINGW32__)
  2571. /* Show no warning in case system functions are not used. */
  2572. #pragma GCC diagnostic push
  2573. #pragma GCC diagnostic ignored "-Wunused-function"
  2574. #endif
  2575. static int
  2576. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2577. {
  2578. (void)unused;
  2579. *mutex = CreateMutex(NULL, FALSE, NULL);
  2580. return (*mutex == NULL) ? -1 : 0;
  2581. }
  2582. static int
  2583. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2584. {
  2585. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2586. }
  2587. static int
  2588. pthread_mutex_lock(pthread_mutex_t *mutex)
  2589. {
  2590. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2591. }
  2592. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2593. static int
  2594. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2595. {
  2596. switch (WaitForSingleObject(*mutex, 0)) {
  2597. case WAIT_OBJECT_0:
  2598. return 0;
  2599. case WAIT_TIMEOUT:
  2600. return -2; /* EBUSY */
  2601. }
  2602. return -1;
  2603. }
  2604. #endif
  2605. static int
  2606. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2607. {
  2608. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2609. }
  2610. #ifndef WIN_PTHREADS_TIME_H
  2611. static int
  2612. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2613. {
  2614. FILETIME ft;
  2615. ULARGE_INTEGER li;
  2616. BOOL ok = FALSE;
  2617. double d;
  2618. static double perfcnt_per_sec = 0.0;
  2619. if (tp) {
  2620. memset(tp, 0, sizeof(*tp));
  2621. if (clk_id == CLOCK_REALTIME) {
  2622. GetSystemTimeAsFileTime(&ft);
  2623. li.LowPart = ft.dwLowDateTime;
  2624. li.HighPart = ft.dwHighDateTime;
  2625. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2626. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2627. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2628. ok = TRUE;
  2629. } else if (clk_id == CLOCK_MONOTONIC) {
  2630. if (perfcnt_per_sec == 0.0) {
  2631. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2632. perfcnt_per_sec = 1.0 / li.QuadPart;
  2633. }
  2634. if (perfcnt_per_sec != 0.0) {
  2635. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2636. d = li.QuadPart * perfcnt_per_sec;
  2637. tp->tv_sec = (time_t)d;
  2638. d -= tp->tv_sec;
  2639. tp->tv_nsec = (long)(d * 1.0E9);
  2640. ok = TRUE;
  2641. }
  2642. }
  2643. }
  2644. return ok ? 0 : -1;
  2645. }
  2646. #endif
  2647. static int
  2648. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2649. {
  2650. (void)unused;
  2651. InitializeCriticalSection(&cv->threadIdSec);
  2652. cv->waiting_thread = NULL;
  2653. return 0;
  2654. }
  2655. static int
  2656. pthread_cond_timedwait(pthread_cond_t *cv,
  2657. pthread_mutex_t *mutex,
  2658. const struct timespec *abstime)
  2659. {
  2660. struct mg_workerTLS **ptls,
  2661. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2662. int ok;
  2663. struct timespec tsnow;
  2664. int64_t nsnow, nswaitabs, nswaitrel;
  2665. DWORD mswaitrel;
  2666. EnterCriticalSection(&cv->threadIdSec);
  2667. /* Add this thread to cv's waiting list */
  2668. ptls = &cv->waiting_thread;
  2669. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2670. ;
  2671. tls->next_waiting_thread = NULL;
  2672. *ptls = tls;
  2673. LeaveCriticalSection(&cv->threadIdSec);
  2674. if (abstime) {
  2675. clock_gettime(CLOCK_REALTIME, &tsnow);
  2676. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2677. nswaitabs =
  2678. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2679. nswaitrel = nswaitabs - nsnow;
  2680. if (nswaitrel < 0) {
  2681. nswaitrel = 0;
  2682. }
  2683. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2684. } else {
  2685. mswaitrel = INFINITE;
  2686. }
  2687. pthread_mutex_unlock(mutex);
  2688. ok = (WAIT_OBJECT_0
  2689. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2690. if (!ok) {
  2691. ok = 1;
  2692. EnterCriticalSection(&cv->threadIdSec);
  2693. ptls = &cv->waiting_thread;
  2694. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2695. if (*ptls == tls) {
  2696. *ptls = tls->next_waiting_thread;
  2697. ok = 0;
  2698. break;
  2699. }
  2700. }
  2701. LeaveCriticalSection(&cv->threadIdSec);
  2702. if (ok) {
  2703. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2704. }
  2705. }
  2706. /* This thread has been removed from cv's waiting list */
  2707. pthread_mutex_lock(mutex);
  2708. return ok ? 0 : -1;
  2709. }
  2710. static int
  2711. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2712. {
  2713. return pthread_cond_timedwait(cv, mutex, NULL);
  2714. }
  2715. static int
  2716. pthread_cond_signal(pthread_cond_t *cv)
  2717. {
  2718. HANDLE wkup = NULL;
  2719. BOOL ok = FALSE;
  2720. EnterCriticalSection(&cv->threadIdSec);
  2721. if (cv->waiting_thread) {
  2722. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2723. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2724. ok = SetEvent(wkup);
  2725. assert(ok);
  2726. }
  2727. LeaveCriticalSection(&cv->threadIdSec);
  2728. return ok ? 0 : 1;
  2729. }
  2730. static int
  2731. pthread_cond_broadcast(pthread_cond_t *cv)
  2732. {
  2733. EnterCriticalSection(&cv->threadIdSec);
  2734. while (cv->waiting_thread) {
  2735. pthread_cond_signal(cv);
  2736. }
  2737. LeaveCriticalSection(&cv->threadIdSec);
  2738. return 0;
  2739. }
  2740. static int
  2741. pthread_cond_destroy(pthread_cond_t *cv)
  2742. {
  2743. EnterCriticalSection(&cv->threadIdSec);
  2744. assert(cv->waiting_thread == NULL);
  2745. LeaveCriticalSection(&cv->threadIdSec);
  2746. DeleteCriticalSection(&cv->threadIdSec);
  2747. return 0;
  2748. }
  2749. #ifdef ALTERNATIVE_QUEUE
  2750. static void *
  2751. event_create(void)
  2752. {
  2753. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2754. }
  2755. static int
  2756. event_wait(void *eventhdl)
  2757. {
  2758. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2759. return (res == WAIT_OBJECT_0);
  2760. }
  2761. static int
  2762. event_signal(void *eventhdl)
  2763. {
  2764. return (int)SetEvent((HANDLE)eventhdl);
  2765. }
  2766. static void
  2767. event_destroy(void *eventhdl)
  2768. {
  2769. CloseHandle((HANDLE)eventhdl);
  2770. }
  2771. #endif
  2772. #if defined(__MINGW32__)
  2773. /* Enable unused function warning again */
  2774. #pragma GCC diagnostic pop
  2775. #endif
  2776. /* For Windows, change all slashes to backslashes in path names. */
  2777. static void
  2778. change_slashes_to_backslashes(char *path)
  2779. {
  2780. int i;
  2781. for (i = 0; path[i] != '\0'; i++) {
  2782. if (path[i] == '/') {
  2783. path[i] = '\\';
  2784. }
  2785. /* remove double backslash (check i > 0 to preserve UNC paths,
  2786. * like \\server\file.txt) */
  2787. if ((path[i] == '\\') && (i > 0)) {
  2788. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2789. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2790. }
  2791. }
  2792. }
  2793. }
  2794. static int
  2795. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2796. {
  2797. int diff;
  2798. do {
  2799. diff = tolower(*s1) - tolower(*s2);
  2800. s1++;
  2801. s2++;
  2802. } while (diff == 0 && s1[-1] != '\0');
  2803. return diff;
  2804. }
  2805. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2806. * wbuf and wbuf_len is a target buffer and its length. */
  2807. static void
  2808. path_to_unicode(const struct mg_connection *conn,
  2809. const char *path,
  2810. wchar_t *wbuf,
  2811. size_t wbuf_len)
  2812. {
  2813. char buf[PATH_MAX], buf2[PATH_MAX];
  2814. wchar_t wbuf2[MAX_PATH + 1];
  2815. DWORD long_len, err;
  2816. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2817. mg_strlcpy(buf, path, sizeof(buf));
  2818. change_slashes_to_backslashes(buf);
  2819. /* Convert to Unicode and back. If doubly-converted string does not
  2820. * match the original, something is fishy, reject. */
  2821. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2822. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2823. WideCharToMultiByte(
  2824. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2825. if (strcmp(buf, buf2) != 0) {
  2826. wbuf[0] = L'\0';
  2827. }
  2828. /* Windows file systems are not case sensitive, but you can still use
  2829. * uppercase and lowercase letters (on all modern file systems).
  2830. * The server can check if the URI uses the same upper/lowercase
  2831. * letters an the file system, effectively making Windows servers
  2832. * case sensitive (like Linux servers are). It is still not possible
  2833. * to use two files with the same name in different cases on Windows
  2834. * (like /a and /A) - this would be possible in Linux.
  2835. * As a default, Windows is not case sensitive, but the case sensitive
  2836. * file name check can be activated by an additional configuration. */
  2837. if (conn) {
  2838. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  2839. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  2840. /* Use case sensitive compare function */
  2841. fcompare = wcscmp;
  2842. }
  2843. }
  2844. (void)conn; /* conn is currently unused */
  2845. #if !defined(_WIN32_WCE)
  2846. /* Only accept a full file path, not a Windows short (8.3) path. */
  2847. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2848. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2849. if (long_len == 0) {
  2850. err = GetLastError();
  2851. if (err == ERROR_FILE_NOT_FOUND) {
  2852. /* File does not exist. This is not always a problem here. */
  2853. return;
  2854. }
  2855. }
  2856. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2857. /* Short name is used. */
  2858. wbuf[0] = L'\0';
  2859. }
  2860. #else
  2861. (void)long_len;
  2862. (void)wbuf2;
  2863. (void)err;
  2864. if (strchr(path, '~')) {
  2865. wbuf[0] = L'\0';
  2866. }
  2867. #endif
  2868. }
  2869. /* Windows happily opens files with some garbage at the end of file name.
  2870. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2871. * "a.cgi", despite one would expect an error back.
  2872. * This function returns non-0 if path ends with some garbage. */
  2873. static int
  2874. path_cannot_disclose_cgi(const char *path)
  2875. {
  2876. static const char *allowed_last_characters = "_-";
  2877. int last = path[strlen(path) - 1];
  2878. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2879. }
  2880. static int
  2881. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2882. {
  2883. wchar_t wbuf[PATH_MAX];
  2884. WIN32_FILE_ATTRIBUTE_DATA info;
  2885. time_t creation_time;
  2886. if (!filep) {
  2887. return 0;
  2888. }
  2889. memset(filep, 0, sizeof(*filep));
  2890. if (conn && is_file_in_memory(conn, path, filep)) {
  2891. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2892. * memset */
  2893. filep->last_modified = time(NULL);
  2894. /* last_modified = now ... assumes the file may change during runtime,
  2895. * so every mg_fopen call may return different data */
  2896. /* last_modified = conn->ctx.start_time;
  2897. * May be used it the data does not change during runtime. This allows
  2898. * browser caching. Since we do not know, we have to assume the file
  2899. * in memory may change. */
  2900. return 1;
  2901. }
  2902. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2903. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2904. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2905. filep->last_modified =
  2906. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2907. info.ftLastWriteTime.dwHighDateTime);
  2908. /* On Windows, the file creation time can be higher than the
  2909. * modification time, e.g. when a file is copied.
  2910. * Since the Last-Modified timestamp is used for caching
  2911. * it should be based on the most recent timestamp. */
  2912. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2913. info.ftCreationTime.dwHighDateTime);
  2914. if (creation_time > filep->last_modified) {
  2915. filep->last_modified = creation_time;
  2916. }
  2917. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2918. /* If file name is fishy, reset the file structure and return
  2919. * error.
  2920. * Note it is important to reset, not just return the error, cause
  2921. * functions like is_file_opened() check the struct. */
  2922. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2923. memset(filep, 0, sizeof(*filep));
  2924. return 0;
  2925. }
  2926. return 1;
  2927. }
  2928. return 0;
  2929. }
  2930. static int
  2931. mg_remove(const struct mg_connection *conn, const char *path)
  2932. {
  2933. wchar_t wbuf[PATH_MAX];
  2934. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2935. return DeleteFileW(wbuf) ? 0 : -1;
  2936. }
  2937. static int
  2938. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2939. {
  2940. wchar_t wbuf[PATH_MAX];
  2941. (void)mode;
  2942. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2943. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2944. }
  2945. /* Create substitutes for POSIX functions in Win32. */
  2946. #if defined(__MINGW32__)
  2947. /* Show no warning in case system functions are not used. */
  2948. #pragma GCC diagnostic push
  2949. #pragma GCC diagnostic ignored "-Wunused-function"
  2950. #endif
  2951. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2952. static DIR *
  2953. mg_opendir(const struct mg_connection *conn, const char *name)
  2954. {
  2955. DIR *dir = NULL;
  2956. wchar_t wpath[PATH_MAX];
  2957. DWORD attrs;
  2958. if (name == NULL) {
  2959. SetLastError(ERROR_BAD_ARGUMENTS);
  2960. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2961. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2962. } else {
  2963. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2964. attrs = GetFileAttributesW(wpath);
  2965. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2966. == FILE_ATTRIBUTE_DIRECTORY)) {
  2967. (void)wcscat(wpath, L"\\*");
  2968. dir->handle = FindFirstFileW(wpath, &dir->info);
  2969. dir->result.d_name[0] = '\0';
  2970. } else {
  2971. mg_free(dir);
  2972. dir = NULL;
  2973. }
  2974. }
  2975. return dir;
  2976. }
  2977. static int
  2978. mg_closedir(DIR *dir)
  2979. {
  2980. int result = 0;
  2981. if (dir != NULL) {
  2982. if (dir->handle != INVALID_HANDLE_VALUE)
  2983. result = FindClose(dir->handle) ? 0 : -1;
  2984. mg_free(dir);
  2985. } else {
  2986. result = -1;
  2987. SetLastError(ERROR_BAD_ARGUMENTS);
  2988. }
  2989. return result;
  2990. }
  2991. static struct dirent *
  2992. mg_readdir(DIR *dir)
  2993. {
  2994. struct dirent *result = 0;
  2995. if (dir) {
  2996. if (dir->handle != INVALID_HANDLE_VALUE) {
  2997. result = &dir->result;
  2998. (void)WideCharToMultiByte(CP_UTF8,
  2999. 0,
  3000. dir->info.cFileName,
  3001. -1,
  3002. result->d_name,
  3003. sizeof(result->d_name),
  3004. NULL,
  3005. NULL);
  3006. if (!FindNextFileW(dir->handle, &dir->info)) {
  3007. (void)FindClose(dir->handle);
  3008. dir->handle = INVALID_HANDLE_VALUE;
  3009. }
  3010. } else {
  3011. SetLastError(ERROR_FILE_NOT_FOUND);
  3012. }
  3013. } else {
  3014. SetLastError(ERROR_BAD_ARGUMENTS);
  3015. }
  3016. return result;
  3017. }
  3018. #ifndef HAVE_POLL
  3019. static int
  3020. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3021. {
  3022. struct timeval tv;
  3023. fd_set set;
  3024. unsigned int i;
  3025. int result;
  3026. SOCKET maxfd = 0;
  3027. memset(&tv, 0, sizeof(tv));
  3028. tv.tv_sec = milliseconds / 1000;
  3029. tv.tv_usec = (milliseconds % 1000) * 1000;
  3030. FD_ZERO(&set);
  3031. for (i = 0; i < n; i++) {
  3032. FD_SET((SOCKET)pfd[i].fd, &set);
  3033. pfd[i].revents = 0;
  3034. if (pfd[i].fd > maxfd) {
  3035. maxfd = pfd[i].fd;
  3036. }
  3037. }
  3038. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3039. for (i = 0; i < n; i++) {
  3040. if (FD_ISSET(pfd[i].fd, &set)) {
  3041. pfd[i].revents = POLLIN;
  3042. }
  3043. }
  3044. }
  3045. /* Should subtract time used in select from remaining "milliseconds",
  3046. * in particular if called from mg_poll with a timeout quantum.
  3047. * Unfortunately, the remaining time is not stored in "tv" in all
  3048. * implementations, so the result in "tv" must be considered undefined.
  3049. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3050. return result;
  3051. }
  3052. #endif /* HAVE_POLL */
  3053. #if defined(__MINGW32__)
  3054. /* Enable unused function warning again */
  3055. #pragma GCC diagnostic pop
  3056. #endif
  3057. static void
  3058. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3059. {
  3060. (void)conn; /* Unused. */
  3061. #if defined(_WIN32_WCE)
  3062. (void)sock;
  3063. #else
  3064. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3065. #endif
  3066. }
  3067. int
  3068. mg_start_thread(mg_thread_func_t f, void *p)
  3069. {
  3070. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3071. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3072. */
  3073. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3074. == ((uintptr_t)(-1L)))
  3075. ? -1
  3076. : 0);
  3077. #else
  3078. return (
  3079. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3080. ? -1
  3081. : 0);
  3082. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3083. }
  3084. /* Start a thread storing the thread context. */
  3085. static int
  3086. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3087. void *p,
  3088. pthread_t *threadidptr)
  3089. {
  3090. uintptr_t uip;
  3091. HANDLE threadhandle;
  3092. int result = -1;
  3093. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3094. threadhandle = (HANDLE)uip;
  3095. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3096. *threadidptr = threadhandle;
  3097. result = 0;
  3098. }
  3099. return result;
  3100. }
  3101. /* Wait for a thread to finish. */
  3102. static int
  3103. mg_join_thread(pthread_t threadid)
  3104. {
  3105. int result;
  3106. DWORD dwevent;
  3107. result = -1;
  3108. dwevent = WaitForSingleObject(threadid, INFINITE);
  3109. if (dwevent == WAIT_FAILED) {
  3110. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3111. } else {
  3112. if (dwevent == WAIT_OBJECT_0) {
  3113. CloseHandle(threadid);
  3114. result = 0;
  3115. }
  3116. }
  3117. return result;
  3118. }
  3119. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3120. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3121. /* Create substitutes for POSIX functions in Win32. */
  3122. #if defined(__MINGW32__)
  3123. /* Show no warning in case system functions are not used. */
  3124. #pragma GCC diagnostic push
  3125. #pragma GCC diagnostic ignored "-Wunused-function"
  3126. #endif
  3127. static HANDLE
  3128. dlopen(const char *dll_name, int flags)
  3129. {
  3130. wchar_t wbuf[PATH_MAX];
  3131. (void)flags;
  3132. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3133. return LoadLibraryW(wbuf);
  3134. }
  3135. static int
  3136. dlclose(void *handle)
  3137. {
  3138. int result;
  3139. if (FreeLibrary((HMODULE)handle) != 0) {
  3140. result = 0;
  3141. } else {
  3142. result = -1;
  3143. }
  3144. return result;
  3145. }
  3146. #if defined(__MINGW32__)
  3147. /* Enable unused function warning again */
  3148. #pragma GCC diagnostic pop
  3149. #endif
  3150. #endif
  3151. #if !defined(NO_CGI)
  3152. #define SIGKILL (0)
  3153. static int
  3154. kill(pid_t pid, int sig_num)
  3155. {
  3156. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3157. (void)CloseHandle((HANDLE)pid);
  3158. return 0;
  3159. }
  3160. static void
  3161. trim_trailing_whitespaces(char *s)
  3162. {
  3163. char *e = s + strlen(s) - 1;
  3164. while (e > s && isspace(*(unsigned char *)e)) {
  3165. *e-- = '\0';
  3166. }
  3167. }
  3168. static pid_t
  3169. spawn_process(struct mg_connection *conn,
  3170. const char *prog,
  3171. char *envblk,
  3172. char *envp[],
  3173. int fdin[2],
  3174. int fdout[2],
  3175. int fderr[2],
  3176. const char *dir)
  3177. {
  3178. HANDLE me;
  3179. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3180. cmdline[PATH_MAX], buf[PATH_MAX];
  3181. int truncated;
  3182. struct file file = STRUCT_FILE_INITIALIZER;
  3183. STARTUPINFOA si;
  3184. PROCESS_INFORMATION pi = {0};
  3185. (void)envp;
  3186. memset(&si, 0, sizeof(si));
  3187. si.cb = sizeof(si);
  3188. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3189. si.wShowWindow = SW_HIDE;
  3190. me = GetCurrentProcess();
  3191. DuplicateHandle(me,
  3192. (HANDLE)_get_osfhandle(fdin[0]),
  3193. me,
  3194. &si.hStdInput,
  3195. 0,
  3196. TRUE,
  3197. DUPLICATE_SAME_ACCESS);
  3198. DuplicateHandle(me,
  3199. (HANDLE)_get_osfhandle(fdout[1]),
  3200. me,
  3201. &si.hStdOutput,
  3202. 0,
  3203. TRUE,
  3204. DUPLICATE_SAME_ACCESS);
  3205. DuplicateHandle(me,
  3206. (HANDLE)_get_osfhandle(fderr[1]),
  3207. me,
  3208. &si.hStdError,
  3209. 0,
  3210. TRUE,
  3211. DUPLICATE_SAME_ACCESS);
  3212. /* Mark handles that should not be inherited. See
  3213. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3214. */
  3215. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3216. HANDLE_FLAG_INHERIT,
  3217. 0);
  3218. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3219. HANDLE_FLAG_INHERIT,
  3220. 0);
  3221. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3222. HANDLE_FLAG_INHERIT,
  3223. 0);
  3224. /* If CGI file is a script, try to read the interpreter line */
  3225. interp = conn->ctx->config[CGI_INTERPRETER];
  3226. if (interp == NULL) {
  3227. buf[0] = buf[1] = '\0';
  3228. /* Read the first line of the script into the buffer */
  3229. mg_snprintf(
  3230. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3231. if (truncated) {
  3232. pi.hProcess = (pid_t)-1;
  3233. goto spawn_cleanup;
  3234. }
  3235. if (mg_fopen(conn, cmdline, "r", &file)) {
  3236. p = (char *)file.membuf;
  3237. mg_fgets(buf, sizeof(buf), &file, &p);
  3238. mg_fclose(&file);
  3239. buf[sizeof(buf) - 1] = '\0';
  3240. }
  3241. if (buf[0] == '#' && buf[1] == '!') {
  3242. trim_trailing_whitespaces(buf + 2);
  3243. } else {
  3244. buf[2] = '\0';
  3245. }
  3246. interp = buf + 2;
  3247. }
  3248. if (interp[0] != '\0') {
  3249. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3250. interp = full_interp;
  3251. }
  3252. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3253. if (interp[0] != '\0') {
  3254. mg_snprintf(conn,
  3255. &truncated,
  3256. cmdline,
  3257. sizeof(cmdline),
  3258. "\"%s\" \"%s\\%s\"",
  3259. interp,
  3260. full_dir,
  3261. prog);
  3262. } else {
  3263. mg_snprintf(conn,
  3264. &truncated,
  3265. cmdline,
  3266. sizeof(cmdline),
  3267. "\"%s\\%s\"",
  3268. full_dir,
  3269. prog);
  3270. }
  3271. if (truncated) {
  3272. pi.hProcess = (pid_t)-1;
  3273. goto spawn_cleanup;
  3274. }
  3275. DEBUG_TRACE("Running [%s]", cmdline);
  3276. if (CreateProcessA(NULL,
  3277. cmdline,
  3278. NULL,
  3279. NULL,
  3280. TRUE,
  3281. CREATE_NEW_PROCESS_GROUP,
  3282. envblk,
  3283. NULL,
  3284. &si,
  3285. &pi) == 0) {
  3286. mg_cry(
  3287. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3288. pi.hProcess = (pid_t)-1;
  3289. /* goto spawn_cleanup; */
  3290. }
  3291. spawn_cleanup:
  3292. (void)CloseHandle(si.hStdOutput);
  3293. (void)CloseHandle(si.hStdError);
  3294. (void)CloseHandle(si.hStdInput);
  3295. if (pi.hThread != NULL) {
  3296. (void)CloseHandle(pi.hThread);
  3297. }
  3298. return (pid_t)pi.hProcess;
  3299. }
  3300. #endif /* !NO_CGI */
  3301. static int
  3302. set_non_blocking_mode(SOCKET sock)
  3303. {
  3304. unsigned long on = 1;
  3305. return ioctlsocket(sock, (long)FIONBIO, &on);
  3306. }
  3307. #else
  3308. static int
  3309. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3310. {
  3311. struct stat st;
  3312. if (!filep) {
  3313. return 0;
  3314. }
  3315. memset(filep, 0, sizeof(*filep));
  3316. if (conn && is_file_in_memory(conn, path, filep)) {
  3317. return 1;
  3318. }
  3319. if (0 == stat(path, &st)) {
  3320. filep->size = (uint64_t)(st.st_size);
  3321. filep->last_modified = st.st_mtime;
  3322. filep->is_directory = S_ISDIR(st.st_mode);
  3323. return 1;
  3324. }
  3325. return 0;
  3326. }
  3327. static void
  3328. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3329. {
  3330. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3331. if (conn) {
  3332. mg_cry(conn,
  3333. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3334. __func__,
  3335. strerror(ERRNO));
  3336. }
  3337. }
  3338. }
  3339. int
  3340. mg_start_thread(mg_thread_func_t func, void *param)
  3341. {
  3342. pthread_t thread_id;
  3343. pthread_attr_t attr;
  3344. int result;
  3345. (void)pthread_attr_init(&attr);
  3346. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3347. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3348. /* Compile-time option to control stack size,
  3349. * e.g. -DUSE_STACK_SIZE=16384 */
  3350. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3351. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3352. result = pthread_create(&thread_id, &attr, func, param);
  3353. pthread_attr_destroy(&attr);
  3354. return result;
  3355. }
  3356. /* Start a thread storing the thread context. */
  3357. static int
  3358. mg_start_thread_with_id(mg_thread_func_t func,
  3359. void *param,
  3360. pthread_t *threadidptr)
  3361. {
  3362. pthread_t thread_id;
  3363. pthread_attr_t attr;
  3364. int result;
  3365. (void)pthread_attr_init(&attr);
  3366. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3367. /* Compile-time option to control stack size,
  3368. * e.g. -DUSE_STACK_SIZE=16384 */
  3369. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3370. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3371. result = pthread_create(&thread_id, &attr, func, param);
  3372. pthread_attr_destroy(&attr);
  3373. if ((result == 0) && (threadidptr != NULL)) {
  3374. *threadidptr = thread_id;
  3375. }
  3376. return result;
  3377. }
  3378. /* Wait for a thread to finish. */
  3379. static int
  3380. mg_join_thread(pthread_t threadid)
  3381. {
  3382. int result;
  3383. result = pthread_join(threadid, NULL);
  3384. return result;
  3385. }
  3386. #ifndef NO_CGI
  3387. static pid_t
  3388. spawn_process(struct mg_connection *conn,
  3389. const char *prog,
  3390. char *envblk,
  3391. char *envp[],
  3392. int fdin[2],
  3393. int fdout[2],
  3394. int fderr[2],
  3395. const char *dir)
  3396. {
  3397. pid_t pid;
  3398. const char *interp;
  3399. (void)envblk;
  3400. if (conn == NULL) {
  3401. return 0;
  3402. }
  3403. if ((pid = fork()) == -1) {
  3404. /* Parent */
  3405. send_http_error(conn,
  3406. 500,
  3407. "Error: Creating CGI process\nfork(): %s",
  3408. strerror(ERRNO));
  3409. } else if (pid == 0) {
  3410. /* Child */
  3411. if (chdir(dir) != 0) {
  3412. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3413. } else if (dup2(fdin[0], 0) == -1) {
  3414. mg_cry(conn,
  3415. "%s: dup2(%d, 0): %s",
  3416. __func__,
  3417. fdin[0],
  3418. strerror(ERRNO));
  3419. } else if (dup2(fdout[1], 1) == -1) {
  3420. mg_cry(conn,
  3421. "%s: dup2(%d, 1): %s",
  3422. __func__,
  3423. fdout[1],
  3424. strerror(ERRNO));
  3425. } else if (dup2(fderr[1], 2) == -1) {
  3426. mg_cry(conn,
  3427. "%s: dup2(%d, 2): %s",
  3428. __func__,
  3429. fderr[1],
  3430. strerror(ERRNO));
  3431. } else {
  3432. /* Keep stderr and stdout in two different pipes.
  3433. * Stdout will be sent back to the client,
  3434. * stderr should go into a server error log. */
  3435. (void)close(fdin[0]);
  3436. (void)close(fdout[1]);
  3437. (void)close(fderr[1]);
  3438. /* Close write end fdin and read end fdout and fderr */
  3439. (void)close(fdin[1]);
  3440. (void)close(fdout[0]);
  3441. (void)close(fderr[0]);
  3442. /* After exec, all signal handlers are restored to their default
  3443. * values, with one exception of SIGCHLD. According to
  3444. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3445. * leave unchanged after exec if it was set to be ignored. Restore
  3446. * it to default action. */
  3447. signal(SIGCHLD, SIG_DFL);
  3448. interp = conn->ctx->config[CGI_INTERPRETER];
  3449. if (interp == NULL) {
  3450. (void)execle(prog, prog, NULL, envp);
  3451. mg_cry(conn,
  3452. "%s: execle(%s): %s",
  3453. __func__,
  3454. prog,
  3455. strerror(ERRNO));
  3456. } else {
  3457. (void)execle(interp, interp, prog, NULL, envp);
  3458. mg_cry(conn,
  3459. "%s: execle(%s %s): %s",
  3460. __func__,
  3461. interp,
  3462. prog,
  3463. strerror(ERRNO));
  3464. }
  3465. }
  3466. exit(EXIT_FAILURE);
  3467. }
  3468. return pid;
  3469. }
  3470. #endif /* !NO_CGI */
  3471. static int
  3472. set_non_blocking_mode(SOCKET sock)
  3473. {
  3474. int flags;
  3475. flags = fcntl(sock, F_GETFL, 0);
  3476. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3477. return 0;
  3478. }
  3479. #endif /* _WIN32 */
  3480. /* End of initial operating system specific define block. */
  3481. /* Get a random number (independent of C rand function) */
  3482. static uint64_t
  3483. get_random(void)
  3484. {
  3485. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3486. static uint64_t lcg = 0; /* Linear congruential generator */
  3487. struct timespec now;
  3488. memset(&now, 0, sizeof(now));
  3489. clock_gettime(CLOCK_MONOTONIC, &now);
  3490. if (lfsr == 0) {
  3491. /* lfsr will be only 0 if has not been initialized,
  3492. * so this code is called only once. */
  3493. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3494. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3495. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3496. + (uint64_t)(ptrdiff_t)&now;
  3497. } else {
  3498. /* Get the next step of both random number generators. */
  3499. lfsr = (lfsr >> 1)
  3500. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3501. << 63);
  3502. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3503. }
  3504. /* Combining two pseudo-random number generators and a high resolution part
  3505. * of the current server time will make it hard (impossible?) to guess the
  3506. * next number. */
  3507. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3508. }
  3509. static int
  3510. mg_poll(struct pollfd *pfd,
  3511. unsigned int n,
  3512. int milliseconds,
  3513. volatile int *stop_server)
  3514. {
  3515. int ms_now, result;
  3516. /* Call poll, but only for a maximum time of a few seconds.
  3517. * This will allow to stop the server after some seconds, instead
  3518. * of having to wait for a long socket timeout. */
  3519. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3520. do {
  3521. if (*stop_server) {
  3522. /* Shut down signal */
  3523. return -2;
  3524. }
  3525. if (milliseconds < ms_now) {
  3526. ms_now = milliseconds;
  3527. }
  3528. result = poll(pfd, n, ms_now);
  3529. if (result != 0) {
  3530. /* Poll returned either success (1) or error (-1).
  3531. * Forward both to the caller. */
  3532. return result;
  3533. }
  3534. /* Poll returned timeout (0). */
  3535. milliseconds -= ms_now;
  3536. } while (milliseconds > 0);
  3537. return result;
  3538. }
  3539. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3540. * descriptor. Return number of bytes written. */
  3541. static int
  3542. push(struct mg_context *ctx,
  3543. FILE *fp,
  3544. SOCKET sock,
  3545. SSL *ssl,
  3546. const char *buf,
  3547. int len,
  3548. double timeout)
  3549. {
  3550. struct timespec start, now;
  3551. int n, err;
  3552. #ifdef _WIN32
  3553. typedef int len_t;
  3554. #else
  3555. typedef size_t len_t;
  3556. #endif
  3557. if (timeout > 0) {
  3558. memset(&start, 0, sizeof(start));
  3559. memset(&now, 0, sizeof(now));
  3560. clock_gettime(CLOCK_MONOTONIC, &start);
  3561. }
  3562. if (ctx == NULL) {
  3563. return -1;
  3564. }
  3565. #ifdef NO_SSL
  3566. if (ssl) {
  3567. return -1;
  3568. }
  3569. #endif
  3570. do {
  3571. #ifndef NO_SSL
  3572. if (ssl != NULL) {
  3573. n = SSL_write(ssl, buf, len);
  3574. if (n <= 0) {
  3575. err = SSL_get_error(ssl, n);
  3576. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3577. err = ERRNO;
  3578. } else if ((err == SSL_ERROR_WANT_READ)
  3579. || (err == SSL_ERROR_WANT_WRITE)) {
  3580. n = 0;
  3581. } else {
  3582. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3583. return -1;
  3584. }
  3585. } else {
  3586. err = 0;
  3587. }
  3588. } else
  3589. #endif
  3590. if (fp != NULL) {
  3591. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3592. if (ferror(fp)) {
  3593. n = -1;
  3594. err = ERRNO;
  3595. } else {
  3596. err = 0;
  3597. }
  3598. } else {
  3599. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3600. err = (n < 0) ? ERRNO : 0;
  3601. if (n == 0) {
  3602. /* shutdown of the socket at client side */
  3603. return -1;
  3604. }
  3605. }
  3606. if (ctx->stop_flag) {
  3607. return -1;
  3608. }
  3609. if ((n > 0) || (n == 0 && len == 0)) {
  3610. /* some data has been read, or no data was requested */
  3611. return n;
  3612. }
  3613. if (n < 0) {
  3614. /* socket error - check errno */
  3615. DEBUG_TRACE("send() failed, error %d", err);
  3616. /* TODO: error handling depending on the error code.
  3617. * These codes are different between Windows and Linux.
  3618. */
  3619. return -1;
  3620. }
  3621. /* This code is not reached in the moment.
  3622. * ==> Fix the TODOs above first. */
  3623. if (timeout > 0) {
  3624. clock_gettime(CLOCK_MONOTONIC, &now);
  3625. }
  3626. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3627. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3628. used */
  3629. return -1;
  3630. }
  3631. static int64_t
  3632. push_all(struct mg_context *ctx,
  3633. FILE *fp,
  3634. SOCKET sock,
  3635. SSL *ssl,
  3636. const char *buf,
  3637. int64_t len)
  3638. {
  3639. double timeout = -1.0;
  3640. int64_t n, nwritten = 0;
  3641. if (ctx == NULL) {
  3642. return -1;
  3643. }
  3644. if (ctx->config[REQUEST_TIMEOUT]) {
  3645. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3646. }
  3647. while (len > 0 && ctx->stop_flag == 0) {
  3648. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3649. if (n < 0) {
  3650. if (nwritten == 0) {
  3651. nwritten = n; /* Propagate the error */
  3652. }
  3653. break;
  3654. } else if (n == 0) {
  3655. break; /* No more data to write */
  3656. } else {
  3657. nwritten += n;
  3658. len -= n;
  3659. }
  3660. }
  3661. return nwritten;
  3662. }
  3663. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3664. * Return negative value on error, or number of bytes read on success. */
  3665. static int
  3666. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3667. {
  3668. int nread, err = 0;
  3669. struct timespec start, now;
  3670. #ifdef _WIN32
  3671. typedef int len_t;
  3672. #else
  3673. typedef size_t len_t;
  3674. #endif
  3675. if (timeout > 0) {
  3676. memset(&start, 0, sizeof(start));
  3677. memset(&now, 0, sizeof(now));
  3678. clock_gettime(CLOCK_MONOTONIC, &start);
  3679. }
  3680. do {
  3681. if (fp != NULL) {
  3682. #if !defined(_WIN32_WCE)
  3683. /* Use read() instead of fread(), because if we're reading from the
  3684. * CGI pipe, fread() may block until IO buffer is filled up. We
  3685. * cannot afford to block and must pass all read bytes immediately
  3686. * to the client. */
  3687. nread = (int)read(fileno(fp), buf, (size_t)len);
  3688. #else
  3689. /* WinCE does not support CGI pipes */
  3690. nread = (int)fread(buf, 1, (size_t)len, fp);
  3691. #endif
  3692. err = (nread < 0) ? ERRNO : 0;
  3693. #ifndef NO_SSL
  3694. } else if (conn->ssl != NULL) {
  3695. struct pollfd pfd[1];
  3696. int pollres;
  3697. pfd[0].fd = conn->client.sock;
  3698. pfd[0].events = POLLIN;
  3699. pollres = mg_poll(pfd,
  3700. 1,
  3701. (int)(timeout * 1000.0),
  3702. &(conn->ctx->stop_flag));
  3703. if (conn->ctx->stop_flag) {
  3704. return -1;
  3705. }
  3706. if (pollres > 0) {
  3707. nread = SSL_read(conn->ssl, buf, len);
  3708. if (nread <= 0) {
  3709. err = SSL_get_error(conn->ssl, nread);
  3710. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3711. err = ERRNO;
  3712. } else if ((err == SSL_ERROR_WANT_READ)
  3713. || (err == SSL_ERROR_WANT_WRITE)) {
  3714. nread = 0;
  3715. } else {
  3716. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3717. return -1;
  3718. }
  3719. } else {
  3720. err = 0;
  3721. }
  3722. } else if (pollres < 0) {
  3723. /* Error */
  3724. return -1;
  3725. } else {
  3726. /* pollres = 0 means timeout */
  3727. nread = 0;
  3728. }
  3729. #endif
  3730. } else {
  3731. struct pollfd pfd[1];
  3732. int pollres;
  3733. pfd[0].fd = conn->client.sock;
  3734. pfd[0].events = POLLIN;
  3735. pollres = mg_poll(pfd,
  3736. 1,
  3737. (int)(timeout * 1000.0),
  3738. &(conn->ctx->stop_flag));
  3739. if (conn->ctx->stop_flag) {
  3740. return -1;
  3741. }
  3742. if (pollres > 0) {
  3743. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3744. err = (nread < 0) ? ERRNO : 0;
  3745. if (nread == 0) {
  3746. /* shutdown of the socket at client side */
  3747. return -1;
  3748. }
  3749. } else if (pollres < 0) {
  3750. /* error callint poll */
  3751. return -1;
  3752. } else {
  3753. /* pollres = 0 means timeout */
  3754. nread = 0;
  3755. }
  3756. }
  3757. if (conn->ctx->stop_flag) {
  3758. return -1;
  3759. }
  3760. if ((nread > 0) || (nread == 0 && len == 0)) {
  3761. /* some data has been read, or no data was requested */
  3762. return nread;
  3763. }
  3764. if (nread < 0) {
  3765. /* socket error - check errno */
  3766. #ifdef _WIN32
  3767. if (err == WSAEWOULDBLOCK) {
  3768. /* standard case if called from close_socket_gracefully */
  3769. return -1;
  3770. } else if (err == WSAETIMEDOUT) {
  3771. /* timeout is handled by the while loop */
  3772. } else {
  3773. DEBUG_TRACE("recv() failed, error %d", err);
  3774. return -1;
  3775. }
  3776. #else
  3777. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3778. * if the timeout is reached and if the socket was set to non-
  3779. * blocking in close_socket_gracefully, so we can not distinguish
  3780. * here. We have to wait for the timeout in both cases for now.
  3781. */
  3782. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3783. /* EAGAIN/EWOULDBLOCK:
  3784. * standard case if called from close_socket_gracefully
  3785. * => should return -1 */
  3786. /* or timeout occured
  3787. * => the code must stay in the while loop */
  3788. /* EINTR can be generated on a socket with a timeout set even
  3789. * when SA_RESTART is effective for all relevant signals
  3790. * (see signal(7)).
  3791. * => stay in the while loop */
  3792. } else {
  3793. DEBUG_TRACE("recv() failed, error %d", err);
  3794. return -1;
  3795. }
  3796. #endif
  3797. }
  3798. if (timeout > 0) {
  3799. clock_gettime(CLOCK_MONOTONIC, &now);
  3800. }
  3801. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3802. /* Timeout occured, but no data available. */
  3803. return -1;
  3804. }
  3805. static int
  3806. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3807. {
  3808. int n, nread = 0;
  3809. double timeout = -1.0;
  3810. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3811. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3812. }
  3813. while (len > 0 && conn->ctx->stop_flag == 0) {
  3814. n = pull(fp, conn, buf + nread, len, timeout);
  3815. if (n < 0) {
  3816. if (nread == 0) {
  3817. nread = n; /* Propagate the error */
  3818. }
  3819. break;
  3820. } else if (n == 0) {
  3821. break; /* No more data to read */
  3822. } else {
  3823. conn->consumed_content += n;
  3824. nread += n;
  3825. len -= n;
  3826. }
  3827. }
  3828. return nread;
  3829. }
  3830. static void
  3831. discard_unread_request_data(struct mg_connection *conn)
  3832. {
  3833. char buf[MG_BUF_LEN];
  3834. size_t to_read;
  3835. int nread;
  3836. if (conn == NULL) {
  3837. return;
  3838. }
  3839. to_read = sizeof(buf);
  3840. if (conn->is_chunked) {
  3841. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3842. * completely */
  3843. while (conn->is_chunked == 1) {
  3844. nread = mg_read(conn, buf, to_read);
  3845. if (nread <= 0) {
  3846. break;
  3847. }
  3848. }
  3849. } else {
  3850. /* Not chunked: content length is known */
  3851. while (conn->consumed_content < conn->content_len) {
  3852. if (to_read
  3853. > (size_t)(conn->content_len - conn->consumed_content)) {
  3854. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3855. }
  3856. nread = mg_read(conn, buf, to_read);
  3857. if (nread <= 0) {
  3858. break;
  3859. }
  3860. }
  3861. }
  3862. }
  3863. static int
  3864. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3865. {
  3866. int64_t n, buffered_len, nread;
  3867. int64_t len64 =
  3868. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3869. * int, we may not read more
  3870. * bytes */
  3871. const char *body;
  3872. if (conn == NULL) {
  3873. return 0;
  3874. }
  3875. /* If Content-Length is not set for a PUT or POST request, read until
  3876. * socket is closed */
  3877. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3878. conn->content_len = INT64_MAX;
  3879. conn->must_close = 1;
  3880. }
  3881. nread = 0;
  3882. if (conn->consumed_content < conn->content_len) {
  3883. /* Adjust number of bytes to read. */
  3884. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3885. if (left_to_read < len64) {
  3886. /* Do not read more than the total content length of the request.
  3887. */
  3888. len64 = left_to_read;
  3889. }
  3890. /* Return buffered data */
  3891. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3892. - conn->consumed_content;
  3893. if (buffered_len > 0) {
  3894. if (len64 < buffered_len) {
  3895. buffered_len = len64;
  3896. }
  3897. body = conn->buf + conn->request_len + conn->consumed_content;
  3898. memcpy(buf, body, (size_t)buffered_len);
  3899. len64 -= buffered_len;
  3900. conn->consumed_content += buffered_len;
  3901. nread += buffered_len;
  3902. buf = (char *)buf + buffered_len;
  3903. }
  3904. /* We have returned all buffered data. Read new data from the remote
  3905. * socket.
  3906. */
  3907. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3908. nread += n;
  3909. } else {
  3910. nread = ((nread > 0) ? nread : n);
  3911. }
  3912. }
  3913. return (int)nread;
  3914. }
  3915. static char
  3916. mg_getc(struct mg_connection *conn)
  3917. {
  3918. char c;
  3919. if (conn == NULL) {
  3920. return 0;
  3921. }
  3922. conn->content_len++;
  3923. if (mg_read_inner(conn, &c, 1) <= 0) {
  3924. return (char)0;
  3925. }
  3926. return c;
  3927. }
  3928. int
  3929. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3930. {
  3931. if (len > INT_MAX) {
  3932. len = INT_MAX;
  3933. }
  3934. if (conn == NULL) {
  3935. return 0;
  3936. }
  3937. if (conn->is_chunked) {
  3938. size_t all_read = 0;
  3939. while (len > 0) {
  3940. if (conn->is_chunked == 2) {
  3941. /* No more data left to read */
  3942. return 0;
  3943. }
  3944. if (conn->chunk_remainder) {
  3945. /* copy from the remainder of the last received chunk */
  3946. long read_ret;
  3947. size_t read_now =
  3948. ((conn->chunk_remainder > len) ? (len)
  3949. : (conn->chunk_remainder));
  3950. conn->content_len += (int)read_now;
  3951. read_ret =
  3952. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3953. all_read += (size_t)read_ret;
  3954. conn->chunk_remainder -= read_now;
  3955. len -= read_now;
  3956. if (conn->chunk_remainder == 0) {
  3957. /* the rest of the data in the current chunk has been read
  3958. */
  3959. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3960. /* Protocol violation */
  3961. return -1;
  3962. }
  3963. }
  3964. } else {
  3965. /* fetch a new chunk */
  3966. int i = 0;
  3967. char lenbuf[64];
  3968. char *end = 0;
  3969. unsigned long chunkSize = 0;
  3970. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3971. lenbuf[i] = mg_getc(conn);
  3972. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3973. continue;
  3974. }
  3975. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3976. lenbuf[i + 1] = 0;
  3977. chunkSize = strtoul(lenbuf, &end, 16);
  3978. if (chunkSize == 0) {
  3979. /* regular end of content */
  3980. conn->is_chunked = 2;
  3981. }
  3982. break;
  3983. }
  3984. if (!isalnum(lenbuf[i])) {
  3985. /* illegal character for chunk length */
  3986. return -1;
  3987. }
  3988. }
  3989. if ((end == NULL) || (*end != '\r')) {
  3990. /* chunksize not set correctly */
  3991. return -1;
  3992. }
  3993. if (chunkSize == 0) {
  3994. break;
  3995. }
  3996. conn->chunk_remainder = chunkSize;
  3997. }
  3998. }
  3999. return (int)all_read;
  4000. }
  4001. return mg_read_inner(conn, buf, len);
  4002. }
  4003. int
  4004. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4005. {
  4006. time_t now;
  4007. int64_t n, total, allowed;
  4008. if (conn == NULL) {
  4009. return 0;
  4010. }
  4011. if (conn->throttle > 0) {
  4012. if ((now = time(NULL)) != conn->last_throttle_time) {
  4013. conn->last_throttle_time = now;
  4014. conn->last_throttle_bytes = 0;
  4015. }
  4016. allowed = conn->throttle - conn->last_throttle_bytes;
  4017. if (allowed > (int64_t)len) {
  4018. allowed = (int64_t)len;
  4019. }
  4020. if ((total = push_all(conn->ctx,
  4021. NULL,
  4022. conn->client.sock,
  4023. conn->ssl,
  4024. (const char *)buf,
  4025. (int64_t)allowed)) == allowed) {
  4026. buf = (const char *)buf + total;
  4027. conn->last_throttle_bytes += total;
  4028. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4029. allowed = (conn->throttle > ((int64_t)len - total))
  4030. ? (int64_t)len - total
  4031. : conn->throttle;
  4032. if ((n = push_all(conn->ctx,
  4033. NULL,
  4034. conn->client.sock,
  4035. conn->ssl,
  4036. (const char *)buf,
  4037. (int64_t)allowed)) != allowed) {
  4038. break;
  4039. }
  4040. sleep(1);
  4041. conn->last_throttle_bytes = allowed;
  4042. conn->last_throttle_time = time(NULL);
  4043. buf = (const char *)buf + n;
  4044. total += n;
  4045. }
  4046. }
  4047. } else {
  4048. total = push_all(conn->ctx,
  4049. NULL,
  4050. conn->client.sock,
  4051. conn->ssl,
  4052. (const char *)buf,
  4053. (int64_t)len);
  4054. }
  4055. return (int)total;
  4056. }
  4057. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4058. static int
  4059. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4060. {
  4061. va_list ap_copy;
  4062. size_t size = MG_BUF_LEN / 4;
  4063. int len = -1;
  4064. *buf = NULL;
  4065. while (len < 0) {
  4066. if (*buf) {
  4067. mg_free(*buf);
  4068. }
  4069. size *= 4;
  4070. *buf = (char *)mg_malloc(size);
  4071. if (!*buf) {
  4072. break;
  4073. }
  4074. va_copy(ap_copy, ap);
  4075. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4076. va_end(ap_copy);
  4077. (*buf)[size - 1] = 0;
  4078. }
  4079. return len;
  4080. }
  4081. /* Print message to buffer. If buffer is large enough to hold the message,
  4082. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4083. * and return allocated buffer. */
  4084. static int
  4085. alloc_vprintf(char **out_buf,
  4086. char *prealloc_buf,
  4087. size_t prealloc_size,
  4088. const char *fmt,
  4089. va_list ap)
  4090. {
  4091. va_list ap_copy;
  4092. int len;
  4093. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4094. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4095. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4096. * Therefore, we make two passes: on first pass, get required message
  4097. * length.
  4098. * On second pass, actually print the message. */
  4099. va_copy(ap_copy, ap);
  4100. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4101. va_end(ap_copy);
  4102. if (len < 0) {
  4103. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4104. * Switch to alternative code path that uses incremental allocations.
  4105. */
  4106. va_copy(ap_copy, ap);
  4107. len = alloc_vprintf2(out_buf, fmt, ap);
  4108. va_end(ap_copy);
  4109. } else if ((size_t)(len) >= prealloc_size) {
  4110. /* The pre-allocated buffer not large enough. */
  4111. /* Allocate a new buffer. */
  4112. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4113. if (!*out_buf) {
  4114. /* Allocation failed. Return -1 as "out of memory" error. */
  4115. return -1;
  4116. }
  4117. /* Buffer allocation successful. Store the string there. */
  4118. va_copy(ap_copy, ap);
  4119. IGNORE_UNUSED_RESULT(
  4120. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4121. va_end(ap_copy);
  4122. } else {
  4123. /* The pre-allocated buffer is large enough.
  4124. * Use it to store the string and return the address. */
  4125. va_copy(ap_copy, ap);
  4126. IGNORE_UNUSED_RESULT(
  4127. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4128. va_end(ap_copy);
  4129. *out_buf = prealloc_buf;
  4130. }
  4131. return len;
  4132. }
  4133. static int
  4134. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4135. {
  4136. char mem[MG_BUF_LEN];
  4137. char *buf = NULL;
  4138. int len;
  4139. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4140. len = mg_write(conn, buf, (size_t)len);
  4141. }
  4142. if (buf != mem && buf != NULL) {
  4143. mg_free(buf);
  4144. }
  4145. return len;
  4146. }
  4147. int
  4148. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4149. {
  4150. va_list ap;
  4151. int result;
  4152. va_start(ap, fmt);
  4153. result = mg_vprintf(conn, fmt, ap);
  4154. va_end(ap);
  4155. return result;
  4156. }
  4157. int
  4158. mg_url_decode(const char *src,
  4159. int src_len,
  4160. char *dst,
  4161. int dst_len,
  4162. int is_form_url_encoded)
  4163. {
  4164. int i, j, a, b;
  4165. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4166. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4167. if (i < src_len - 2 && src[i] == '%'
  4168. && isxdigit(*(const unsigned char *)(src + i + 1))
  4169. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4170. a = tolower(*(const unsigned char *)(src + i + 1));
  4171. b = tolower(*(const unsigned char *)(src + i + 2));
  4172. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4173. i += 2;
  4174. } else if (is_form_url_encoded && src[i] == '+') {
  4175. dst[j] = ' ';
  4176. } else {
  4177. dst[j] = src[i];
  4178. }
  4179. }
  4180. dst[j] = '\0'; /* Null-terminate the destination */
  4181. return (i >= src_len) ? j : -1;
  4182. }
  4183. int
  4184. mg_get_var(const char *data,
  4185. size_t data_len,
  4186. const char *name,
  4187. char *dst,
  4188. size_t dst_len)
  4189. {
  4190. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4191. }
  4192. int
  4193. mg_get_var2(const char *data,
  4194. size_t data_len,
  4195. const char *name,
  4196. char *dst,
  4197. size_t dst_len,
  4198. size_t occurrence)
  4199. {
  4200. const char *p, *e, *s;
  4201. size_t name_len;
  4202. int len;
  4203. if (dst == NULL || dst_len == 0) {
  4204. len = -2;
  4205. } else if (data == NULL || name == NULL || data_len == 0) {
  4206. len = -1;
  4207. dst[0] = '\0';
  4208. } else {
  4209. name_len = strlen(name);
  4210. e = data + data_len;
  4211. len = -1;
  4212. dst[0] = '\0';
  4213. /* data is "var1=val1&var2=val2...". Find variable first */
  4214. for (p = data; p + name_len < e; p++) {
  4215. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4216. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4217. /* Point p to variable value */
  4218. p += name_len + 1;
  4219. /* Point s to the end of the value */
  4220. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4221. if (s == NULL) {
  4222. s = e;
  4223. }
  4224. /* assert(s >= p); */
  4225. if (s < p) {
  4226. return -3;
  4227. }
  4228. /* Decode variable into destination buffer */
  4229. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4230. /* Redirect error code from -1 to -2 (destination buffer too
  4231. * small). */
  4232. if (len == -1) {
  4233. len = -2;
  4234. }
  4235. break;
  4236. }
  4237. }
  4238. }
  4239. return len;
  4240. }
  4241. /* HCP24: some changes to compare hole var_name */
  4242. int
  4243. mg_get_cookie(const char *cookie_header,
  4244. const char *var_name,
  4245. char *dst,
  4246. size_t dst_size)
  4247. {
  4248. const char *s, *p, *end;
  4249. int name_len, len = -1;
  4250. if (dst == NULL || dst_size == 0) {
  4251. return -2;
  4252. }
  4253. dst[0] = '\0';
  4254. if (var_name == NULL || (s = cookie_header) == NULL) {
  4255. return -1;
  4256. }
  4257. name_len = (int)strlen(var_name);
  4258. end = s + strlen(s);
  4259. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4260. if (s[name_len] == '=') {
  4261. /* HCP24: now check is it a substring or a full cookie name */
  4262. if ((s == cookie_header) || (s[-1] == ' ')) {
  4263. s += name_len + 1;
  4264. if ((p = strchr(s, ' ')) == NULL) {
  4265. p = end;
  4266. }
  4267. if (p[-1] == ';') {
  4268. p--;
  4269. }
  4270. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4271. s++;
  4272. p--;
  4273. }
  4274. if ((size_t)(p - s) < dst_size) {
  4275. len = (int)(p - s);
  4276. mg_strlcpy(dst, s, (size_t)len + 1);
  4277. } else {
  4278. len = -3;
  4279. }
  4280. break;
  4281. }
  4282. }
  4283. }
  4284. return len;
  4285. }
  4286. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4287. static void
  4288. base64_encode(const unsigned char *src, int src_len, char *dst)
  4289. {
  4290. static const char *b64 =
  4291. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4292. int i, j, a, b, c;
  4293. for (i = j = 0; i < src_len; i += 3) {
  4294. a = src[i];
  4295. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4296. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4297. dst[j++] = b64[a >> 2];
  4298. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4299. if (i + 1 < src_len) {
  4300. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4301. }
  4302. if (i + 2 < src_len) {
  4303. dst[j++] = b64[c & 63];
  4304. }
  4305. }
  4306. while (j % 4 != 0) {
  4307. dst[j++] = '=';
  4308. }
  4309. dst[j++] = '\0';
  4310. }
  4311. #endif
  4312. #if defined(USE_LUA)
  4313. static unsigned char
  4314. b64reverse(char letter)
  4315. {
  4316. if (letter >= 'A' && letter <= 'Z') {
  4317. return letter - 'A';
  4318. }
  4319. if (letter >= 'a' && letter <= 'z') {
  4320. return letter - 'a' + 26;
  4321. }
  4322. if (letter >= '0' && letter <= '9') {
  4323. return letter - '0' + 52;
  4324. }
  4325. if (letter == '+') {
  4326. return 62;
  4327. }
  4328. if (letter == '/') {
  4329. return 63;
  4330. }
  4331. if (letter == '=') {
  4332. return 255; /* normal end */
  4333. }
  4334. return 254; /* error */
  4335. }
  4336. static int
  4337. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4338. {
  4339. int i;
  4340. unsigned char a, b, c, d;
  4341. *dst_len = 0;
  4342. for (i = 0; i < src_len; i += 4) {
  4343. a = b64reverse(src[i]);
  4344. if (a >= 254) {
  4345. return i;
  4346. }
  4347. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4348. if (b >= 254) {
  4349. return i + 1;
  4350. }
  4351. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4352. if (c == 254) {
  4353. return i + 2;
  4354. }
  4355. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4356. if (d == 254) {
  4357. return i + 3;
  4358. }
  4359. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4360. if (c != 255) {
  4361. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4362. if (d != 255) {
  4363. dst[(*dst_len)++] = (c << 6) + d;
  4364. }
  4365. }
  4366. }
  4367. return -1;
  4368. }
  4369. #endif
  4370. static int
  4371. is_put_or_delete_method(const struct mg_connection *conn)
  4372. {
  4373. if (conn) {
  4374. const char *s = conn->request_info.request_method;
  4375. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4376. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4377. }
  4378. return 0;
  4379. }
  4380. static void
  4381. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4382. char *filename, /* out: filename */
  4383. size_t filename_buf_len, /* in: size of filename buffer */
  4384. struct file *filep, /* out: file structure */
  4385. int *is_found, /* out: file is found (directly) */
  4386. int *is_script_resource, /* out: handled by a script? */
  4387. int *is_websocket_request, /* out: websocket connetion? */
  4388. int *is_put_or_delete_request /* out: put/delete a file? */
  4389. )
  4390. {
  4391. /* TODO (high): Restructure this function */
  4392. #if !defined(NO_FILES)
  4393. const char *uri = conn->request_info.local_uri;
  4394. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4395. const char *rewrite;
  4396. struct vec a, b;
  4397. int match_len;
  4398. char gz_path[PATH_MAX];
  4399. char const *accept_encoding;
  4400. int truncated;
  4401. #if !defined(NO_CGI) || defined(USE_LUA)
  4402. char *p;
  4403. #endif
  4404. #else
  4405. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4406. #endif
  4407. memset(filep, 0, sizeof(*filep));
  4408. *filename = 0;
  4409. *is_found = 0;
  4410. *is_script_resource = 0;
  4411. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4412. #if defined(USE_WEBSOCKET)
  4413. *is_websocket_request = is_websocket_protocol(conn);
  4414. #if !defined(NO_FILES)
  4415. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4416. root = conn->ctx->config[WEBSOCKET_ROOT];
  4417. }
  4418. #endif /* !NO_FILES */
  4419. #else /* USE_WEBSOCKET */
  4420. *is_websocket_request = 0;
  4421. #endif /* USE_WEBSOCKET */
  4422. #if !defined(NO_FILES)
  4423. /* Note that root == NULL is a regular use case here. This occurs,
  4424. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4425. * config is not required. */
  4426. if (root == NULL) {
  4427. /* all file related outputs have already been set to 0, just return
  4428. */
  4429. return;
  4430. }
  4431. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4432. * of the path one byte on the right.
  4433. * If document_root is NULL, leave the file empty. */
  4434. mg_snprintf(
  4435. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4436. if (truncated) {
  4437. goto interpret_cleanup;
  4438. }
  4439. rewrite = conn->ctx->config[REWRITE];
  4440. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4441. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4442. mg_snprintf(conn,
  4443. &truncated,
  4444. filename,
  4445. filename_buf_len - 1,
  4446. "%.*s%s",
  4447. (int)b.len,
  4448. b.ptr,
  4449. uri + match_len);
  4450. break;
  4451. }
  4452. }
  4453. if (truncated) {
  4454. goto interpret_cleanup;
  4455. }
  4456. /* Local file path and name, corresponding to requested URI
  4457. * is now stored in "filename" variable. */
  4458. if (mg_stat(conn, filename, filep)) {
  4459. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4460. /* File exists. Check if it is a script type. */
  4461. if (0
  4462. #if !defined(NO_CGI)
  4463. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4464. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4465. filename) > 0
  4466. #endif
  4467. #if defined(USE_LUA)
  4468. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4469. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4470. filename) > 0
  4471. #endif
  4472. #if defined(USE_DUKTAPE)
  4473. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4474. strlen(
  4475. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4476. filename) > 0
  4477. #endif
  4478. ) {
  4479. /* The request addresses a CGI script or a Lua script. The URI
  4480. * corresponds to the script itself (like /path/script.cgi),
  4481. * and there is no additional resource path
  4482. * (like /path/script.cgi/something).
  4483. * Requests that modify (replace or delete) a resource, like
  4484. * PUT and DELETE requests, should replace/delete the script
  4485. * file.
  4486. * Requests that read or write from/to a resource, like GET and
  4487. * POST requests, should call the script and return the
  4488. * generated response. */
  4489. *is_script_resource = !*is_put_or_delete_request;
  4490. }
  4491. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4492. *is_found = 1;
  4493. return;
  4494. }
  4495. /* If we can't find the actual file, look for the file
  4496. * with the same name but a .gz extension. If we find it,
  4497. * use that and set the gzipped flag in the file struct
  4498. * to indicate that the response need to have the content-
  4499. * encoding: gzip header.
  4500. * We can only do this if the browser declares support. */
  4501. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4502. if (strstr(accept_encoding, "gzip") != NULL) {
  4503. mg_snprintf(
  4504. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4505. if (truncated) {
  4506. goto interpret_cleanup;
  4507. }
  4508. if (mg_stat(conn, gz_path, filep)) {
  4509. if (filep) {
  4510. filep->gzipped = 1;
  4511. *is_found = 1;
  4512. }
  4513. /* Currently gz files can not be scripts. */
  4514. return;
  4515. }
  4516. }
  4517. }
  4518. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4519. /* Support PATH_INFO for CGI scripts. */
  4520. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4521. if (*p == '/') {
  4522. *p = '\0';
  4523. if ((0
  4524. #if !defined(NO_CGI)
  4525. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4526. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4527. filename) > 0
  4528. #endif
  4529. #if defined(USE_LUA)
  4530. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4531. strlen(
  4532. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4533. filename) > 0
  4534. #endif
  4535. #if defined(USE_DUKTAPE)
  4536. || match_prefix(
  4537. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4538. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4539. filename) > 0
  4540. #endif
  4541. ) && mg_stat(conn, filename, filep)) {
  4542. /* Shift PATH_INFO block one character right, e.g.
  4543. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4544. * conn->path_info is pointing to the local variable "path"
  4545. * declared in handle_request(), so PATH_INFO is not valid
  4546. * after handle_request returns. */
  4547. conn->path_info = p + 1;
  4548. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4549. * trailing \0 */
  4550. p[1] = '/';
  4551. *is_script_resource = 1;
  4552. break;
  4553. } else {
  4554. *p = '/';
  4555. }
  4556. }
  4557. }
  4558. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4559. #endif /* !defined(NO_FILES) */
  4560. return;
  4561. #if !defined(NO_FILES)
  4562. /* Reset all outputs */
  4563. interpret_cleanup:
  4564. memset(filep, 0, sizeof(*filep));
  4565. *filename = 0;
  4566. *is_found = 0;
  4567. *is_script_resource = 0;
  4568. *is_websocket_request = 0;
  4569. *is_put_or_delete_request = 0;
  4570. #endif /* !defined(NO_FILES) */
  4571. }
  4572. /* Check whether full request is buffered. Return:
  4573. * -1 if request is malformed
  4574. * 0 if request is not yet fully buffered
  4575. * >0 actual request length, including last \r\n\r\n */
  4576. static int
  4577. get_request_len(const char *buf, int buflen)
  4578. {
  4579. const char *s, *e;
  4580. int len = 0;
  4581. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4582. /* Control characters are not allowed but >=128 is. */
  4583. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4584. && *(const unsigned char *)s < 128) {
  4585. len = -1;
  4586. break; /* [i_a] abort scan as soon as one malformed character is
  4587. * found; */
  4588. /* don't let subsequent \r\n\r\n win us over anyhow */
  4589. } else if (s[0] == '\n' && s[1] == '\n') {
  4590. len = (int)(s - buf) + 2;
  4591. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4592. len = (int)(s - buf) + 3;
  4593. }
  4594. return len;
  4595. }
  4596. #if !defined(NO_CACHING)
  4597. /* Convert month to the month number. Return -1 on error, or month number */
  4598. static int
  4599. get_month_index(const char *s)
  4600. {
  4601. size_t i;
  4602. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4603. if (!strcmp(s, month_names[i])) {
  4604. return (int)i;
  4605. }
  4606. }
  4607. return -1;
  4608. }
  4609. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4610. static time_t
  4611. parse_date_string(const char *datetime)
  4612. {
  4613. char month_str[32] = {0};
  4614. int second, minute, hour, day, month, year;
  4615. time_t result = (time_t)0;
  4616. struct tm tm;
  4617. if ((sscanf(datetime,
  4618. "%d/%3s/%d %d:%d:%d",
  4619. &day,
  4620. month_str,
  4621. &year,
  4622. &hour,
  4623. &minute,
  4624. &second) == 6) || (sscanf(datetime,
  4625. "%d %3s %d %d:%d:%d",
  4626. &day,
  4627. month_str,
  4628. &year,
  4629. &hour,
  4630. &minute,
  4631. &second) == 6)
  4632. || (sscanf(datetime,
  4633. "%*3s, %d %3s %d %d:%d:%d",
  4634. &day,
  4635. month_str,
  4636. &year,
  4637. &hour,
  4638. &minute,
  4639. &second) == 6) || (sscanf(datetime,
  4640. "%d-%3s-%d %d:%d:%d",
  4641. &day,
  4642. month_str,
  4643. &year,
  4644. &hour,
  4645. &minute,
  4646. &second) == 6)) {
  4647. month = get_month_index(month_str);
  4648. if ((month >= 0) && (year >= 1970)) {
  4649. memset(&tm, 0, sizeof(tm));
  4650. tm.tm_year = year - 1900;
  4651. tm.tm_mon = month;
  4652. tm.tm_mday = day;
  4653. tm.tm_hour = hour;
  4654. tm.tm_min = minute;
  4655. tm.tm_sec = second;
  4656. result = timegm(&tm);
  4657. }
  4658. }
  4659. return result;
  4660. }
  4661. #endif /* !NO_CACHING */
  4662. /* Protect against directory disclosure attack by removing '..',
  4663. * excessive '/' and '\' characters */
  4664. static void
  4665. remove_double_dots_and_double_slashes(char *s)
  4666. {
  4667. char *p = s;
  4668. while ((s[0] == '.') && (s[1] == '.')) {
  4669. s++;
  4670. }
  4671. while (*s != '\0') {
  4672. *p++ = *s++;
  4673. if (s[-1] == '/' || s[-1] == '\\') {
  4674. /* Skip all following slashes, backslashes and double-dots */
  4675. while (s[0] != '\0') {
  4676. if (s[0] == '/' || s[0] == '\\') {
  4677. s++;
  4678. } else if (s[0] == '.' && s[1] == '.') {
  4679. s += 2;
  4680. } else {
  4681. break;
  4682. }
  4683. }
  4684. }
  4685. }
  4686. *p = '\0';
  4687. }
  4688. static const struct {
  4689. const char *extension;
  4690. size_t ext_len;
  4691. const char *mime_type;
  4692. } builtin_mime_types[] = {
  4693. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4694. * application types */
  4695. {".doc", 4, "application/msword"},
  4696. {".eps", 4, "application/postscript"},
  4697. {".exe", 4, "application/octet-stream"},
  4698. {".js", 3, "application/javascript"},
  4699. {".json", 5, "application/json"},
  4700. {".pdf", 4, "application/pdf"},
  4701. {".ps", 3, "application/postscript"},
  4702. {".rtf", 4, "application/rtf"},
  4703. {".xhtml", 6, "application/xhtml+xml"},
  4704. {".xsl", 4, "application/xml"},
  4705. {".xslt", 5, "application/xml"},
  4706. /* fonts */
  4707. {".ttf", 4, "application/font-sfnt"},
  4708. {".cff", 4, "application/font-sfnt"},
  4709. {".otf", 4, "application/font-sfnt"},
  4710. {".aat", 4, "application/font-sfnt"},
  4711. {".sil", 4, "application/font-sfnt"},
  4712. {".pfr", 4, "application/font-tdpfr"},
  4713. {".woff", 5, "application/font-woff"},
  4714. /* audio */
  4715. {".mp3", 4, "audio/mpeg"},
  4716. {".oga", 4, "audio/ogg"},
  4717. {".ogg", 4, "audio/ogg"},
  4718. /* image */
  4719. {".gif", 4, "image/gif"},
  4720. {".ief", 4, "image/ief"},
  4721. {".jpeg", 5, "image/jpeg"},
  4722. {".jpg", 4, "image/jpeg"},
  4723. {".jpm", 4, "image/jpm"},
  4724. {".jpx", 4, "image/jpx"},
  4725. {".png", 4, "image/png"},
  4726. {".svg", 4, "image/svg+xml"},
  4727. {".tif", 4, "image/tiff"},
  4728. {".tiff", 5, "image/tiff"},
  4729. /* model */
  4730. {".wrl", 4, "model/vrml"},
  4731. /* text */
  4732. {".css", 4, "text/css"},
  4733. {".csv", 4, "text/csv"},
  4734. {".htm", 4, "text/html"},
  4735. {".html", 5, "text/html"},
  4736. {".sgm", 4, "text/sgml"},
  4737. {".shtm", 5, "text/html"},
  4738. {".shtml", 6, "text/html"},
  4739. {".txt", 4, "text/plain"},
  4740. {".xml", 4, "text/xml"},
  4741. /* video */
  4742. {".mov", 4, "video/quicktime"},
  4743. {".mp4", 4, "video/mp4"},
  4744. {".mpeg", 5, "video/mpeg"},
  4745. {".mpg", 4, "video/mpeg"},
  4746. {".ogv", 4, "video/ogg"},
  4747. {".qt", 3, "video/quicktime"},
  4748. /* not registered types
  4749. * (http://reference.sitepoint.com/html/mime-types-full,
  4750. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4751. {".arj", 4, "application/x-arj-compressed"},
  4752. {".gz", 3, "application/x-gunzip"},
  4753. {".rar", 4, "application/x-arj-compressed"},
  4754. {".swf", 4, "application/x-shockwave-flash"},
  4755. {".tar", 4, "application/x-tar"},
  4756. {".tgz", 4, "application/x-tar-gz"},
  4757. {".torrent", 8, "application/x-bittorrent"},
  4758. {".ppt", 4, "application/x-mspowerpoint"},
  4759. {".xls", 4, "application/x-msexcel"},
  4760. {".zip", 4, "application/x-zip-compressed"},
  4761. {".aac",
  4762. 4,
  4763. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4764. {".aif", 4, "audio/x-aif"},
  4765. {".m3u", 4, "audio/x-mpegurl"},
  4766. {".mid", 4, "audio/x-midi"},
  4767. {".ra", 3, "audio/x-pn-realaudio"},
  4768. {".ram", 4, "audio/x-pn-realaudio"},
  4769. {".wav", 4, "audio/x-wav"},
  4770. {".bmp", 4, "image/bmp"},
  4771. {".ico", 4, "image/x-icon"},
  4772. {".pct", 4, "image/x-pct"},
  4773. {".pict", 5, "image/pict"},
  4774. {".rgb", 4, "image/x-rgb"},
  4775. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4776. {".asf", 4, "video/x-ms-asf"},
  4777. {".avi", 4, "video/x-msvideo"},
  4778. {".m4v", 4, "video/x-m4v"},
  4779. {NULL, 0, NULL}};
  4780. const char *
  4781. mg_get_builtin_mime_type(const char *path)
  4782. {
  4783. const char *ext;
  4784. size_t i, path_len;
  4785. path_len = strlen(path);
  4786. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4787. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4788. if (path_len > builtin_mime_types[i].ext_len
  4789. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4790. return builtin_mime_types[i].mime_type;
  4791. }
  4792. }
  4793. return "text/plain";
  4794. }
  4795. /* Look at the "path" extension and figure what mime type it has.
  4796. * Store mime type in the vector. */
  4797. static void
  4798. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4799. {
  4800. struct vec ext_vec, mime_vec;
  4801. const char *list, *ext;
  4802. size_t path_len;
  4803. path_len = strlen(path);
  4804. if (ctx == NULL || vec == NULL) {
  4805. return;
  4806. }
  4807. /* Scan user-defined mime types first, in case user wants to
  4808. * override default mime types. */
  4809. list = ctx->config[EXTRA_MIME_TYPES];
  4810. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4811. /* ext now points to the path suffix */
  4812. ext = path + path_len - ext_vec.len;
  4813. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4814. *vec = mime_vec;
  4815. return;
  4816. }
  4817. }
  4818. vec->ptr = mg_get_builtin_mime_type(path);
  4819. vec->len = strlen(vec->ptr);
  4820. }
  4821. /* Stringify binary data. Output buffer must be twice as big as input,
  4822. * because each byte takes 2 bytes in string representation */
  4823. static void
  4824. bin2str(char *to, const unsigned char *p, size_t len)
  4825. {
  4826. static const char *hex = "0123456789abcdef";
  4827. for (; len--; p++) {
  4828. *to++ = hex[p[0] >> 4];
  4829. *to++ = hex[p[0] & 0x0f];
  4830. }
  4831. *to = '\0';
  4832. }
  4833. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4834. char *
  4835. mg_md5(char buf[33], ...)
  4836. {
  4837. md5_byte_t hash[16];
  4838. const char *p;
  4839. va_list ap;
  4840. md5_state_t ctx;
  4841. md5_init(&ctx);
  4842. va_start(ap, buf);
  4843. while ((p = va_arg(ap, const char *)) != NULL) {
  4844. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4845. }
  4846. va_end(ap);
  4847. md5_finish(&ctx, hash);
  4848. bin2str(buf, hash, sizeof(hash));
  4849. return buf;
  4850. }
  4851. /* Check the user's password, return 1 if OK */
  4852. static int
  4853. check_password(const char *method,
  4854. const char *ha1,
  4855. const char *uri,
  4856. const char *nonce,
  4857. const char *nc,
  4858. const char *cnonce,
  4859. const char *qop,
  4860. const char *response)
  4861. {
  4862. char ha2[32 + 1], expected_response[32 + 1];
  4863. /* Some of the parameters may be NULL */
  4864. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4865. || qop == NULL
  4866. || response == NULL) {
  4867. return 0;
  4868. }
  4869. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4870. if (strlen(response) != 32) {
  4871. return 0;
  4872. }
  4873. mg_md5(ha2, method, ":", uri, NULL);
  4874. mg_md5(expected_response,
  4875. ha1,
  4876. ":",
  4877. nonce,
  4878. ":",
  4879. nc,
  4880. ":",
  4881. cnonce,
  4882. ":",
  4883. qop,
  4884. ":",
  4885. ha2,
  4886. NULL);
  4887. return mg_strcasecmp(response, expected_response) == 0;
  4888. }
  4889. /* Use the global passwords file, if specified by auth_gpass option,
  4890. * or search for .htpasswd in the requested directory. */
  4891. static void
  4892. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4893. {
  4894. if (conn != NULL && conn->ctx != NULL) {
  4895. char name[PATH_MAX];
  4896. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4897. struct file file = STRUCT_FILE_INITIALIZER;
  4898. int truncated;
  4899. if (gpass != NULL) {
  4900. /* Use global passwords file */
  4901. if (!mg_fopen(conn, gpass, "r", filep)) {
  4902. #ifdef DEBUG
  4903. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4904. #endif
  4905. }
  4906. /* Important: using local struct file to test path for is_directory
  4907. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4908. * was opened. */
  4909. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4910. mg_snprintf(conn,
  4911. &truncated,
  4912. name,
  4913. sizeof(name),
  4914. "%s/%s",
  4915. path,
  4916. PASSWORDS_FILE_NAME);
  4917. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4918. #ifdef DEBUG
  4919. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4920. #endif
  4921. }
  4922. } else {
  4923. /* Try to find .htpasswd in requested directory. */
  4924. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4925. if (e[0] == '/') {
  4926. break;
  4927. }
  4928. }
  4929. mg_snprintf(conn,
  4930. &truncated,
  4931. name,
  4932. sizeof(name),
  4933. "%.*s/%s",
  4934. (int)(e - p),
  4935. p,
  4936. PASSWORDS_FILE_NAME);
  4937. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4938. #ifdef DEBUG
  4939. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4940. #endif
  4941. }
  4942. }
  4943. }
  4944. }
  4945. /* Parsed Authorization header */
  4946. struct ah {
  4947. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4948. };
  4949. /* Return 1 on success. Always initializes the ah structure. */
  4950. static int
  4951. parse_auth_header(struct mg_connection *conn,
  4952. char *buf,
  4953. size_t buf_size,
  4954. struct ah *ah)
  4955. {
  4956. char *name, *value, *s;
  4957. const char *auth_header;
  4958. uint64_t nonce;
  4959. if (!ah || !conn) {
  4960. return 0;
  4961. }
  4962. (void)memset(ah, 0, sizeof(*ah));
  4963. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4964. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4965. return 0;
  4966. }
  4967. /* Make modifiable copy of the auth header */
  4968. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4969. s = buf;
  4970. /* Parse authorization header */
  4971. for (;;) {
  4972. /* Gobble initial spaces */
  4973. while (isspace(*(unsigned char *)s)) {
  4974. s++;
  4975. }
  4976. name = skip_quoted(&s, "=", " ", 0);
  4977. /* Value is either quote-delimited, or ends at first comma or space. */
  4978. if (s[0] == '\"') {
  4979. s++;
  4980. value = skip_quoted(&s, "\"", " ", '\\');
  4981. if (s[0] == ',') {
  4982. s++;
  4983. }
  4984. } else {
  4985. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4986. * spaces */
  4987. }
  4988. if (*name == '\0') {
  4989. break;
  4990. }
  4991. if (!strcmp(name, "username")) {
  4992. ah->user = value;
  4993. } else if (!strcmp(name, "cnonce")) {
  4994. ah->cnonce = value;
  4995. } else if (!strcmp(name, "response")) {
  4996. ah->response = value;
  4997. } else if (!strcmp(name, "uri")) {
  4998. ah->uri = value;
  4999. } else if (!strcmp(name, "qop")) {
  5000. ah->qop = value;
  5001. } else if (!strcmp(name, "nc")) {
  5002. ah->nc = value;
  5003. } else if (!strcmp(name, "nonce")) {
  5004. ah->nonce = value;
  5005. }
  5006. }
  5007. #ifndef NO_NONCE_CHECK
  5008. /* Read the nonce from the response. */
  5009. if (ah->nonce == NULL) {
  5010. return 0;
  5011. }
  5012. s = NULL;
  5013. nonce = strtoull(ah->nonce, &s, 10);
  5014. if ((s == NULL) || (*s != 0)) {
  5015. return 0;
  5016. }
  5017. /* Convert the nonce from the client to a number. */
  5018. nonce ^= conn->ctx->auth_nonce_mask;
  5019. /* The converted number corresponds to the time the nounce has been
  5020. * created. This should not be earlier than the server start. */
  5021. /* Server side nonce check is valuable in all situations but one:
  5022. * if the server restarts frequently, but the client should not see
  5023. * that, so the server should accept nonces from previous starts. */
  5024. /* However, the reasonable default is to not accept a nonce from a
  5025. * previous start, so if anyone changed the access rights between
  5026. * two restarts, a new login is required. */
  5027. if (nonce < (uint64_t)conn->ctx->start_time) {
  5028. /* nonce is from a previous start of the server and no longer valid
  5029. * (replay attack?) */
  5030. return 0;
  5031. }
  5032. /* Check if the nonce is too high, so it has not (yet) been used by the
  5033. * server. */
  5034. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5035. return 0;
  5036. }
  5037. #else
  5038. (void)nonce;
  5039. #endif
  5040. /* CGI needs it as REMOTE_USER */
  5041. if (ah->user != NULL) {
  5042. conn->request_info.remote_user = mg_strdup(ah->user);
  5043. } else {
  5044. return 0;
  5045. }
  5046. return 1;
  5047. }
  5048. static const char *
  5049. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  5050. {
  5051. const char *eof;
  5052. size_t len;
  5053. const char *memend;
  5054. if (!filep) {
  5055. return NULL;
  5056. }
  5057. if (filep->membuf != NULL && *p != NULL) {
  5058. memend = (const char *)&filep->membuf[filep->size];
  5059. /* Search for \n from p till the end of stream */
  5060. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5061. if (eof != NULL) {
  5062. eof += 1; /* Include \n */
  5063. } else {
  5064. eof = memend; /* Copy remaining data */
  5065. }
  5066. len =
  5067. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5068. memcpy(buf, *p, len);
  5069. buf[len] = '\0';
  5070. *p += len;
  5071. return len ? eof : NULL;
  5072. } else if (filep->fp != NULL) {
  5073. return fgets(buf, (int)size, filep->fp);
  5074. } else {
  5075. return NULL;
  5076. }
  5077. }
  5078. struct read_auth_file_struct {
  5079. struct mg_connection *conn;
  5080. struct ah ah;
  5081. char *domain;
  5082. char buf[256 + 256 + 40];
  5083. char *f_user;
  5084. char *f_domain;
  5085. char *f_ha1;
  5086. };
  5087. static int
  5088. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  5089. {
  5090. char *p;
  5091. int is_authorized = 0;
  5092. struct file fp;
  5093. size_t l;
  5094. if (!filep || !workdata) {
  5095. return 0;
  5096. }
  5097. /* Loop over passwords file */
  5098. p = (char *)filep->membuf;
  5099. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5100. l = strlen(workdata->buf);
  5101. while (l > 0) {
  5102. if (isspace(workdata->buf[l - 1])
  5103. || iscntrl(workdata->buf[l - 1])) {
  5104. l--;
  5105. workdata->buf[l] = 0;
  5106. } else
  5107. break;
  5108. }
  5109. if (l < 1) {
  5110. continue;
  5111. }
  5112. workdata->f_user = workdata->buf;
  5113. if (workdata->f_user[0] == ':') {
  5114. /* user names may not contain a ':' and may not be empty,
  5115. * so lines starting with ':' may be used for a special purpose */
  5116. if (workdata->f_user[1] == '#') {
  5117. /* :# is a comment */
  5118. continue;
  5119. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5120. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  5121. is_authorized = read_auth_file(&fp, workdata);
  5122. mg_fclose(&fp);
  5123. } else {
  5124. mg_cry(workdata->conn,
  5125. "%s: cannot open authorization file: %s",
  5126. __func__,
  5127. workdata->buf);
  5128. }
  5129. continue;
  5130. }
  5131. /* everything is invalid for the moment (might change in the
  5132. * future) */
  5133. mg_cry(workdata->conn,
  5134. "%s: syntax error in authorization file: %s",
  5135. __func__,
  5136. workdata->buf);
  5137. continue;
  5138. }
  5139. workdata->f_domain = strchr(workdata->f_user, ':');
  5140. if (workdata->f_domain == NULL) {
  5141. mg_cry(workdata->conn,
  5142. "%s: syntax error in authorization file: %s",
  5143. __func__,
  5144. workdata->buf);
  5145. continue;
  5146. }
  5147. *(workdata->f_domain) = 0;
  5148. (workdata->f_domain)++;
  5149. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5150. if (workdata->f_ha1 == NULL) {
  5151. mg_cry(workdata->conn,
  5152. "%s: syntax error in authorization file: %s",
  5153. __func__,
  5154. workdata->buf);
  5155. continue;
  5156. }
  5157. *(workdata->f_ha1) = 0;
  5158. (workdata->f_ha1)++;
  5159. if (!strcmp(workdata->ah.user, workdata->f_user)
  5160. && !strcmp(workdata->domain, workdata->f_domain)) {
  5161. return check_password(workdata->conn->request_info.request_method,
  5162. workdata->f_ha1,
  5163. workdata->ah.uri,
  5164. workdata->ah.nonce,
  5165. workdata->ah.nc,
  5166. workdata->ah.cnonce,
  5167. workdata->ah.qop,
  5168. workdata->ah.response);
  5169. }
  5170. }
  5171. return is_authorized;
  5172. }
  5173. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5174. static int
  5175. authorize(struct mg_connection *conn, struct file *filep)
  5176. {
  5177. struct read_auth_file_struct workdata;
  5178. char buf[MG_BUF_LEN];
  5179. if (!conn || !conn->ctx) {
  5180. return 0;
  5181. }
  5182. memset(&workdata, 0, sizeof(workdata));
  5183. workdata.conn = conn;
  5184. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5185. return 0;
  5186. }
  5187. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5188. return read_auth_file(filep, &workdata);
  5189. }
  5190. /* Return 1 if request is authorised, 0 otherwise. */
  5191. static int
  5192. check_authorization(struct mg_connection *conn, const char *path)
  5193. {
  5194. char fname[PATH_MAX];
  5195. struct vec uri_vec, filename_vec;
  5196. const char *list;
  5197. struct file file = STRUCT_FILE_INITIALIZER;
  5198. int authorized = 1, truncated;
  5199. if (!conn || !conn->ctx) {
  5200. return 0;
  5201. }
  5202. list = conn->ctx->config[PROTECT_URI];
  5203. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5204. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5205. mg_snprintf(conn,
  5206. &truncated,
  5207. fname,
  5208. sizeof(fname),
  5209. "%.*s",
  5210. (int)filename_vec.len,
  5211. filename_vec.ptr);
  5212. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5213. mg_cry(conn,
  5214. "%s: cannot open %s: %s",
  5215. __func__,
  5216. fname,
  5217. strerror(errno));
  5218. }
  5219. break;
  5220. }
  5221. }
  5222. if (!is_file_opened(&file)) {
  5223. open_auth_file(conn, path, &file);
  5224. }
  5225. if (is_file_opened(&file)) {
  5226. authorized = authorize(conn, &file);
  5227. mg_fclose(&file);
  5228. }
  5229. return authorized;
  5230. }
  5231. static void
  5232. send_authorization_request(struct mg_connection *conn)
  5233. {
  5234. char date[64];
  5235. time_t curtime = time(NULL);
  5236. if (conn && conn->ctx) {
  5237. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5238. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5239. nonce += conn->ctx->nonce_count;
  5240. ++conn->ctx->nonce_count;
  5241. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5242. nonce ^= conn->ctx->auth_nonce_mask;
  5243. conn->status_code = 401;
  5244. conn->must_close = 1;
  5245. gmt_time_string(date, sizeof(date), &curtime);
  5246. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5247. send_no_cache_header(conn);
  5248. mg_printf(conn,
  5249. "Date: %s\r\n"
  5250. "Connection: %s\r\n"
  5251. "Content-Length: 0\r\n"
  5252. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5253. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5254. date,
  5255. suggest_connection_header(conn),
  5256. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5257. nonce);
  5258. }
  5259. }
  5260. #if !defined(NO_FILES)
  5261. static int
  5262. is_authorized_for_put(struct mg_connection *conn)
  5263. {
  5264. if (conn) {
  5265. struct file file = STRUCT_FILE_INITIALIZER;
  5266. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5267. int ret = 0;
  5268. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5269. ret = authorize(conn, &file);
  5270. mg_fclose(&file);
  5271. }
  5272. return ret;
  5273. }
  5274. return 0;
  5275. }
  5276. #endif
  5277. int
  5278. mg_modify_passwords_file(const char *fname,
  5279. const char *domain,
  5280. const char *user,
  5281. const char *pass)
  5282. {
  5283. int found, i;
  5284. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5285. FILE *fp, *fp2;
  5286. found = 0;
  5287. fp = fp2 = NULL;
  5288. /* Regard empty password as no password - remove user record. */
  5289. if (pass != NULL && pass[0] == '\0') {
  5290. pass = NULL;
  5291. }
  5292. /* Other arguments must not be empty */
  5293. if (fname == NULL || domain == NULL || user == NULL) {
  5294. return 0;
  5295. }
  5296. /* Using the given file format, user name and domain must not contain ':'
  5297. */
  5298. if (strchr(user, ':') != NULL) {
  5299. return 0;
  5300. }
  5301. if (strchr(domain, ':') != NULL) {
  5302. return 0;
  5303. }
  5304. /* Do not allow control characters like newline in user name and domain.
  5305. * Do not allow excessively long names either. */
  5306. for (i = 0; i < 255 && user[i] != 0; i++) {
  5307. if (iscntrl(user[i])) {
  5308. return 0;
  5309. }
  5310. }
  5311. if (user[i]) {
  5312. return 0;
  5313. }
  5314. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5315. if (iscntrl(domain[i])) {
  5316. return 0;
  5317. }
  5318. }
  5319. if (domain[i]) {
  5320. return 0;
  5321. }
  5322. /* The maximum length of the path to the password file is limited */
  5323. if ((strlen(fname) + 4) >= PATH_MAX) {
  5324. return 0;
  5325. }
  5326. /* Create a temporary file name. Length has been checked before. */
  5327. strcpy(tmp, fname);
  5328. strcat(tmp, ".tmp");
  5329. /* Create the file if does not exist */
  5330. /* Use of fopen here is OK, since fname is only ASCII */
  5331. if ((fp = fopen(fname, "a+")) != NULL) {
  5332. (void)fclose(fp);
  5333. }
  5334. /* Open the given file and temporary file */
  5335. if ((fp = fopen(fname, "r")) == NULL) {
  5336. return 0;
  5337. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5338. fclose(fp);
  5339. return 0;
  5340. }
  5341. /* Copy the stuff to temporary file */
  5342. while (fgets(line, sizeof(line), fp) != NULL) {
  5343. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5344. continue;
  5345. }
  5346. u[255] = 0;
  5347. d[255] = 0;
  5348. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5349. found++;
  5350. if (pass != NULL) {
  5351. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5352. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5353. }
  5354. } else {
  5355. fprintf(fp2, "%s", line);
  5356. }
  5357. }
  5358. /* If new user, just add it */
  5359. if (!found && pass != NULL) {
  5360. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5361. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5362. }
  5363. /* Close files */
  5364. fclose(fp);
  5365. fclose(fp2);
  5366. /* Put the temp file in place of real file */
  5367. IGNORE_UNUSED_RESULT(remove(fname));
  5368. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5369. return 1;
  5370. }
  5371. static int
  5372. is_valid_port(unsigned long port)
  5373. {
  5374. return port < 0xffff;
  5375. }
  5376. static int
  5377. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5378. {
  5379. struct addrinfo hints, *res, *ressave;
  5380. int func_ret = 0;
  5381. int gai_ret;
  5382. memset(&hints, 0, sizeof(struct addrinfo));
  5383. hints.ai_family = af;
  5384. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5385. if (gai_ret != 0) {
  5386. /* gai_strerror could be used to convert gai_ret to a string */
  5387. /* POSIX return values: see
  5388. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5389. */
  5390. /* Windows return values: see
  5391. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5392. */
  5393. return 0;
  5394. }
  5395. ressave = res;
  5396. while (res) {
  5397. if (dstlen >= res->ai_addrlen) {
  5398. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5399. func_ret = 1;
  5400. }
  5401. res = res->ai_next;
  5402. }
  5403. freeaddrinfo(ressave);
  5404. return func_ret;
  5405. }
  5406. static int
  5407. connect_socket(struct mg_context *ctx /* may be NULL */,
  5408. const char *host,
  5409. int port,
  5410. int use_ssl,
  5411. char *ebuf,
  5412. size_t ebuf_len,
  5413. SOCKET *sock /* output: socket, must not be NULL */,
  5414. union usa *sa /* output: socket address, must not be NULL */
  5415. )
  5416. {
  5417. int ip_ver = 0;
  5418. *sock = INVALID_SOCKET;
  5419. memset(sa, 0, sizeof(*sa));
  5420. if (ebuf_len > 0) {
  5421. *ebuf = 0;
  5422. }
  5423. if (host == NULL) {
  5424. mg_snprintf(NULL,
  5425. NULL, /* No truncation check for ebuf */
  5426. ebuf,
  5427. ebuf_len,
  5428. "%s",
  5429. "NULL host");
  5430. return 0;
  5431. }
  5432. if (port < 0 || !is_valid_port((unsigned)port)) {
  5433. mg_snprintf(NULL,
  5434. NULL, /* No truncation check for ebuf */
  5435. ebuf,
  5436. ebuf_len,
  5437. "%s",
  5438. "invalid port");
  5439. return 0;
  5440. }
  5441. #if !defined(NO_SSL)
  5442. if (use_ssl && (SSLv23_client_method == NULL)) {
  5443. mg_snprintf(NULL,
  5444. NULL, /* No truncation check for ebuf */
  5445. ebuf,
  5446. ebuf_len,
  5447. "%s",
  5448. "SSL is not initialized");
  5449. return 0;
  5450. }
  5451. #else
  5452. (void)use_ssl;
  5453. #endif
  5454. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5455. sa->sin.sin_port = htons((uint16_t)port);
  5456. ip_ver = 4;
  5457. #ifdef USE_IPV6
  5458. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5459. sa->sin6.sin6_port = htons((uint16_t)port);
  5460. ip_ver = 6;
  5461. } else if (host[0] == '[') {
  5462. /* While getaddrinfo on Windows will work with [::1],
  5463. * getaddrinfo on Linux only works with ::1 (without []). */
  5464. size_t l = strlen(host + 1);
  5465. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5466. if (h) {
  5467. h[l - 1] = 0;
  5468. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5469. sa->sin6.sin6_port = htons((uint16_t)port);
  5470. ip_ver = 6;
  5471. }
  5472. mg_free(h);
  5473. }
  5474. #endif
  5475. }
  5476. if (ip_ver == 0) {
  5477. mg_snprintf(NULL,
  5478. NULL, /* No truncation check for ebuf */
  5479. ebuf,
  5480. ebuf_len,
  5481. "%s",
  5482. "host not found");
  5483. return 0;
  5484. }
  5485. if (ip_ver == 4) {
  5486. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5487. }
  5488. #ifdef USE_IPV6
  5489. else if (ip_ver == 6) {
  5490. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5491. }
  5492. #endif
  5493. if (*sock == INVALID_SOCKET) {
  5494. mg_snprintf(NULL,
  5495. NULL, /* No truncation check for ebuf */
  5496. ebuf,
  5497. ebuf_len,
  5498. "socket(): %s",
  5499. strerror(ERRNO));
  5500. return 0;
  5501. }
  5502. set_close_on_exec(*sock, fc(ctx));
  5503. if ((ip_ver == 4)
  5504. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5505. == 0)) {
  5506. /* connected with IPv4 */
  5507. set_non_blocking_mode(*sock);
  5508. return 1;
  5509. }
  5510. #ifdef USE_IPV6
  5511. if ((ip_ver == 6)
  5512. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5513. == 0)) {
  5514. /* connected with IPv6 */
  5515. set_non_blocking_mode(*sock);
  5516. return 1;
  5517. }
  5518. #endif
  5519. /* Not connected */
  5520. mg_snprintf(NULL,
  5521. NULL, /* No truncation check for ebuf */
  5522. ebuf,
  5523. ebuf_len,
  5524. "connect(%s:%d): %s",
  5525. host,
  5526. port,
  5527. strerror(ERRNO));
  5528. closesocket(*sock);
  5529. *sock = INVALID_SOCKET;
  5530. return 0;
  5531. }
  5532. int
  5533. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5534. {
  5535. static const char *dont_escape = "._-$,;~()";
  5536. static const char *hex = "0123456789abcdef";
  5537. char *pos = dst;
  5538. const char *end = dst + dst_len - 1;
  5539. for (; *src != '\0' && pos < end; src++, pos++) {
  5540. if (isalnum(*(const unsigned char *)src)
  5541. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5542. *pos = *src;
  5543. } else if (pos + 2 < end) {
  5544. pos[0] = '%';
  5545. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5546. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5547. pos += 2;
  5548. } else {
  5549. break;
  5550. }
  5551. }
  5552. *pos = '\0';
  5553. return (*src == '\0') ? (int)(pos - dst) : -1;
  5554. }
  5555. static void
  5556. print_dir_entry(struct de *de)
  5557. {
  5558. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5559. struct tm *tm;
  5560. if (de->file.is_directory) {
  5561. mg_snprintf(de->conn,
  5562. NULL, /* Buffer is big enough */
  5563. size,
  5564. sizeof(size),
  5565. "%s",
  5566. "[DIRECTORY]");
  5567. } else {
  5568. /* We use (signed) cast below because MSVC 6 compiler cannot
  5569. * convert unsigned __int64 to double. Sigh. */
  5570. if (de->file.size < 1024) {
  5571. mg_snprintf(de->conn,
  5572. NULL, /* Buffer is big enough */
  5573. size,
  5574. sizeof(size),
  5575. "%d",
  5576. (int)de->file.size);
  5577. } else if (de->file.size < 0x100000) {
  5578. mg_snprintf(de->conn,
  5579. NULL, /* Buffer is big enough */
  5580. size,
  5581. sizeof(size),
  5582. "%.1fk",
  5583. (double)de->file.size / 1024.0);
  5584. } else if (de->file.size < 0x40000000) {
  5585. mg_snprintf(de->conn,
  5586. NULL, /* Buffer is big enough */
  5587. size,
  5588. sizeof(size),
  5589. "%.1fM",
  5590. (double)de->file.size / 1048576);
  5591. } else {
  5592. mg_snprintf(de->conn,
  5593. NULL, /* Buffer is big enough */
  5594. size,
  5595. sizeof(size),
  5596. "%.1fG",
  5597. (double)de->file.size / 1073741824);
  5598. }
  5599. }
  5600. /* Note: mg_snprintf will not cause a buffer overflow above.
  5601. * So, string truncation checks are not required here. */
  5602. tm = localtime(&de->file.last_modified);
  5603. if (tm != NULL) {
  5604. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5605. } else {
  5606. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5607. mod[sizeof(mod) - 1] = '\0';
  5608. }
  5609. mg_url_encode(de->file_name, href, sizeof(href));
  5610. de->conn->num_bytes_sent +=
  5611. mg_printf(de->conn,
  5612. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5613. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5614. de->conn->request_info.local_uri,
  5615. href,
  5616. de->file.is_directory ? "/" : "",
  5617. de->file_name,
  5618. de->file.is_directory ? "/" : "",
  5619. mod,
  5620. size);
  5621. }
  5622. /* This function is called from send_directory() and used for
  5623. * sorting directory entries by size, or name, or modification time.
  5624. * On windows, __cdecl specification is needed in case if project is built
  5625. * with __stdcall convention. qsort always requires __cdels callback. */
  5626. static int WINCDECL
  5627. compare_dir_entries(const void *p1, const void *p2)
  5628. {
  5629. if (p1 && p2) {
  5630. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5631. const char *query_string = a->conn->request_info.query_string;
  5632. int cmp_result = 0;
  5633. if (query_string == NULL) {
  5634. query_string = "na";
  5635. }
  5636. if (a->file.is_directory && !b->file.is_directory) {
  5637. return -1; /* Always put directories on top */
  5638. } else if (!a->file.is_directory && b->file.is_directory) {
  5639. return 1; /* Always put directories on top */
  5640. } else if (*query_string == 'n') {
  5641. cmp_result = strcmp(a->file_name, b->file_name);
  5642. } else if (*query_string == 's') {
  5643. cmp_result = (a->file.size == b->file.size)
  5644. ? 0
  5645. : ((a->file.size > b->file.size) ? 1 : -1);
  5646. } else if (*query_string == 'd') {
  5647. cmp_result =
  5648. (a->file.last_modified == b->file.last_modified)
  5649. ? 0
  5650. : ((a->file.last_modified > b->file.last_modified) ? 1
  5651. : -1);
  5652. }
  5653. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5654. }
  5655. return 0;
  5656. }
  5657. static int
  5658. must_hide_file(struct mg_connection *conn, const char *path)
  5659. {
  5660. if (conn && conn->ctx) {
  5661. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5662. const char *pattern = conn->ctx->config[HIDE_FILES];
  5663. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5664. || (pattern != NULL
  5665. && match_prefix(pattern, strlen(pattern), path) > 0);
  5666. }
  5667. return 0;
  5668. }
  5669. static int
  5670. scan_directory(struct mg_connection *conn,
  5671. const char *dir,
  5672. void *data,
  5673. void (*cb)(struct de *, void *))
  5674. {
  5675. char path[PATH_MAX];
  5676. struct dirent *dp;
  5677. DIR *dirp;
  5678. struct de de;
  5679. int truncated;
  5680. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5681. return 0;
  5682. } else {
  5683. de.conn = conn;
  5684. while ((dp = mg_readdir(dirp)) != NULL) {
  5685. /* Do not show current dir and hidden files */
  5686. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5687. || must_hide_file(conn, dp->d_name)) {
  5688. continue;
  5689. }
  5690. mg_snprintf(
  5691. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5692. /* If we don't memset stat structure to zero, mtime will have
  5693. * garbage and strftime() will segfault later on in
  5694. * print_dir_entry(). memset is required only if mg_stat()
  5695. * fails. For more details, see
  5696. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5697. memset(&de.file, 0, sizeof(de.file));
  5698. if (truncated) {
  5699. /* If the path is not complete, skip processing. */
  5700. continue;
  5701. }
  5702. if (!mg_stat(conn, path, &de.file)) {
  5703. mg_cry(conn,
  5704. "%s: mg_stat(%s) failed: %s",
  5705. __func__,
  5706. path,
  5707. strerror(ERRNO));
  5708. }
  5709. de.file_name = dp->d_name;
  5710. cb(&de, data);
  5711. }
  5712. (void)mg_closedir(dirp);
  5713. }
  5714. return 1;
  5715. }
  5716. #if !defined(NO_FILES)
  5717. static int
  5718. remove_directory(struct mg_connection *conn, const char *dir)
  5719. {
  5720. char path[PATH_MAX];
  5721. struct dirent *dp;
  5722. DIR *dirp;
  5723. struct de de;
  5724. int truncated;
  5725. int ok = 1;
  5726. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5727. return 0;
  5728. } else {
  5729. de.conn = conn;
  5730. while ((dp = mg_readdir(dirp)) != NULL) {
  5731. /* Do not show current dir (but show hidden files as they will
  5732. * also be removed) */
  5733. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5734. continue;
  5735. }
  5736. mg_snprintf(
  5737. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5738. /* If we don't memset stat structure to zero, mtime will have
  5739. * garbage and strftime() will segfault later on in
  5740. * print_dir_entry(). memset is required only if mg_stat()
  5741. * fails. For more details, see
  5742. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5743. memset(&de.file, 0, sizeof(de.file));
  5744. if (truncated) {
  5745. /* Do not delete anything shorter */
  5746. ok = 0;
  5747. continue;
  5748. }
  5749. if (!mg_stat(conn, path, &de.file)) {
  5750. mg_cry(conn,
  5751. "%s: mg_stat(%s) failed: %s",
  5752. __func__,
  5753. path,
  5754. strerror(ERRNO));
  5755. ok = 0;
  5756. }
  5757. if (de.file.membuf == NULL) {
  5758. /* file is not in memory */
  5759. if (de.file.is_directory) {
  5760. if (remove_directory(conn, path) == 0) {
  5761. ok = 0;
  5762. }
  5763. } else {
  5764. if (mg_remove(conn, path) == 0) {
  5765. ok = 0;
  5766. }
  5767. }
  5768. } else {
  5769. /* file is in memory. It can not be deleted. */
  5770. ok = 0;
  5771. }
  5772. }
  5773. (void)mg_closedir(dirp);
  5774. IGNORE_UNUSED_RESULT(rmdir(dir));
  5775. }
  5776. return ok;
  5777. }
  5778. #endif
  5779. struct dir_scan_data {
  5780. struct de *entries;
  5781. unsigned int num_entries;
  5782. unsigned int arr_size;
  5783. };
  5784. /* Behaves like realloc(), but frees original pointer on failure */
  5785. static void *
  5786. realloc2(void *ptr, size_t size)
  5787. {
  5788. void *new_ptr = mg_realloc(ptr, size);
  5789. if (new_ptr == NULL) {
  5790. mg_free(ptr);
  5791. }
  5792. return new_ptr;
  5793. }
  5794. static void
  5795. dir_scan_callback(struct de *de, void *data)
  5796. {
  5797. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5798. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5799. dsd->arr_size *= 2;
  5800. dsd->entries =
  5801. (struct de *)realloc2(dsd->entries,
  5802. dsd->arr_size * sizeof(dsd->entries[0]));
  5803. }
  5804. if (dsd->entries == NULL) {
  5805. /* TODO(lsm, low): propagate an error to the caller */
  5806. dsd->num_entries = 0;
  5807. } else {
  5808. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5809. dsd->entries[dsd->num_entries].file = de->file;
  5810. dsd->entries[dsd->num_entries].conn = de->conn;
  5811. dsd->num_entries++;
  5812. }
  5813. }
  5814. static void
  5815. handle_directory_request(struct mg_connection *conn, const char *dir)
  5816. {
  5817. unsigned int i;
  5818. int sort_direction;
  5819. struct dir_scan_data data = {NULL, 0, 128};
  5820. char date[64];
  5821. time_t curtime = time(NULL);
  5822. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5823. send_http_error(conn,
  5824. 500,
  5825. "Error: Cannot open directory\nopendir(%s): %s",
  5826. dir,
  5827. strerror(ERRNO));
  5828. return;
  5829. }
  5830. gmt_time_string(date, sizeof(date), &curtime);
  5831. if (!conn) {
  5832. return;
  5833. }
  5834. sort_direction = ((conn->request_info.query_string != NULL)
  5835. && (conn->request_info.query_string[1] == 'd'))
  5836. ? 'a'
  5837. : 'd';
  5838. conn->must_close = 1;
  5839. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5840. send_static_cache_header(conn);
  5841. mg_printf(conn,
  5842. "Date: %s\r\n"
  5843. "Connection: close\r\n"
  5844. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5845. date);
  5846. conn->num_bytes_sent +=
  5847. mg_printf(conn,
  5848. "<html><head><title>Index of %s</title>"
  5849. "<style>th {text-align: left;}</style></head>"
  5850. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5851. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5852. "<th><a href=\"?d%c\">Modified</a></th>"
  5853. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5854. "<tr><td colspan=\"3\"><hr></td></tr>",
  5855. conn->request_info.local_uri,
  5856. conn->request_info.local_uri,
  5857. sort_direction,
  5858. sort_direction,
  5859. sort_direction);
  5860. /* Print first entry - link to a parent directory */
  5861. conn->num_bytes_sent +=
  5862. mg_printf(conn,
  5863. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5864. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5865. conn->request_info.local_uri,
  5866. "..",
  5867. "Parent directory",
  5868. "-",
  5869. "-");
  5870. /* Sort and print directory entries */
  5871. if (data.entries != NULL) {
  5872. qsort(data.entries,
  5873. (size_t)data.num_entries,
  5874. sizeof(data.entries[0]),
  5875. compare_dir_entries);
  5876. for (i = 0; i < data.num_entries; i++) {
  5877. print_dir_entry(&data.entries[i]);
  5878. mg_free(data.entries[i].file_name);
  5879. }
  5880. mg_free(data.entries);
  5881. }
  5882. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5883. conn->status_code = 200;
  5884. }
  5885. /* Send len bytes from the opened file to the client. */
  5886. static void
  5887. send_file_data(struct mg_connection *conn,
  5888. struct file *filep,
  5889. int64_t offset,
  5890. int64_t len)
  5891. {
  5892. char buf[MG_BUF_LEN];
  5893. int to_read, num_read, num_written;
  5894. int64_t size;
  5895. if (!filep || !conn) {
  5896. return;
  5897. }
  5898. /* Sanity check the offset */
  5899. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5900. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5901. if (len > 0 && filep->membuf != NULL && size > 0) {
  5902. /* file stored in memory */
  5903. if (len > size - offset) {
  5904. len = size - offset;
  5905. }
  5906. mg_write(conn, filep->membuf + offset, (size_t)len);
  5907. } else if (len > 0 && filep->fp != NULL) {
  5908. /* file stored on disk */
  5909. #if defined(__linux__)
  5910. /* sendfile is only available for Linux */
  5911. if ((conn->ssl == 0) && (conn->throttle == 0)
  5912. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  5913. "yes"))) {
  5914. off_t sf_offs = (off_t)offset;
  5915. ssize_t sf_sent;
  5916. int sf_file = fileno(filep->fp);
  5917. int loop_cnt = 0;
  5918. do {
  5919. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5920. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5921. size_t sf_tosend =
  5922. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5923. sf_sent =
  5924. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5925. if (sf_sent > 0) {
  5926. conn->num_bytes_sent += sf_sent;
  5927. len -= sf_sent;
  5928. offset += sf_sent;
  5929. } else if (loop_cnt == 0) {
  5930. /* This file can not be sent using sendfile.
  5931. * This might be the case for pseudo-files in the
  5932. * /sys/ and /proc/ file system.
  5933. * Use the regular user mode copy code instead. */
  5934. break;
  5935. } else if (sf_sent == 0) {
  5936. /* No error, but 0 bytes sent. May be EOF? */
  5937. return;
  5938. }
  5939. loop_cnt++;
  5940. } while ((len > 0) && (sf_sent >= 0));
  5941. if (sf_sent > 0) {
  5942. return; /* OK */
  5943. }
  5944. /* sf_sent<0 means error, thus fall back to the classic way */
  5945. /* This is always the case, if sf_file is not a "normal" file,
  5946. * e.g., for sending data from the output of a CGI process. */
  5947. offset = (int64_t)sf_offs;
  5948. }
  5949. #endif
  5950. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5951. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5952. send_http_error(
  5953. conn,
  5954. 500,
  5955. "%s",
  5956. "Error: Unable to access file at requested position.");
  5957. } else {
  5958. while (len > 0) {
  5959. /* Calculate how much to read from the file in the buffer */
  5960. to_read = sizeof(buf);
  5961. if ((int64_t)to_read > len) {
  5962. to_read = (int)len;
  5963. }
  5964. /* Read from file, exit the loop on error */
  5965. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5966. <= 0) {
  5967. break;
  5968. }
  5969. /* Send read bytes to the client, exit the loop on error */
  5970. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5971. != num_read) {
  5972. break;
  5973. }
  5974. /* Both read and were successful, adjust counters */
  5975. conn->num_bytes_sent += num_written;
  5976. len -= num_written;
  5977. }
  5978. }
  5979. }
  5980. }
  5981. static int
  5982. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5983. {
  5984. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5985. }
  5986. static void
  5987. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5988. {
  5989. if (filep != NULL && buf != NULL) {
  5990. mg_snprintf(NULL,
  5991. NULL, /* All calls to construct_etag use 64 byte buffer */
  5992. buf,
  5993. buf_len,
  5994. "\"%lx.%" INT64_FMT "\"",
  5995. (unsigned long)filep->last_modified,
  5996. filep->size);
  5997. }
  5998. }
  5999. static void
  6000. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  6001. {
  6002. if (filep != NULL && filep->fp != NULL) {
  6003. #ifdef _WIN32
  6004. (void)conn; /* Unused. */
  6005. #else
  6006. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6007. mg_cry(conn,
  6008. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6009. __func__,
  6010. strerror(ERRNO));
  6011. }
  6012. #endif
  6013. }
  6014. }
  6015. static void
  6016. handle_static_file_request(struct mg_connection *conn,
  6017. const char *path,
  6018. struct file *filep,
  6019. const char *mime_type,
  6020. const char *additional_headers)
  6021. {
  6022. char date[64], lm[64], etag[64];
  6023. char range[128]; /* large enough, so there will be no overflow */
  6024. const char *msg = "OK", *hdr;
  6025. time_t curtime = time(NULL);
  6026. int64_t cl, r1, r2;
  6027. struct vec mime_vec;
  6028. int n, truncated;
  6029. char gz_path[PATH_MAX];
  6030. const char *encoding = "";
  6031. const char *cors1, *cors2, *cors3;
  6032. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6033. return;
  6034. }
  6035. if (mime_type == NULL) {
  6036. get_mime_type(conn->ctx, path, &mime_vec);
  6037. } else {
  6038. mime_vec.ptr = mime_type;
  6039. mime_vec.len = strlen(mime_type);
  6040. }
  6041. if (filep->size > INT64_MAX) {
  6042. send_http_error(conn,
  6043. 500,
  6044. "Error: File size is too large to send\n%" INT64_FMT,
  6045. filep->size);
  6046. }
  6047. cl = (int64_t)filep->size;
  6048. conn->status_code = 200;
  6049. range[0] = '\0';
  6050. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6051. * it's important to rewrite the filename after resolving
  6052. * the mime type from it, to preserve the actual file's type */
  6053. if (filep->gzipped) {
  6054. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6055. if (truncated) {
  6056. send_http_error(conn,
  6057. 500,
  6058. "Error: Path of zipped file too long (%s)",
  6059. path);
  6060. return;
  6061. }
  6062. path = gz_path;
  6063. encoding = "Content-Encoding: gzip\r\n";
  6064. }
  6065. if (!mg_fopen(conn, path, "rb", filep)) {
  6066. send_http_error(conn,
  6067. 500,
  6068. "Error: Cannot open file\nfopen(%s): %s",
  6069. path,
  6070. strerror(ERRNO));
  6071. return;
  6072. }
  6073. fclose_on_exec(filep, conn);
  6074. /* If Range: header specified, act accordingly */
  6075. r1 = r2 = 0;
  6076. hdr = mg_get_header(conn, "Range");
  6077. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6078. && r2 >= 0) {
  6079. /* actually, range requests don't play well with a pre-gzipped
  6080. * file (since the range is specified in the uncompressed space) */
  6081. if (filep->gzipped) {
  6082. send_http_error(
  6083. conn,
  6084. 501,
  6085. "%s",
  6086. "Error: Range requests in gzipped files are not supported");
  6087. mg_fclose(filep);
  6088. return;
  6089. }
  6090. conn->status_code = 206;
  6091. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6092. mg_snprintf(conn,
  6093. NULL, /* range buffer is big enough */
  6094. range,
  6095. sizeof(range),
  6096. "Content-Range: bytes "
  6097. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6098. r1,
  6099. r1 + cl - 1,
  6100. filep->size);
  6101. msg = "Partial Content";
  6102. }
  6103. hdr = mg_get_header(conn, "Origin");
  6104. if (hdr) {
  6105. /* Cross-origin resource sharing (CORS), see
  6106. * http://www.html5rocks.com/en/tutorials/cors/,
  6107. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6108. * preflight is not supported for files. */
  6109. cors1 = "Access-Control-Allow-Origin: ";
  6110. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6111. cors3 = "\r\n";
  6112. } else {
  6113. cors1 = cors2 = cors3 = "";
  6114. }
  6115. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6116. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6117. gmt_time_string(date, sizeof(date), &curtime);
  6118. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6119. construct_etag(etag, sizeof(etag), filep);
  6120. (void)mg_printf(conn,
  6121. "HTTP/1.1 %d %s\r\n"
  6122. "%s%s%s"
  6123. "Date: %s\r\n",
  6124. conn->status_code,
  6125. msg,
  6126. cors1,
  6127. cors2,
  6128. cors3,
  6129. date);
  6130. send_static_cache_header(conn);
  6131. (void)mg_printf(conn,
  6132. "Last-Modified: %s\r\n"
  6133. "Etag: %s\r\n"
  6134. "Content-Type: %.*s\r\n"
  6135. "Content-Length: %" INT64_FMT "\r\n"
  6136. "Connection: %s\r\n"
  6137. "Accept-Ranges: bytes\r\n"
  6138. "%s%s",
  6139. lm,
  6140. etag,
  6141. (int)mime_vec.len,
  6142. mime_vec.ptr,
  6143. cl,
  6144. suggest_connection_header(conn),
  6145. range,
  6146. encoding);
  6147. /* The previous code must not add any header starting with X- to make
  6148. * sure no one of the additional_headers is included twice */
  6149. if (additional_headers != NULL) {
  6150. (void)mg_printf(conn,
  6151. "%.*s\r\n\r\n",
  6152. (int)strlen(additional_headers),
  6153. additional_headers);
  6154. } else {
  6155. (void)mg_printf(conn, "\r\n");
  6156. }
  6157. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6158. send_file_data(conn, filep, r1, cl);
  6159. }
  6160. mg_fclose(filep);
  6161. }
  6162. #if !defined(NO_CACHING)
  6163. static void
  6164. handle_not_modified_static_file_request(struct mg_connection *conn,
  6165. struct file *filep)
  6166. {
  6167. char date[64], lm[64], etag[64];
  6168. time_t curtime = time(NULL);
  6169. if (conn == NULL || filep == NULL) {
  6170. return;
  6171. }
  6172. conn->status_code = 304;
  6173. gmt_time_string(date, sizeof(date), &curtime);
  6174. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6175. construct_etag(etag, sizeof(etag), filep);
  6176. (void)mg_printf(conn,
  6177. "HTTP/1.1 %d %s\r\n"
  6178. "Date: %s\r\n",
  6179. conn->status_code,
  6180. mg_get_response_code_text(conn, conn->status_code),
  6181. date);
  6182. send_static_cache_header(conn);
  6183. (void)mg_printf(conn,
  6184. "Last-Modified: %s\r\n"
  6185. "Etag: %s\r\n"
  6186. "Connection: %s\r\n"
  6187. "\r\n",
  6188. lm,
  6189. etag,
  6190. suggest_connection_header(conn));
  6191. }
  6192. #endif
  6193. void
  6194. mg_send_file(struct mg_connection *conn, const char *path)
  6195. {
  6196. mg_send_mime_file(conn, path, NULL);
  6197. }
  6198. void
  6199. mg_send_mime_file(struct mg_connection *conn,
  6200. const char *path,
  6201. const char *mime_type)
  6202. {
  6203. mg_send_mime_file2(conn, path, mime_type, NULL);
  6204. }
  6205. void
  6206. mg_send_mime_file2(struct mg_connection *conn,
  6207. const char *path,
  6208. const char *mime_type,
  6209. const char *additional_headers)
  6210. {
  6211. struct file file = STRUCT_FILE_INITIALIZER;
  6212. if (mg_stat(conn, path, &file)) {
  6213. if (file.is_directory) {
  6214. if (!conn) {
  6215. return;
  6216. }
  6217. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6218. "yes")) {
  6219. handle_directory_request(conn, path);
  6220. } else {
  6221. send_http_error(conn,
  6222. 403,
  6223. "%s",
  6224. "Error: Directory listing denied");
  6225. }
  6226. } else {
  6227. handle_static_file_request(
  6228. conn, path, &file, mime_type, additional_headers);
  6229. }
  6230. } else {
  6231. send_http_error(conn, 404, "%s", "Error: File not found");
  6232. }
  6233. }
  6234. /* For a given PUT path, create all intermediate subdirectories.
  6235. * Return 0 if the path itself is a directory.
  6236. * Return 1 if the path leads to a file.
  6237. * Return -1 for if the path is too long.
  6238. * Return -2 if path can not be created.
  6239. */
  6240. static int
  6241. put_dir(struct mg_connection *conn, const char *path)
  6242. {
  6243. char buf[PATH_MAX];
  6244. const char *s, *p;
  6245. struct file file = STRUCT_FILE_INITIALIZER;
  6246. size_t len;
  6247. int res = 1;
  6248. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6249. len = (size_t)(p - path);
  6250. if (len >= sizeof(buf)) {
  6251. /* path too long */
  6252. res = -1;
  6253. break;
  6254. }
  6255. memcpy(buf, path, len);
  6256. buf[len] = '\0';
  6257. /* Try to create intermediate directory */
  6258. DEBUG_TRACE("mkdir(%s)", buf);
  6259. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6260. /* path does not exixt and can not be created */
  6261. res = -2;
  6262. break;
  6263. }
  6264. /* Is path itself a directory? */
  6265. if (p[1] == '\0') {
  6266. res = 0;
  6267. }
  6268. }
  6269. return res;
  6270. }
  6271. static void
  6272. remove_bad_file(const struct mg_connection *conn, const char *path)
  6273. {
  6274. int r = mg_remove(conn, path);
  6275. if (r != 0) {
  6276. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6277. }
  6278. }
  6279. long long
  6280. mg_store_body(struct mg_connection *conn, const char *path)
  6281. {
  6282. char buf[MG_BUF_LEN];
  6283. long long len = 0;
  6284. int ret, n;
  6285. struct file fi;
  6286. if (conn->consumed_content != 0) {
  6287. mg_cry(conn, "%s: Contents already consumed", __func__);
  6288. return -11;
  6289. }
  6290. ret = put_dir(conn, path);
  6291. if (ret < 0) {
  6292. /* -1 for path too long,
  6293. * -2 for path can not be created. */
  6294. return ret;
  6295. }
  6296. if (ret != 1) {
  6297. /* Return 0 means, path itself is a directory. */
  6298. return 0;
  6299. }
  6300. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6301. return -12;
  6302. }
  6303. ret = mg_read(conn, buf, sizeof(buf));
  6304. while (ret > 0) {
  6305. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6306. if (n != ret) {
  6307. mg_fclose(&fi);
  6308. remove_bad_file(conn, path);
  6309. return -13;
  6310. }
  6311. ret = mg_read(conn, buf, sizeof(buf));
  6312. }
  6313. /* TODO: mg_fclose should return an error,
  6314. * and every caller should check and handle it. */
  6315. if (fclose(fi.fp) != 0) {
  6316. remove_bad_file(conn, path);
  6317. return -14;
  6318. }
  6319. return len;
  6320. }
  6321. /* Parse HTTP headers from the given buffer, advance buf pointer
  6322. * to the point where parsing stopped.
  6323. * All parameters must be valid pointers (not NULL).
  6324. * Return <0 on error. */
  6325. static int
  6326. parse_http_headers(char **buf, struct mg_request_info *ri)
  6327. {
  6328. int i;
  6329. ri->num_headers = 0;
  6330. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6331. char *dp = *buf;
  6332. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6333. dp++;
  6334. }
  6335. if (dp == *buf) {
  6336. /* End of headers reached. */
  6337. break;
  6338. }
  6339. if (*dp != ':') {
  6340. /* This is not a valid field. */
  6341. return -1;
  6342. }
  6343. /* End of header key (*dp == ':') */
  6344. /* Truncate here and set the key name */
  6345. *dp = 0;
  6346. ri->http_headers[i].name = *buf;
  6347. do {
  6348. dp++;
  6349. } while (*dp == ' ');
  6350. /* The rest of the line is the value */
  6351. ri->http_headers[i].value = dp;
  6352. *buf = dp + strcspn(dp, "\r\n");
  6353. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6354. *buf = NULL;
  6355. }
  6356. ri->num_headers = i + 1;
  6357. if (*buf) {
  6358. (*buf)[0] = 0;
  6359. (*buf)[1] = 0;
  6360. *buf += 2;
  6361. } else {
  6362. *buf = dp;
  6363. break;
  6364. }
  6365. if ((*buf)[0] == '\r') {
  6366. /* This is the end of the header */
  6367. break;
  6368. }
  6369. }
  6370. return ri->num_headers;
  6371. }
  6372. static int
  6373. is_valid_http_method(const char *method)
  6374. {
  6375. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6376. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6377. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6378. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6379. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6380. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6381. /* TRACE method (RFC 2616) is not supported for security reasons */
  6382. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6383. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6384. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6385. /* Unsupported WEBDAV Methods: */
  6386. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6387. /* + 11 methods from RFC 3253 */
  6388. /* ORDERPATCH (RFC 3648) */
  6389. /* ACL (RFC 3744) */
  6390. /* SEARCH (RFC 5323) */
  6391. /* + MicroSoft extensions
  6392. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6393. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6394. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6395. }
  6396. /* Parse HTTP request, fill in mg_request_info structure.
  6397. * This function modifies the buffer by NUL-terminating
  6398. * HTTP request components, header names and header values.
  6399. * Parameters:
  6400. * buf (in/out): pointer to the HTTP header to parse and split
  6401. * len (in): length of HTTP header buffer
  6402. * re (out): parsed header as mg_request_info
  6403. * buf and ri must be valid pointers (not NULL), len>0.
  6404. * Returns <0 on error. */
  6405. static int
  6406. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6407. {
  6408. int is_request, request_length;
  6409. char *start_line;
  6410. request_length = get_request_len(buf, len);
  6411. if (request_length > 0) {
  6412. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6413. * remote_port */
  6414. ri->remote_user = ri->request_method = ri->request_uri =
  6415. ri->http_version = NULL;
  6416. ri->num_headers = 0;
  6417. buf[request_length - 1] = '\0';
  6418. /* RFC says that all initial whitespaces should be ingored */
  6419. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6420. buf++;
  6421. }
  6422. start_line = skip(&buf, "\r\n");
  6423. ri->request_method = skip(&start_line, " ");
  6424. ri->request_uri = skip(&start_line, " ");
  6425. ri->http_version = start_line;
  6426. /* HTTP message could be either HTTP request:
  6427. * "GET / HTTP/1.0 ..."
  6428. * or a HTTP response:
  6429. * "HTTP/1.0 200 OK ..."
  6430. * otherwise it is invalid.
  6431. */
  6432. is_request = is_valid_http_method(ri->request_method);
  6433. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6434. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6435. /* Not a valid request or response: invalid */
  6436. return -1;
  6437. }
  6438. if (is_request) {
  6439. ri->http_version += 5;
  6440. }
  6441. if (parse_http_headers(&buf, ri) < 0) {
  6442. /* Error while parsing headers */
  6443. return -1;
  6444. }
  6445. }
  6446. return request_length;
  6447. }
  6448. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6449. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6450. * buffer (which marks the end of HTTP request). Buffer buf may already
  6451. * have some data. The length of the data is stored in nread.
  6452. * Upon every read operation, increase nread by the number of bytes read. */
  6453. static int
  6454. read_request(FILE *fp,
  6455. struct mg_connection *conn,
  6456. char *buf,
  6457. int bufsiz,
  6458. int *nread)
  6459. {
  6460. int request_len, n = 0;
  6461. struct timespec last_action_time;
  6462. double request_timeout;
  6463. if (!conn) {
  6464. return 0;
  6465. }
  6466. memset(&last_action_time, 0, sizeof(last_action_time));
  6467. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6468. /* value of request_timeout is in seconds, config in milliseconds */
  6469. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6470. } else {
  6471. request_timeout = -1.0;
  6472. }
  6473. request_len = get_request_len(buf, *nread);
  6474. /* first time reading from this connection */
  6475. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6476. while (
  6477. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6478. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6479. <= request_timeout) || (request_timeout < 0))
  6480. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6481. > 0)) {
  6482. *nread += n;
  6483. /* assert(*nread <= bufsiz); */
  6484. if (*nread > bufsiz) {
  6485. return -2;
  6486. }
  6487. request_len = get_request_len(buf, *nread);
  6488. if (request_timeout > 0.0) {
  6489. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6490. }
  6491. }
  6492. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6493. }
  6494. #if !defined(NO_FILES)
  6495. /* For given directory path, substitute it to valid index file.
  6496. * Return 1 if index file has been found, 0 if not found.
  6497. * If the file is found, it's stats is returned in stp. */
  6498. static int
  6499. substitute_index_file(struct mg_connection *conn,
  6500. char *path,
  6501. size_t path_len,
  6502. struct file *filep)
  6503. {
  6504. if (conn && conn->ctx) {
  6505. const char *list = conn->ctx->config[INDEX_FILES];
  6506. struct file file = STRUCT_FILE_INITIALIZER;
  6507. struct vec filename_vec;
  6508. size_t n = strlen(path);
  6509. int found = 0;
  6510. /* The 'path' given to us points to the directory. Remove all trailing
  6511. * directory separator characters from the end of the path, and
  6512. * then append single directory separator character. */
  6513. while (n > 0 && path[n - 1] == '/') {
  6514. n--;
  6515. }
  6516. path[n] = '/';
  6517. /* Traverse index files list. For each entry, append it to the given
  6518. * path and see if the file exists. If it exists, break the loop */
  6519. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6520. /* Ignore too long entries that may overflow path buffer */
  6521. if (filename_vec.len > path_len - (n + 2)) {
  6522. continue;
  6523. }
  6524. /* Prepare full path to the index file */
  6525. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6526. /* Does it exist? */
  6527. if (mg_stat(conn, path, &file)) {
  6528. /* Yes it does, break the loop */
  6529. *filep = file;
  6530. found = 1;
  6531. break;
  6532. }
  6533. }
  6534. /* If no index file exists, restore directory path */
  6535. if (!found) {
  6536. path[n] = '\0';
  6537. }
  6538. return found;
  6539. }
  6540. return 0;
  6541. }
  6542. #endif
  6543. #if !defined(NO_CACHING)
  6544. /* Return True if we should reply 304 Not Modified. */
  6545. static int
  6546. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6547. {
  6548. char etag[64];
  6549. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6550. const char *inm = mg_get_header(conn, "If-None-Match");
  6551. construct_etag(etag, sizeof(etag), filep);
  6552. if (!filep) {
  6553. return 0;
  6554. }
  6555. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6556. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6557. }
  6558. #endif /* !NO_CACHING */
  6559. #if !defined(NO_CGI) || !defined(NO_FILES)
  6560. static int
  6561. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6562. {
  6563. const char *expect, *body;
  6564. char buf[MG_BUF_LEN];
  6565. int to_read, nread, success = 0;
  6566. int64_t buffered_len;
  6567. double timeout = -1.0;
  6568. if (!conn) {
  6569. return 0;
  6570. }
  6571. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6572. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6573. }
  6574. expect = mg_get_header(conn, "Expect");
  6575. /* assert(fp != NULL); */
  6576. if (!fp) {
  6577. send_http_error(conn, 500, "%s", "Error: NULL File");
  6578. return 0;
  6579. }
  6580. if (conn->content_len == -1 && !conn->is_chunked) {
  6581. /* Content length is not specified by the client. */
  6582. send_http_error(conn,
  6583. 411,
  6584. "%s",
  6585. "Error: Client did not specify content length");
  6586. } else if ((expect != NULL)
  6587. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6588. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6589. send_http_error(conn,
  6590. 417,
  6591. "Error: Can not fulfill expectation %s",
  6592. expect);
  6593. } else {
  6594. if (expect != NULL) {
  6595. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6596. conn->status_code = 100;
  6597. } else {
  6598. conn->status_code = 200;
  6599. }
  6600. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6601. - conn->consumed_content;
  6602. /* assert(buffered_len >= 0); */
  6603. /* assert(conn->consumed_content == 0); */
  6604. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6605. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6606. return 0;
  6607. }
  6608. if (buffered_len > 0) {
  6609. if ((int64_t)buffered_len > conn->content_len) {
  6610. buffered_len = (int)conn->content_len;
  6611. }
  6612. body = conn->buf + conn->request_len + conn->consumed_content;
  6613. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6614. conn->consumed_content += buffered_len;
  6615. }
  6616. nread = 0;
  6617. while (conn->consumed_content < conn->content_len) {
  6618. to_read = sizeof(buf);
  6619. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6620. to_read = (int)(conn->content_len - conn->consumed_content);
  6621. }
  6622. nread = pull(NULL, conn, buf, to_read, timeout);
  6623. if (nread <= 0
  6624. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6625. break;
  6626. }
  6627. conn->consumed_content += nread;
  6628. }
  6629. if (conn->consumed_content == conn->content_len) {
  6630. success = (nread >= 0);
  6631. }
  6632. /* Each error code path in this function must send an error */
  6633. if (!success) {
  6634. /* NOTE: Maybe some data has already been sent. */
  6635. /* TODO (low): If some data has been sent, a correct error
  6636. * reply can no longer be sent, so just close the connection */
  6637. send_http_error(conn, 500, "%s", "");
  6638. }
  6639. }
  6640. return success;
  6641. }
  6642. #endif
  6643. #if !defined(NO_CGI)
  6644. /* This structure helps to create an environment for the spawned CGI program.
  6645. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6646. * last element must be NULL.
  6647. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6648. * strings must reside in a contiguous buffer. The end of the buffer is
  6649. * marked by two '\0' characters.
  6650. * We satisfy both worlds: we create an envp array (which is vars), all
  6651. * entries are actually pointers inside buf. */
  6652. struct cgi_environment {
  6653. struct mg_connection *conn;
  6654. /* Data block */
  6655. char *buf; /* Environment buffer */
  6656. size_t buflen; /* Space available in buf */
  6657. size_t bufused; /* Space taken in buf */
  6658. /* Index block */
  6659. char **var; /* char **envp */
  6660. size_t varlen; /* Number of variables available in var */
  6661. size_t varused; /* Number of variables stored in var */
  6662. };
  6663. static void addenv(struct cgi_environment *env,
  6664. PRINTF_FORMAT_STRING(const char *fmt),
  6665. ...) PRINTF_ARGS(2, 3);
  6666. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6667. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6668. static void
  6669. addenv(struct cgi_environment *env, const char *fmt, ...)
  6670. {
  6671. size_t n, space;
  6672. int truncated = 0;
  6673. char *added;
  6674. va_list ap;
  6675. /* Calculate how much space is left in the buffer */
  6676. space = (env->buflen - env->bufused);
  6677. /* Calculate an estimate for the required space */
  6678. n = strlen(fmt) + 2 + 128;
  6679. do {
  6680. if (space <= n) {
  6681. /* Allocate new buffer */
  6682. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6683. added = (char *)mg_realloc(env->buf, n);
  6684. if (!added) {
  6685. /* Out of memory */
  6686. mg_cry(env->conn,
  6687. "%s: Cannot allocate memory for CGI variable [%s]",
  6688. __func__,
  6689. fmt);
  6690. return;
  6691. }
  6692. env->buf = added;
  6693. env->buflen = n;
  6694. space = (env->buflen - env->bufused);
  6695. }
  6696. /* Make a pointer to the free space int the buffer */
  6697. added = env->buf + env->bufused;
  6698. /* Copy VARIABLE=VALUE\0 string into the free space */
  6699. va_start(ap, fmt);
  6700. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6701. va_end(ap);
  6702. /* Do not add truncated strings to the environment */
  6703. if (truncated) {
  6704. /* Reallocate the buffer */
  6705. space = 0;
  6706. n = 1;
  6707. }
  6708. } while (truncated);
  6709. /* Calculate number of bytes added to the environment */
  6710. n = strlen(added) + 1;
  6711. env->bufused += n;
  6712. /* Now update the variable index */
  6713. space = (env->varlen - env->varused);
  6714. if (space < 2) {
  6715. mg_cry(env->conn,
  6716. "%s: Cannot register CGI variable [%s]",
  6717. __func__,
  6718. fmt);
  6719. return;
  6720. }
  6721. /* Append a pointer to the added string into the envp array */
  6722. env->var[env->varused] = added;
  6723. env->varused++;
  6724. }
  6725. static void
  6726. prepare_cgi_environment(struct mg_connection *conn,
  6727. const char *prog,
  6728. struct cgi_environment *env)
  6729. {
  6730. const char *s;
  6731. struct vec var_vec;
  6732. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6733. int i, truncated;
  6734. if (conn == NULL || prog == NULL || env == NULL) {
  6735. return;
  6736. }
  6737. env->conn = conn;
  6738. env->buflen = CGI_ENVIRONMENT_SIZE;
  6739. env->bufused = 0;
  6740. env->buf = (char *)mg_malloc(env->buflen);
  6741. env->varlen = MAX_CGI_ENVIR_VARS;
  6742. env->varused = 0;
  6743. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6744. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6745. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6746. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6747. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6748. /* Prepare the environment block */
  6749. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6750. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6751. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6752. #if defined(USE_IPV6)
  6753. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6754. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6755. } else
  6756. #endif
  6757. {
  6758. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6759. }
  6760. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6761. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6762. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6763. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6764. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6765. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6766. /* SCRIPT_NAME */
  6767. addenv(env,
  6768. "SCRIPT_NAME=%.*s",
  6769. (int)strlen(conn->request_info.local_uri)
  6770. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6771. conn->request_info.local_uri);
  6772. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6773. if (conn->path_info == NULL) {
  6774. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6775. } else {
  6776. addenv(env,
  6777. "PATH_TRANSLATED=%s%s",
  6778. conn->ctx->config[DOCUMENT_ROOT],
  6779. conn->path_info);
  6780. }
  6781. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6782. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6783. addenv(env, "CONTENT_TYPE=%s", s);
  6784. }
  6785. if (conn->request_info.query_string != NULL) {
  6786. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6787. }
  6788. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6789. addenv(env, "CONTENT_LENGTH=%s", s);
  6790. }
  6791. if ((s = getenv("PATH")) != NULL) {
  6792. addenv(env, "PATH=%s", s);
  6793. }
  6794. if (conn->path_info != NULL) {
  6795. addenv(env, "PATH_INFO=%s", conn->path_info);
  6796. }
  6797. if (conn->status_code > 0) {
  6798. /* CGI error handler should show the status code */
  6799. addenv(env, "STATUS=%d", conn->status_code);
  6800. }
  6801. #if defined(_WIN32)
  6802. if ((s = getenv("COMSPEC")) != NULL) {
  6803. addenv(env, "COMSPEC=%s", s);
  6804. }
  6805. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6806. addenv(env, "SYSTEMROOT=%s", s);
  6807. }
  6808. if ((s = getenv("SystemDrive")) != NULL) {
  6809. addenv(env, "SystemDrive=%s", s);
  6810. }
  6811. if ((s = getenv("ProgramFiles")) != NULL) {
  6812. addenv(env, "ProgramFiles=%s", s);
  6813. }
  6814. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6815. addenv(env, "ProgramFiles(x86)=%s", s);
  6816. }
  6817. #else
  6818. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6819. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6820. }
  6821. #endif /* _WIN32 */
  6822. if ((s = getenv("PERLLIB")) != NULL) {
  6823. addenv(env, "PERLLIB=%s", s);
  6824. }
  6825. if (conn->request_info.remote_user != NULL) {
  6826. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6827. addenv(env, "%s", "AUTH_TYPE=Digest");
  6828. }
  6829. /* Add all headers as HTTP_* variables */
  6830. for (i = 0; i < conn->request_info.num_headers; i++) {
  6831. (void)mg_snprintf(conn,
  6832. &truncated,
  6833. http_var_name,
  6834. sizeof(http_var_name),
  6835. "HTTP_%s",
  6836. conn->request_info.http_headers[i].name);
  6837. if (truncated) {
  6838. mg_cry(conn,
  6839. "%s: HTTP header variable too long [%s]",
  6840. __func__,
  6841. conn->request_info.http_headers[i].name);
  6842. continue;
  6843. }
  6844. /* Convert variable name into uppercase, and change - to _ */
  6845. for (p = http_var_name; *p != '\0'; p++) {
  6846. if (*p == '-') {
  6847. *p = '_';
  6848. }
  6849. *p = (char)toupper(*(unsigned char *)p);
  6850. }
  6851. addenv(env,
  6852. "%s=%s",
  6853. http_var_name,
  6854. conn->request_info.http_headers[i].value);
  6855. }
  6856. /* Add user-specified variables */
  6857. s = conn->ctx->config[CGI_ENVIRONMENT];
  6858. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6859. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6860. }
  6861. env->var[env->varused] = NULL;
  6862. env->buf[env->bufused] = '\0';
  6863. }
  6864. static void
  6865. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6866. {
  6867. char *buf;
  6868. size_t buflen;
  6869. int headers_len, data_len, i, truncated;
  6870. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6871. const char *status, *status_text, *connection_state;
  6872. char *pbuf, dir[PATH_MAX], *p;
  6873. struct mg_request_info ri;
  6874. struct cgi_environment blk;
  6875. FILE *in = NULL, *out = NULL, *err = NULL;
  6876. struct file fout = STRUCT_FILE_INITIALIZER;
  6877. pid_t pid = (pid_t)-1;
  6878. if (conn == NULL) {
  6879. return;
  6880. }
  6881. buf = NULL;
  6882. buflen = 16384;
  6883. prepare_cgi_environment(conn, prog, &blk);
  6884. /* CGI must be executed in its own directory. 'dir' must point to the
  6885. * directory containing executable program, 'p' must point to the
  6886. * executable program name relative to 'dir'. */
  6887. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6888. if (truncated) {
  6889. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6890. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6891. goto done;
  6892. }
  6893. if ((p = strrchr(dir, '/')) != NULL) {
  6894. *p++ = '\0';
  6895. } else {
  6896. dir[0] = '.', dir[1] = '\0';
  6897. p = (char *)prog;
  6898. }
  6899. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6900. status = strerror(ERRNO);
  6901. mg_cry(conn,
  6902. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6903. prog,
  6904. status);
  6905. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6906. goto done;
  6907. }
  6908. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6909. if (pid == (pid_t)-1) {
  6910. status = strerror(ERRNO);
  6911. mg_cry(conn,
  6912. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6913. prog,
  6914. status);
  6915. send_http_error(conn,
  6916. 500,
  6917. "Error: Cannot spawn CGI process [%s]: %s",
  6918. prog,
  6919. status);
  6920. goto done;
  6921. }
  6922. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6923. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6924. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6925. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6926. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6927. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6928. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6929. /* Parent closes only one side of the pipes.
  6930. * If we don't mark them as closed, close() attempt before
  6931. * return from this function throws an exception on Windows.
  6932. * Windows does not like when closed descriptor is closed again. */
  6933. (void)close(fdin[0]);
  6934. (void)close(fdout[1]);
  6935. (void)close(fderr[1]);
  6936. fdin[0] = fdout[1] = fderr[1] = -1;
  6937. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6938. status = strerror(ERRNO);
  6939. mg_cry(conn,
  6940. "Error: CGI program \"%s\": Can not open stdin: %s",
  6941. prog,
  6942. status);
  6943. send_http_error(conn,
  6944. 500,
  6945. "Error: CGI can not open fdin\nfopen: %s",
  6946. status);
  6947. goto done;
  6948. }
  6949. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6950. status = strerror(ERRNO);
  6951. mg_cry(conn,
  6952. "Error: CGI program \"%s\": Can not open stdout: %s",
  6953. prog,
  6954. status);
  6955. send_http_error(conn,
  6956. 500,
  6957. "Error: CGI can not open fdout\nfopen: %s",
  6958. status);
  6959. goto done;
  6960. }
  6961. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6962. status = strerror(ERRNO);
  6963. mg_cry(conn,
  6964. "Error: CGI program \"%s\": Can not open stderr: %s",
  6965. prog,
  6966. status);
  6967. send_http_error(conn,
  6968. 500,
  6969. "Error: CGI can not open fdout\nfopen: %s",
  6970. status);
  6971. goto done;
  6972. }
  6973. setbuf(in, NULL);
  6974. setbuf(out, NULL);
  6975. setbuf(err, NULL);
  6976. fout.fp = out;
  6977. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6978. /* This is a POST/PUT request, or another request with body data. */
  6979. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6980. /* Error sending the body data */
  6981. mg_cry(conn,
  6982. "Error: CGI program \"%s\": Forward body data failed",
  6983. prog);
  6984. goto done;
  6985. }
  6986. }
  6987. /* Close so child gets an EOF. */
  6988. fclose(in);
  6989. in = NULL;
  6990. fdin[1] = -1;
  6991. /* Now read CGI reply into a buffer. We need to set correct
  6992. * status code, thus we need to see all HTTP headers first.
  6993. * Do not send anything back to client, until we buffer in all
  6994. * HTTP headers. */
  6995. data_len = 0;
  6996. buf = (char *)mg_malloc(buflen);
  6997. if (buf == NULL) {
  6998. send_http_error(conn,
  6999. 500,
  7000. "Error: Not enough memory for CGI buffer (%u bytes)",
  7001. (unsigned int)buflen);
  7002. mg_cry(conn,
  7003. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7004. "bytes)",
  7005. prog,
  7006. (unsigned int)buflen);
  7007. goto done;
  7008. }
  7009. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7010. if (headers_len <= 0) {
  7011. /* Could not parse the CGI response. Check if some error message on
  7012. * stderr. */
  7013. i = pull_all(err, conn, buf, (int)buflen);
  7014. if (i > 0) {
  7015. mg_cry(conn,
  7016. "Error: CGI program \"%s\" sent error "
  7017. "message: [%.*s]",
  7018. prog,
  7019. i,
  7020. buf);
  7021. send_http_error(conn,
  7022. 500,
  7023. "Error: CGI program \"%s\" sent error "
  7024. "message: [%.*s]",
  7025. prog,
  7026. i,
  7027. buf);
  7028. } else {
  7029. mg_cry(conn,
  7030. "Error: CGI program sent malformed or too big "
  7031. "(>%u bytes) HTTP headers: [%.*s]",
  7032. (unsigned)buflen,
  7033. data_len,
  7034. buf);
  7035. send_http_error(conn,
  7036. 500,
  7037. "Error: CGI program sent malformed or too big "
  7038. "(>%u bytes) HTTP headers: [%.*s]",
  7039. (unsigned)buflen,
  7040. data_len,
  7041. buf);
  7042. }
  7043. goto done;
  7044. }
  7045. pbuf = buf;
  7046. buf[headers_len - 1] = '\0';
  7047. parse_http_headers(&pbuf, &ri);
  7048. /* Make up and send the status line */
  7049. status_text = "OK";
  7050. if ((status = get_header(&ri, "Status")) != NULL) {
  7051. conn->status_code = atoi(status);
  7052. status_text = status;
  7053. while (isdigit(*(const unsigned char *)status_text)
  7054. || *status_text == ' ') {
  7055. status_text++;
  7056. }
  7057. } else if (get_header(&ri, "Location") != NULL) {
  7058. conn->status_code = 302;
  7059. } else {
  7060. conn->status_code = 200;
  7061. }
  7062. connection_state = get_header(&ri, "Connection");
  7063. if (!header_has_option(connection_state, "keep-alive")) {
  7064. conn->must_close = 1;
  7065. }
  7066. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7067. /* Send headers */
  7068. for (i = 0; i < ri.num_headers; i++) {
  7069. mg_printf(conn,
  7070. "%s: %s\r\n",
  7071. ri.http_headers[i].name,
  7072. ri.http_headers[i].value);
  7073. }
  7074. mg_write(conn, "\r\n", 2);
  7075. /* Send chunk of data that may have been read after the headers */
  7076. conn->num_bytes_sent +=
  7077. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7078. /* Read the rest of CGI output and send to the client */
  7079. send_file_data(conn, &fout, 0, INT64_MAX);
  7080. done:
  7081. mg_free(blk.var);
  7082. mg_free(blk.buf);
  7083. if (pid != (pid_t)-1) {
  7084. kill(pid, SIGKILL);
  7085. #if !defined(_WIN32)
  7086. {
  7087. int st;
  7088. while (waitpid(pid, &st, 0) != -1)
  7089. ; /* clean zombies */
  7090. }
  7091. #endif
  7092. }
  7093. if (fdin[0] != -1) {
  7094. close(fdin[0]);
  7095. }
  7096. if (fdout[1] != -1) {
  7097. close(fdout[1]);
  7098. }
  7099. if (in != NULL) {
  7100. fclose(in);
  7101. } else if (fdin[1] != -1) {
  7102. close(fdin[1]);
  7103. }
  7104. if (out != NULL) {
  7105. fclose(out);
  7106. } else if (fdout[0] != -1) {
  7107. close(fdout[0]);
  7108. }
  7109. if (err != NULL) {
  7110. fclose(err);
  7111. } else if (fderr[0] != -1) {
  7112. close(fderr[0]);
  7113. }
  7114. if (buf != NULL) {
  7115. mg_free(buf);
  7116. }
  7117. }
  7118. #endif /* !NO_CGI */
  7119. #if !defined(NO_FILES)
  7120. static void
  7121. mkcol(struct mg_connection *conn, const char *path)
  7122. {
  7123. int rc, body_len;
  7124. struct de de;
  7125. char date[64];
  7126. time_t curtime = time(NULL);
  7127. if (conn == NULL) {
  7128. return;
  7129. }
  7130. /* TODO (mid): Check the send_http_error situations in this function */
  7131. memset(&de.file, 0, sizeof(de.file));
  7132. if (!mg_stat(conn, path, &de.file)) {
  7133. mg_cry(conn,
  7134. "%s: mg_stat(%s) failed: %s",
  7135. __func__,
  7136. path,
  7137. strerror(ERRNO));
  7138. }
  7139. if (de.file.last_modified) {
  7140. /* TODO (high): This check does not seem to make any sense ! */
  7141. send_http_error(
  7142. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7143. return;
  7144. }
  7145. body_len = conn->data_len - conn->request_len;
  7146. if (body_len > 0) {
  7147. send_http_error(
  7148. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7149. return;
  7150. }
  7151. rc = mg_mkdir(conn, path, 0755);
  7152. if (rc == 0) {
  7153. conn->status_code = 201;
  7154. gmt_time_string(date, sizeof(date), &curtime);
  7155. mg_printf(conn,
  7156. "HTTP/1.1 %d Created\r\n"
  7157. "Date: %s\r\n",
  7158. conn->status_code,
  7159. date);
  7160. send_static_cache_header(conn);
  7161. mg_printf(conn,
  7162. "Content-Length: 0\r\n"
  7163. "Connection: %s\r\n\r\n",
  7164. suggest_connection_header(conn));
  7165. } else if (rc == -1) {
  7166. if (errno == EEXIST) {
  7167. send_http_error(
  7168. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7169. } else if (errno == EACCES) {
  7170. send_http_error(
  7171. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7172. } else if (errno == ENOENT) {
  7173. send_http_error(
  7174. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7175. } else {
  7176. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7177. }
  7178. }
  7179. }
  7180. static void
  7181. put_file(struct mg_connection *conn, const char *path)
  7182. {
  7183. struct file file = STRUCT_FILE_INITIALIZER;
  7184. const char *range;
  7185. int64_t r1, r2;
  7186. int rc;
  7187. char date[64];
  7188. time_t curtime = time(NULL);
  7189. if (conn == NULL) {
  7190. return;
  7191. }
  7192. if (mg_stat(conn, path, &file)) {
  7193. /* File already exists */
  7194. conn->status_code = 200;
  7195. if (file.is_directory) {
  7196. /* This is an already existing directory,
  7197. * so there is nothing to do for the server. */
  7198. rc = 0;
  7199. } else {
  7200. /* File exists and is not a directory. */
  7201. /* Can it be replaced? */
  7202. if (file.membuf != NULL) {
  7203. /* This is an "in-memory" file, that can not be replaced */
  7204. send_http_error(
  7205. conn,
  7206. 405,
  7207. "Error: Put not possible\nReplacing %s is not supported",
  7208. path);
  7209. return;
  7210. }
  7211. /* Check if the server may write this file */
  7212. if (access(path, W_OK) == 0) {
  7213. /* Access granted */
  7214. conn->status_code = 200;
  7215. rc = 1;
  7216. } else {
  7217. send_http_error(
  7218. conn,
  7219. 403,
  7220. "Error: Put not possible\nReplacing %s is not allowed",
  7221. path);
  7222. return;
  7223. }
  7224. }
  7225. } else {
  7226. /* File should be created */
  7227. conn->status_code = 201;
  7228. rc = put_dir(conn, path);
  7229. }
  7230. if (rc == 0) {
  7231. /* put_dir returns 0 if path is a directory */
  7232. gmt_time_string(date, sizeof(date), &curtime);
  7233. mg_printf(conn,
  7234. "HTTP/1.1 %d %s\r\n",
  7235. conn->status_code,
  7236. mg_get_response_code_text(NULL, conn->status_code));
  7237. send_no_cache_header(conn);
  7238. mg_printf(conn,
  7239. "Date: %s\r\n"
  7240. "Content-Length: 0\r\n"
  7241. "Connection: %s\r\n\r\n",
  7242. date,
  7243. suggest_connection_header(conn));
  7244. /* Request to create a directory has been fulfilled successfully.
  7245. * No need to put a file. */
  7246. return;
  7247. }
  7248. if (rc == -1) {
  7249. /* put_dir returns -1 if the path is too long */
  7250. send_http_error(conn,
  7251. 414,
  7252. "Error: Path too long\nput_dir(%s): %s",
  7253. path,
  7254. strerror(ERRNO));
  7255. return;
  7256. }
  7257. if (rc == -2) {
  7258. /* put_dir returns -2 if the directory can not be created */
  7259. send_http_error(conn,
  7260. 500,
  7261. "Error: Can not create directory\nput_dir(%s): %s",
  7262. path,
  7263. strerror(ERRNO));
  7264. return;
  7265. }
  7266. /* A file should be created or overwritten. */
  7267. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7268. mg_fclose(&file);
  7269. send_http_error(conn,
  7270. 500,
  7271. "Error: Can not create file\nfopen(%s): %s",
  7272. path,
  7273. strerror(ERRNO));
  7274. return;
  7275. }
  7276. fclose_on_exec(&file, conn);
  7277. range = mg_get_header(conn, "Content-Range");
  7278. r1 = r2 = 0;
  7279. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7280. conn->status_code = 206; /* Partial content */
  7281. fseeko(file.fp, r1, SEEK_SET);
  7282. }
  7283. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7284. /* forward_body_data failed.
  7285. * The error code has already been sent to the client,
  7286. * and conn->status_code is already set. */
  7287. mg_fclose(&file);
  7288. return;
  7289. }
  7290. gmt_time_string(date, sizeof(date), &curtime);
  7291. mg_printf(conn,
  7292. "HTTP/1.1 %d %s\r\n",
  7293. conn->status_code,
  7294. mg_get_response_code_text(NULL, conn->status_code));
  7295. send_no_cache_header(conn);
  7296. mg_printf(conn,
  7297. "Date: %s\r\n"
  7298. "Content-Length: 0\r\n"
  7299. "Connection: %s\r\n\r\n",
  7300. date,
  7301. suggest_connection_header(conn));
  7302. mg_fclose(&file);
  7303. }
  7304. static void
  7305. delete_file(struct mg_connection *conn, const char *path)
  7306. {
  7307. struct de de;
  7308. memset(&de.file, 0, sizeof(de.file));
  7309. if (!mg_stat(conn, path, &de.file)) {
  7310. /* mg_stat returns 0 if the file does not exist */
  7311. send_http_error(conn,
  7312. 404,
  7313. "Error: Cannot delete file\nFile %s not found",
  7314. path);
  7315. return;
  7316. }
  7317. if (de.file.membuf != NULL) {
  7318. /* the file is cached in memory */
  7319. send_http_error(
  7320. conn,
  7321. 405,
  7322. "Error: Delete not possible\nDeleting %s is not supported",
  7323. path);
  7324. return;
  7325. }
  7326. if (de.file.is_directory) {
  7327. if (remove_directory(conn, path)) {
  7328. /* Delete is successful: Return 204 without content. */
  7329. send_http_error(conn, 204, "%s", "");
  7330. } else {
  7331. /* Delete is not successful: Return 500 (Server error). */
  7332. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7333. }
  7334. return;
  7335. }
  7336. /* This is an existing file (not a directory).
  7337. * Check if write permission is granted. */
  7338. if (access(path, W_OK) != 0) {
  7339. /* File is read only */
  7340. send_http_error(
  7341. conn,
  7342. 403,
  7343. "Error: Delete not possible\nDeleting %s is not allowed",
  7344. path);
  7345. return;
  7346. }
  7347. /* Try to delete it. */
  7348. if (mg_remove(conn, path) == 0) {
  7349. /* Delete was successful: Return 204 without content. */
  7350. send_http_error(conn, 204, "%s", "");
  7351. } else {
  7352. /* Delete not successful (file locked). */
  7353. send_http_error(conn,
  7354. 423,
  7355. "Error: Cannot delete file\nremove(%s): %s",
  7356. path,
  7357. strerror(ERRNO));
  7358. }
  7359. }
  7360. #endif /* !NO_FILES */
  7361. static void
  7362. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7363. static void
  7364. do_ssi_include(struct mg_connection *conn,
  7365. const char *ssi,
  7366. char *tag,
  7367. int include_level)
  7368. {
  7369. char file_name[MG_BUF_LEN], path[512], *p;
  7370. struct file file = STRUCT_FILE_INITIALIZER;
  7371. size_t len;
  7372. int truncated = 0;
  7373. if (conn == NULL) {
  7374. return;
  7375. }
  7376. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7377. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7378. * always < MG_BUF_LEN. */
  7379. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7380. /* File name is relative to the webserver root */
  7381. file_name[511] = 0;
  7382. (void)mg_snprintf(conn,
  7383. &truncated,
  7384. path,
  7385. sizeof(path),
  7386. "%s/%s",
  7387. conn->ctx->config[DOCUMENT_ROOT],
  7388. file_name);
  7389. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7390. /* File name is relative to the webserver working directory
  7391. * or it is absolute system path */
  7392. file_name[511] = 0;
  7393. (void)
  7394. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7395. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7396. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7397. /* File name is relative to the currect document */
  7398. file_name[511] = 0;
  7399. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7400. if (!truncated) {
  7401. if ((p = strrchr(path, '/')) != NULL) {
  7402. p[1] = '\0';
  7403. }
  7404. len = strlen(path);
  7405. (void)mg_snprintf(conn,
  7406. &truncated,
  7407. path + len,
  7408. sizeof(path) - len,
  7409. "%s",
  7410. file_name);
  7411. }
  7412. } else {
  7413. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7414. return;
  7415. }
  7416. if (truncated) {
  7417. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7418. return;
  7419. }
  7420. if (!mg_fopen(conn, path, "rb", &file)) {
  7421. mg_cry(conn,
  7422. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7423. tag,
  7424. path,
  7425. strerror(ERRNO));
  7426. } else {
  7427. fclose_on_exec(&file, conn);
  7428. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7429. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7430. path) > 0) {
  7431. send_ssi_file(conn, path, &file, include_level + 1);
  7432. } else {
  7433. send_file_data(conn, &file, 0, INT64_MAX);
  7434. }
  7435. mg_fclose(&file);
  7436. }
  7437. }
  7438. #if !defined(NO_POPEN)
  7439. static void
  7440. do_ssi_exec(struct mg_connection *conn, char *tag)
  7441. {
  7442. char cmd[1024] = "";
  7443. struct file file = STRUCT_FILE_INITIALIZER;
  7444. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7445. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7446. } else {
  7447. cmd[1023] = 0;
  7448. if ((file.fp = popen(cmd, "r")) == NULL) {
  7449. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7450. } else {
  7451. send_file_data(conn, &file, 0, INT64_MAX);
  7452. pclose(file.fp);
  7453. }
  7454. }
  7455. }
  7456. #endif /* !NO_POPEN */
  7457. static int
  7458. mg_fgetc(struct file *filep, int offset)
  7459. {
  7460. if (filep == NULL) {
  7461. return EOF;
  7462. }
  7463. if (filep->membuf != NULL && offset >= 0
  7464. && ((unsigned int)(offset)) < filep->size) {
  7465. return ((const unsigned char *)filep->membuf)[offset];
  7466. } else if (filep->fp != NULL) {
  7467. return fgetc(filep->fp);
  7468. } else {
  7469. return EOF;
  7470. }
  7471. }
  7472. static void
  7473. send_ssi_file(struct mg_connection *conn,
  7474. const char *path,
  7475. struct file *filep,
  7476. int include_level)
  7477. {
  7478. char buf[MG_BUF_LEN];
  7479. int ch, offset, len, in_ssi_tag;
  7480. if (include_level > 10) {
  7481. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7482. return;
  7483. }
  7484. in_ssi_tag = len = offset = 0;
  7485. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7486. if (in_ssi_tag && ch == '>') {
  7487. in_ssi_tag = 0;
  7488. buf[len++] = (char)ch;
  7489. buf[len] = '\0';
  7490. /* assert(len <= (int) sizeof(buf)); */
  7491. if (len > (int)sizeof(buf)) {
  7492. break;
  7493. }
  7494. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7495. /* Not an SSI tag, pass it */
  7496. (void)mg_write(conn, buf, (size_t)len);
  7497. } else {
  7498. if (!memcmp(buf + 5, "include", 7)) {
  7499. do_ssi_include(conn, path, buf + 12, include_level);
  7500. #if !defined(NO_POPEN)
  7501. } else if (!memcmp(buf + 5, "exec", 4)) {
  7502. do_ssi_exec(conn, buf + 9);
  7503. #endif /* !NO_POPEN */
  7504. } else {
  7505. mg_cry(conn,
  7506. "%s: unknown SSI "
  7507. "command: \"%s\"",
  7508. path,
  7509. buf);
  7510. }
  7511. }
  7512. len = 0;
  7513. } else if (in_ssi_tag) {
  7514. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7515. /* Not an SSI tag */
  7516. in_ssi_tag = 0;
  7517. } else if (len == (int)sizeof(buf) - 2) {
  7518. mg_cry(conn, "%s: SSI tag is too large", path);
  7519. len = 0;
  7520. }
  7521. buf[len++] = (char)(ch & 0xff);
  7522. } else if (ch == '<') {
  7523. in_ssi_tag = 1;
  7524. if (len > 0) {
  7525. mg_write(conn, buf, (size_t)len);
  7526. }
  7527. len = 0;
  7528. buf[len++] = (char)(ch & 0xff);
  7529. } else {
  7530. buf[len++] = (char)(ch & 0xff);
  7531. if (len == (int)sizeof(buf)) {
  7532. mg_write(conn, buf, (size_t)len);
  7533. len = 0;
  7534. }
  7535. }
  7536. }
  7537. /* Send the rest of buffered data */
  7538. if (len > 0) {
  7539. mg_write(conn, buf, (size_t)len);
  7540. }
  7541. }
  7542. static void
  7543. handle_ssi_file_request(struct mg_connection *conn,
  7544. const char *path,
  7545. struct file *filep)
  7546. {
  7547. char date[64];
  7548. time_t curtime = time(NULL);
  7549. const char *cors1, *cors2, *cors3;
  7550. if (conn == NULL || path == NULL || filep == NULL) {
  7551. return;
  7552. }
  7553. if (mg_get_header(conn, "Origin")) {
  7554. /* Cross-origin resource sharing (CORS). */
  7555. cors1 = "Access-Control-Allow-Origin: ";
  7556. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7557. cors3 = "\r\n";
  7558. } else {
  7559. cors1 = cors2 = cors3 = "";
  7560. }
  7561. if (!mg_fopen(conn, path, "rb", filep)) {
  7562. /* File exists (precondition for calling this function),
  7563. * but can not be opened by the server. */
  7564. send_http_error(conn,
  7565. 500,
  7566. "Error: Cannot read file\nfopen(%s): %s",
  7567. path,
  7568. strerror(ERRNO));
  7569. } else {
  7570. conn->must_close = 1;
  7571. gmt_time_string(date, sizeof(date), &curtime);
  7572. fclose_on_exec(filep, conn);
  7573. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7574. send_no_cache_header(conn);
  7575. mg_printf(conn,
  7576. "%s%s%s"
  7577. "Date: %s\r\n"
  7578. "Content-Type: text/html\r\n"
  7579. "Connection: %s\r\n\r\n",
  7580. cors1,
  7581. cors2,
  7582. cors3,
  7583. date,
  7584. suggest_connection_header(conn));
  7585. send_ssi_file(conn, path, filep, 0);
  7586. mg_fclose(filep);
  7587. }
  7588. }
  7589. #if !defined(NO_FILES)
  7590. static void
  7591. send_options(struct mg_connection *conn)
  7592. {
  7593. char date[64];
  7594. time_t curtime = time(NULL);
  7595. if (!conn) {
  7596. return;
  7597. }
  7598. conn->status_code = 200;
  7599. conn->must_close = 1;
  7600. gmt_time_string(date, sizeof(date), &curtime);
  7601. mg_printf(conn,
  7602. "HTTP/1.1 200 OK\r\n"
  7603. "Date: %s\r\n"
  7604. /* TODO: "Cache-Control" (?) */
  7605. "Connection: %s\r\n"
  7606. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7607. "PROPFIND, MKCOL\r\n"
  7608. "DAV: 1\r\n\r\n",
  7609. date,
  7610. suggest_connection_header(conn));
  7611. }
  7612. /* Writes PROPFIND properties for a collection element */
  7613. static void
  7614. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7615. {
  7616. char mtime[64];
  7617. if (conn == NULL || uri == NULL || filep == NULL) {
  7618. return;
  7619. }
  7620. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7621. conn->num_bytes_sent +=
  7622. mg_printf(conn,
  7623. "<d:response>"
  7624. "<d:href>%s</d:href>"
  7625. "<d:propstat>"
  7626. "<d:prop>"
  7627. "<d:resourcetype>%s</d:resourcetype>"
  7628. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7629. "<d:getlastmodified>%s</d:getlastmodified>"
  7630. "</d:prop>"
  7631. "<d:status>HTTP/1.1 200 OK</d:status>"
  7632. "</d:propstat>"
  7633. "</d:response>\n",
  7634. uri,
  7635. filep->is_directory ? "<d:collection/>" : "",
  7636. filep->size,
  7637. mtime);
  7638. }
  7639. static void
  7640. print_dav_dir_entry(struct de *de, void *data)
  7641. {
  7642. char href[PATH_MAX];
  7643. char href_encoded[PATH_MAX * 3 /* worst case */];
  7644. int truncated;
  7645. struct mg_connection *conn = (struct mg_connection *)data;
  7646. if (!de || !conn) {
  7647. return;
  7648. }
  7649. mg_snprintf(conn,
  7650. &truncated,
  7651. href,
  7652. sizeof(href),
  7653. "%s%s",
  7654. conn->request_info.local_uri,
  7655. de->file_name);
  7656. if (!truncated) {
  7657. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7658. print_props(conn, href_encoded, &de->file);
  7659. }
  7660. }
  7661. static void
  7662. handle_propfind(struct mg_connection *conn,
  7663. const char *path,
  7664. struct file *filep)
  7665. {
  7666. const char *depth = mg_get_header(conn, "Depth");
  7667. char date[64];
  7668. time_t curtime = time(NULL);
  7669. gmt_time_string(date, sizeof(date), &curtime);
  7670. if (!conn || !path || !filep || !conn->ctx) {
  7671. return;
  7672. }
  7673. conn->must_close = 1;
  7674. conn->status_code = 207;
  7675. mg_printf(conn,
  7676. "HTTP/1.1 207 Multi-Status\r\n"
  7677. "Date: %s\r\n",
  7678. date);
  7679. send_static_cache_header(conn);
  7680. mg_printf(conn,
  7681. "Connection: %s\r\n"
  7682. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7683. suggest_connection_header(conn));
  7684. conn->num_bytes_sent +=
  7685. mg_printf(conn,
  7686. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7687. "<d:multistatus xmlns:d='DAV:'>\n");
  7688. /* Print properties for the requested resource itself */
  7689. print_props(conn, conn->request_info.local_uri, filep);
  7690. /* If it is a directory, print directory entries too if Depth is not 0 */
  7691. if (filep && filep->is_directory
  7692. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7693. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7694. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7695. }
  7696. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7697. }
  7698. #endif
  7699. void
  7700. mg_lock_connection(struct mg_connection *conn)
  7701. {
  7702. if (conn) {
  7703. (void)pthread_mutex_lock(&conn->mutex);
  7704. }
  7705. }
  7706. void
  7707. mg_unlock_connection(struct mg_connection *conn)
  7708. {
  7709. if (conn) {
  7710. (void)pthread_mutex_unlock(&conn->mutex);
  7711. }
  7712. }
  7713. void
  7714. mg_lock_context(struct mg_context *ctx)
  7715. {
  7716. if (ctx) {
  7717. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7718. }
  7719. }
  7720. void
  7721. mg_unlock_context(struct mg_context *ctx)
  7722. {
  7723. if (ctx) {
  7724. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7725. }
  7726. }
  7727. #if defined(USE_TIMERS)
  7728. #include "timer.inl"
  7729. #endif /* USE_TIMERS */
  7730. #ifdef USE_LUA
  7731. #include "mod_lua.inl"
  7732. #endif /* USE_LUA */
  7733. #ifdef USE_DUKTAPE
  7734. #include "mod_duktape.inl"
  7735. #endif /* USE_DUKTAPE */
  7736. #if defined(USE_WEBSOCKET)
  7737. /* START OF SHA-1 code
  7738. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7739. #define SHA1HANDSOFF
  7740. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7741. *
  7742. * #if defined(__sun)
  7743. * #include "solarisfixes.h"
  7744. * #endif
  7745. */
  7746. static int
  7747. is_big_endian(void)
  7748. {
  7749. static const int n = 1;
  7750. return ((char *)&n)[0] == 0;
  7751. }
  7752. union char64long16 {
  7753. unsigned char c[64];
  7754. uint32_t l[16];
  7755. };
  7756. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7757. static uint32_t
  7758. blk0(union char64long16 *block, int i)
  7759. {
  7760. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7761. if (!is_big_endian()) {
  7762. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7763. | (rol(block->l[i], 8) & 0x00FF00FF);
  7764. }
  7765. return block->l[i];
  7766. }
  7767. #define blk(i) \
  7768. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7769. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7770. 1))
  7771. #define R0(v, w, x, y, z, i) \
  7772. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7773. w = rol(w, 30);
  7774. #define R1(v, w, x, y, z, i) \
  7775. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7776. w = rol(w, 30);
  7777. #define R2(v, w, x, y, z, i) \
  7778. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7779. w = rol(w, 30);
  7780. #define R3(v, w, x, y, z, i) \
  7781. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7782. w = rol(w, 30);
  7783. #define R4(v, w, x, y, z, i) \
  7784. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7785. w = rol(w, 30);
  7786. typedef struct {
  7787. uint32_t state[5];
  7788. uint32_t count[2];
  7789. unsigned char buffer[64];
  7790. } SHA1_CTX;
  7791. static void
  7792. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7793. {
  7794. uint32_t a, b, c, d, e;
  7795. union char64long16 block[1];
  7796. memcpy(block, buffer, 64);
  7797. a = state[0];
  7798. b = state[1];
  7799. c = state[2];
  7800. d = state[3];
  7801. e = state[4];
  7802. R0(a, b, c, d, e, 0);
  7803. R0(e, a, b, c, d, 1);
  7804. R0(d, e, a, b, c, 2);
  7805. R0(c, d, e, a, b, 3);
  7806. R0(b, c, d, e, a, 4);
  7807. R0(a, b, c, d, e, 5);
  7808. R0(e, a, b, c, d, 6);
  7809. R0(d, e, a, b, c, 7);
  7810. R0(c, d, e, a, b, 8);
  7811. R0(b, c, d, e, a, 9);
  7812. R0(a, b, c, d, e, 10);
  7813. R0(e, a, b, c, d, 11);
  7814. R0(d, e, a, b, c, 12);
  7815. R0(c, d, e, a, b, 13);
  7816. R0(b, c, d, e, a, 14);
  7817. R0(a, b, c, d, e, 15);
  7818. R1(e, a, b, c, d, 16);
  7819. R1(d, e, a, b, c, 17);
  7820. R1(c, d, e, a, b, 18);
  7821. R1(b, c, d, e, a, 19);
  7822. R2(a, b, c, d, e, 20);
  7823. R2(e, a, b, c, d, 21);
  7824. R2(d, e, a, b, c, 22);
  7825. R2(c, d, e, a, b, 23);
  7826. R2(b, c, d, e, a, 24);
  7827. R2(a, b, c, d, e, 25);
  7828. R2(e, a, b, c, d, 26);
  7829. R2(d, e, a, b, c, 27);
  7830. R2(c, d, e, a, b, 28);
  7831. R2(b, c, d, e, a, 29);
  7832. R2(a, b, c, d, e, 30);
  7833. R2(e, a, b, c, d, 31);
  7834. R2(d, e, a, b, c, 32);
  7835. R2(c, d, e, a, b, 33);
  7836. R2(b, c, d, e, a, 34);
  7837. R2(a, b, c, d, e, 35);
  7838. R2(e, a, b, c, d, 36);
  7839. R2(d, e, a, b, c, 37);
  7840. R2(c, d, e, a, b, 38);
  7841. R2(b, c, d, e, a, 39);
  7842. R3(a, b, c, d, e, 40);
  7843. R3(e, a, b, c, d, 41);
  7844. R3(d, e, a, b, c, 42);
  7845. R3(c, d, e, a, b, 43);
  7846. R3(b, c, d, e, a, 44);
  7847. R3(a, b, c, d, e, 45);
  7848. R3(e, a, b, c, d, 46);
  7849. R3(d, e, a, b, c, 47);
  7850. R3(c, d, e, a, b, 48);
  7851. R3(b, c, d, e, a, 49);
  7852. R3(a, b, c, d, e, 50);
  7853. R3(e, a, b, c, d, 51);
  7854. R3(d, e, a, b, c, 52);
  7855. R3(c, d, e, a, b, 53);
  7856. R3(b, c, d, e, a, 54);
  7857. R3(a, b, c, d, e, 55);
  7858. R3(e, a, b, c, d, 56);
  7859. R3(d, e, a, b, c, 57);
  7860. R3(c, d, e, a, b, 58);
  7861. R3(b, c, d, e, a, 59);
  7862. R4(a, b, c, d, e, 60);
  7863. R4(e, a, b, c, d, 61);
  7864. R4(d, e, a, b, c, 62);
  7865. R4(c, d, e, a, b, 63);
  7866. R4(b, c, d, e, a, 64);
  7867. R4(a, b, c, d, e, 65);
  7868. R4(e, a, b, c, d, 66);
  7869. R4(d, e, a, b, c, 67);
  7870. R4(c, d, e, a, b, 68);
  7871. R4(b, c, d, e, a, 69);
  7872. R4(a, b, c, d, e, 70);
  7873. R4(e, a, b, c, d, 71);
  7874. R4(d, e, a, b, c, 72);
  7875. R4(c, d, e, a, b, 73);
  7876. R4(b, c, d, e, a, 74);
  7877. R4(a, b, c, d, e, 75);
  7878. R4(e, a, b, c, d, 76);
  7879. R4(d, e, a, b, c, 77);
  7880. R4(c, d, e, a, b, 78);
  7881. R4(b, c, d, e, a, 79);
  7882. state[0] += a;
  7883. state[1] += b;
  7884. state[2] += c;
  7885. state[3] += d;
  7886. state[4] += e;
  7887. a = b = c = d = e = 0;
  7888. memset(block, '\0', sizeof(block));
  7889. }
  7890. static void
  7891. SHA1Init(SHA1_CTX *context)
  7892. {
  7893. context->state[0] = 0x67452301;
  7894. context->state[1] = 0xEFCDAB89;
  7895. context->state[2] = 0x98BADCFE;
  7896. context->state[3] = 0x10325476;
  7897. context->state[4] = 0xC3D2E1F0;
  7898. context->count[0] = context->count[1] = 0;
  7899. }
  7900. static void
  7901. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7902. {
  7903. uint32_t i, j;
  7904. j = context->count[0];
  7905. if ((context->count[0] += len << 3) < j) {
  7906. context->count[1]++;
  7907. }
  7908. context->count[1] += (len >> 29);
  7909. j = (j >> 3) & 63;
  7910. if ((j + len) > 63) {
  7911. memcpy(&context->buffer[j], data, (i = 64 - j));
  7912. SHA1Transform(context->state, context->buffer);
  7913. for (; i + 63 < len; i += 64) {
  7914. SHA1Transform(context->state, &data[i]);
  7915. }
  7916. j = 0;
  7917. } else
  7918. i = 0;
  7919. memcpy(&context->buffer[j], &data[i], len - i);
  7920. }
  7921. static void
  7922. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7923. {
  7924. unsigned i;
  7925. unsigned char finalcount[8], c;
  7926. for (i = 0; i < 8; i++) {
  7927. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7928. >> ((3 - (i & 3)) * 8)) & 255);
  7929. }
  7930. c = 0200;
  7931. SHA1Update(context, &c, 1);
  7932. while ((context->count[0] & 504) != 448) {
  7933. c = 0000;
  7934. SHA1Update(context, &c, 1);
  7935. }
  7936. SHA1Update(context, finalcount, 8);
  7937. for (i = 0; i < 20; i++) {
  7938. digest[i] = (unsigned char)((context->state[i >> 2]
  7939. >> ((3 - (i & 3)) * 8)) & 255);
  7940. }
  7941. memset(context, '\0', sizeof(*context));
  7942. memset(&finalcount, '\0', sizeof(finalcount));
  7943. }
  7944. /* END OF SHA1 CODE */
  7945. static int
  7946. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7947. {
  7948. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7949. const char *protocol = NULL;
  7950. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7951. SHA1_CTX sha_ctx;
  7952. int truncated;
  7953. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7954. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7955. if (truncated) {
  7956. conn->must_close = 1;
  7957. return 0;
  7958. }
  7959. SHA1Init(&sha_ctx);
  7960. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7961. SHA1Final((unsigned char *)sha, &sha_ctx);
  7962. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7963. mg_printf(conn,
  7964. "HTTP/1.1 101 Switching Protocols\r\n"
  7965. "Upgrade: websocket\r\n"
  7966. "Connection: Upgrade\r\n"
  7967. "Sec-WebSocket-Accept: %s\r\n",
  7968. b64_sha);
  7969. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7970. if (protocol) {
  7971. /* The protocol is a comma seperated list of names. */
  7972. /* The server must only return one value from this list. */
  7973. /* First check if it is a list or just a single value. */
  7974. const char *sep = strchr(protocol, ',');
  7975. if (sep == NULL) {
  7976. /* Just a single protocol -> accept it. */
  7977. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7978. } else {
  7979. /* Multiple protocols -> accept the first one. */
  7980. /* This is just a quick fix if the client offers multiple
  7981. * protocols. In order to get the behavior intended by
  7982. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7983. * required to have a list of websocket subprotocols accepted
  7984. * by the server. Then the server must either select a subprotocol
  7985. * supported by client and server, or the server has to abort the
  7986. * handshake by not returning a Sec-Websocket-Protocol header if
  7987. * no subprotocol is acceptable.
  7988. */
  7989. mg_printf(conn,
  7990. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7991. (int)(sep - protocol),
  7992. protocol);
  7993. }
  7994. /* TODO: Real subprotocol negotiation instead of just taking the first
  7995. * websocket subprotocol suggested by the client. */
  7996. } else {
  7997. mg_printf(conn, "%s", "\r\n");
  7998. }
  7999. return 1;
  8000. }
  8001. static void
  8002. read_websocket(struct mg_connection *conn,
  8003. mg_websocket_data_handler ws_data_handler,
  8004. void *callback_data)
  8005. {
  8006. /* Pointer to the beginning of the portion of the incoming websocket
  8007. * message queue.
  8008. * The original websocket upgrade request is never removed, so the queue
  8009. * begins after it. */
  8010. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8011. int n, error, exit_by_callback;
  8012. /* body_len is the length of the entire queue in bytes
  8013. * len is the length of the current message
  8014. * data_len is the length of the current message's data payload
  8015. * header_len is the length of the current message's header */
  8016. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8017. /* "The masking key is a 32-bit value chosen at random by the client."
  8018. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8019. */
  8020. unsigned char mask[4];
  8021. /* data points to the place where the message is stored when passed to
  8022. * the
  8023. * websocket_data callback. This is either mem on the stack, or a
  8024. * dynamically allocated buffer if it is too large. */
  8025. unsigned char mem[4096];
  8026. unsigned char *data = mem;
  8027. unsigned char mop; /* mask flag and opcode */
  8028. double timeout = -1.0;
  8029. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8030. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8031. }
  8032. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8033. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8034. }
  8035. mg_set_thread_name("wsock");
  8036. /* Loop continuously, reading messages from the socket, invoking the
  8037. * callback, and waiting repeatedly until an error occurs. */
  8038. while (!conn->ctx->stop_flag) {
  8039. header_len = 0;
  8040. assert(conn->data_len >= conn->request_len);
  8041. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8042. len = buf[1] & 127;
  8043. mask_len = (buf[1] & 128) ? 4 : 0;
  8044. if ((len < 126) && (body_len >= mask_len)) {
  8045. data_len = len;
  8046. header_len = 2 + mask_len;
  8047. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8048. header_len = 4 + mask_len;
  8049. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8050. } else if (body_len >= (10 + mask_len)) {
  8051. header_len = 10 + mask_len;
  8052. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8053. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8054. }
  8055. }
  8056. if (header_len > 0 && body_len >= header_len) {
  8057. /* Allocate space to hold websocket payload */
  8058. data = mem;
  8059. if (data_len > sizeof(mem)) {
  8060. data = (unsigned char *)mg_malloc(data_len);
  8061. if (data == NULL) {
  8062. /* Allocation failed, exit the loop and then close the
  8063. * connection */
  8064. mg_cry(conn, "websocket out of memory; closing connection");
  8065. break;
  8066. }
  8067. }
  8068. /* Copy the mask before we shift the queue and destroy it */
  8069. if (mask_len > 0) {
  8070. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8071. } else {
  8072. memset(mask, 0, sizeof(mask));
  8073. }
  8074. /* Read frame payload from the first message in the queue into
  8075. * data and advance the queue by moving the memory in place. */
  8076. assert(body_len >= header_len);
  8077. if (data_len + header_len > body_len) {
  8078. mop = buf[0]; /* current mask and opcode */
  8079. /* Overflow case */
  8080. len = body_len - header_len;
  8081. memcpy(data, buf + header_len, len);
  8082. error = 0;
  8083. while (len < data_len) {
  8084. n = pull(NULL,
  8085. conn,
  8086. (char *)(data + len),
  8087. (int)(data_len - len),
  8088. timeout);
  8089. if (n <= 0) {
  8090. error = 1;
  8091. break;
  8092. }
  8093. len += (size_t)n;
  8094. }
  8095. if (error) {
  8096. mg_cry(conn, "Websocket pull failed; closing connection");
  8097. break;
  8098. }
  8099. conn->data_len = conn->request_len;
  8100. } else {
  8101. mop = buf[0]; /* current mask and opcode, overwritten by
  8102. * memmove() */
  8103. /* Length of the message being read at the front of the
  8104. * queue */
  8105. len = data_len + header_len;
  8106. /* Copy the data payload into the data pointer for the
  8107. * callback */
  8108. memcpy(data, buf + header_len, data_len);
  8109. /* Move the queue forward len bytes */
  8110. memmove(buf, buf + len, body_len - len);
  8111. /* Mark the queue as advanced */
  8112. conn->data_len -= (int)len;
  8113. }
  8114. /* Apply mask if necessary */
  8115. if (mask_len > 0) {
  8116. for (i = 0; i < data_len; ++i) {
  8117. data[i] ^= mask[i & 3];
  8118. }
  8119. }
  8120. /* Exit the loop if callback signals to exit (server side),
  8121. * or "connection close" opcode received (client side). */
  8122. exit_by_callback = 0;
  8123. if ((ws_data_handler != NULL)
  8124. && !ws_data_handler(
  8125. conn, mop, (char *)data, data_len, callback_data)) {
  8126. exit_by_callback = 1;
  8127. }
  8128. if (data != mem) {
  8129. mg_free(data);
  8130. }
  8131. if (exit_by_callback
  8132. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8133. /* Opcode == 8, connection close */
  8134. break;
  8135. }
  8136. /* Not breaking the loop, process next websocket frame. */
  8137. } else {
  8138. /* Read from the socket into the next available location in the
  8139. * message queue. */
  8140. if ((n = pull(NULL,
  8141. conn,
  8142. conn->buf + conn->data_len,
  8143. conn->buf_size - conn->data_len,
  8144. timeout)) <= 0) {
  8145. /* Error, no bytes read */
  8146. break;
  8147. }
  8148. conn->data_len += n;
  8149. }
  8150. }
  8151. mg_set_thread_name("worker");
  8152. }
  8153. static int
  8154. mg_websocket_write_exec(struct mg_connection *conn,
  8155. int opcode,
  8156. const char *data,
  8157. size_t dataLen,
  8158. uint32_t masking_key)
  8159. {
  8160. unsigned char header[14];
  8161. size_t headerLen = 1;
  8162. int retval = -1;
  8163. #if defined(__GNUC__) || defined(__MINGW32__)
  8164. /* Disable spurious conversion warning for GCC */
  8165. #pragma GCC diagnostic push
  8166. #pragma GCC diagnostic ignored "-Wconversion"
  8167. #endif
  8168. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8169. #if defined(__GNUC__) || defined(__MINGW32__)
  8170. #pragma GCC diagnostic pop
  8171. #endif
  8172. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8173. if (dataLen < 126) {
  8174. /* inline 7-bit length field */
  8175. header[1] = (unsigned char)dataLen;
  8176. headerLen = 2;
  8177. } else if (dataLen <= 0xFFFF) {
  8178. /* 16-bit length field */
  8179. uint16_t len = htons((uint16_t)dataLen);
  8180. header[1] = 126;
  8181. memcpy(header + 2, &len, 2);
  8182. headerLen = 4;
  8183. } else {
  8184. /* 64-bit length field */
  8185. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8186. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8187. header[1] = 127;
  8188. memcpy(header + 2, &len1, 4);
  8189. memcpy(header + 6, &len2, 4);
  8190. headerLen = 10;
  8191. }
  8192. if (masking_key) {
  8193. /* add mask */
  8194. header[1] |= 0x80;
  8195. memcpy(header + headerLen, &masking_key, 4);
  8196. headerLen += 4;
  8197. }
  8198. /* Note that POSIX/Winsock's send() is threadsafe
  8199. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8200. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8201. * push(), although that is only a problem if the packet is large or
  8202. * outgoing buffer is full). */
  8203. (void)mg_lock_connection(conn);
  8204. retval = mg_write(conn, header, headerLen);
  8205. if (dataLen > 0) {
  8206. retval = mg_write(conn, data, dataLen);
  8207. }
  8208. mg_unlock_connection(conn);
  8209. return retval;
  8210. }
  8211. int
  8212. mg_websocket_write(struct mg_connection *conn,
  8213. int opcode,
  8214. const char *data,
  8215. size_t dataLen)
  8216. {
  8217. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8218. }
  8219. static void
  8220. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8221. {
  8222. size_t i = 0;
  8223. i = 0;
  8224. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8225. /* Convert in 32 bit words, if data is 4 byte aligned */
  8226. while (i < (in_len - 3)) {
  8227. *(uint32_t *)(void *)(out + i) =
  8228. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8229. i += 4;
  8230. }
  8231. }
  8232. if (i != in_len) {
  8233. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8234. while (i < in_len) {
  8235. *(uint8_t *)(void *)(out + i) =
  8236. *(uint8_t *)(void *)(in + i)
  8237. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8238. i++;
  8239. }
  8240. }
  8241. }
  8242. int
  8243. mg_websocket_client_write(struct mg_connection *conn,
  8244. int opcode,
  8245. const char *data,
  8246. size_t dataLen)
  8247. {
  8248. int retval = -1;
  8249. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8250. uint32_t masking_key = (uint32_t)get_random();
  8251. if (masked_data == NULL) {
  8252. /* Return -1 in an error case */
  8253. mg_cry(conn,
  8254. "Cannot allocate buffer for masked websocket response: "
  8255. "Out of memory");
  8256. return -1;
  8257. }
  8258. mask_data(data, dataLen, masking_key, masked_data);
  8259. retval = mg_websocket_write_exec(
  8260. conn, opcode, masked_data, dataLen, masking_key);
  8261. mg_free(masked_data);
  8262. return retval;
  8263. }
  8264. static void
  8265. handle_websocket_request(struct mg_connection *conn,
  8266. const char *path,
  8267. int is_callback_resource,
  8268. mg_websocket_connect_handler ws_connect_handler,
  8269. mg_websocket_ready_handler ws_ready_handler,
  8270. mg_websocket_data_handler ws_data_handler,
  8271. mg_websocket_close_handler ws_close_handler,
  8272. void *cbData)
  8273. {
  8274. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8275. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8276. int lua_websock = 0;
  8277. #if !defined(USE_LUA)
  8278. (void)path;
  8279. #endif
  8280. /* Step 1: Check websocket protocol version. */
  8281. /* Step 1.1: Check Sec-WebSocket-Key. */
  8282. if (!websock_key) {
  8283. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8284. * requires a Sec-WebSocket-Key header.
  8285. */
  8286. /* It could be the hixie draft version
  8287. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8288. */
  8289. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8290. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8291. char key3[8];
  8292. if ((key1 != NULL) && (key2 != NULL)) {
  8293. /* This version uses 8 byte body data in a GET request */
  8294. conn->content_len = 8;
  8295. if (8 == mg_read(conn, key3, 8)) {
  8296. /* This is the hixie version */
  8297. send_http_error(conn,
  8298. 426,
  8299. "%s",
  8300. "Protocol upgrade to RFC 6455 required");
  8301. return;
  8302. }
  8303. }
  8304. /* This is an unknown version */
  8305. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8306. return;
  8307. }
  8308. /* Step 1.2: Check websocket protocol version. */
  8309. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8310. if (version == NULL || strcmp(version, "13") != 0) {
  8311. /* Reject wrong versions */
  8312. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8313. return;
  8314. }
  8315. /* Step 1.3: Could check for "Host", but we do not really nead this
  8316. * value for anything, so just ignore it. */
  8317. /* Step 2: If a callback is responsible, call it. */
  8318. if (is_callback_resource) {
  8319. if (ws_connect_handler != NULL
  8320. && ws_connect_handler(conn, cbData) != 0) {
  8321. /* C callback has returned non-zero, do not proceed with
  8322. * handshake.
  8323. */
  8324. /* Note that C callbacks are no longer called when Lua is
  8325. * responsible, so C can no longer filter callbacks for Lua. */
  8326. return;
  8327. }
  8328. }
  8329. #if defined(USE_LUA)
  8330. /* Step 3: No callback. Check if Lua is responsible. */
  8331. else {
  8332. /* Step 3.1: Check if Lua is responsible. */
  8333. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8334. lua_websock =
  8335. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8336. strlen(
  8337. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8338. path);
  8339. }
  8340. if (lua_websock) {
  8341. /* Step 3.2: Lua is responsible: call it. */
  8342. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8343. if (!conn->lua_websocket_state) {
  8344. /* Lua rejected the new client */
  8345. return;
  8346. }
  8347. }
  8348. }
  8349. #endif
  8350. /* Step 4: Check if there is a responsible websocket handler. */
  8351. if (!is_callback_resource && !lua_websock) {
  8352. /* There is no callback, an Lua is not responsible either. */
  8353. /* Reply with a 404 Not Found or with nothing at all?
  8354. * TODO (mid): check the websocket standards, how to reply to
  8355. * requests to invalid websocket addresses. */
  8356. send_http_error(conn, 404, "%s", "Not found");
  8357. return;
  8358. }
  8359. /* Step 5: The websocket connection has been accepted */
  8360. if (!send_websocket_handshake(conn, websock_key)) {
  8361. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8362. return;
  8363. }
  8364. /* Step 6: Call the ready handler */
  8365. if (is_callback_resource) {
  8366. if (ws_ready_handler != NULL) {
  8367. ws_ready_handler(conn, cbData);
  8368. }
  8369. #if defined(USE_LUA)
  8370. } else if (lua_websock) {
  8371. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8372. /* the ready handler returned false */
  8373. return;
  8374. }
  8375. #endif
  8376. }
  8377. /* Step 7: Enter the read loop */
  8378. if (is_callback_resource) {
  8379. read_websocket(conn, ws_data_handler, cbData);
  8380. #if defined(USE_LUA)
  8381. } else if (lua_websock) {
  8382. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8383. #endif
  8384. }
  8385. /* Step 8: Call the close handler */
  8386. if (ws_close_handler) {
  8387. ws_close_handler(conn, cbData);
  8388. }
  8389. }
  8390. static int
  8391. is_websocket_protocol(const struct mg_connection *conn)
  8392. {
  8393. const char *upgrade, *connection;
  8394. /* A websocket protocoll has the following HTTP headers:
  8395. *
  8396. * Connection: Upgrade
  8397. * Upgrade: Websocket
  8398. */
  8399. upgrade = mg_get_header(conn, "Upgrade");
  8400. if (upgrade == NULL) {
  8401. return 0; /* fail early, don't waste time checking other header
  8402. * fields
  8403. */
  8404. }
  8405. if (!mg_strcasestr(upgrade, "websocket")) {
  8406. return 0;
  8407. }
  8408. connection = mg_get_header(conn, "Connection");
  8409. if (connection == NULL) {
  8410. return 0;
  8411. }
  8412. if (!mg_strcasestr(connection, "upgrade")) {
  8413. return 0;
  8414. }
  8415. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8416. * "Sec-WebSocket-Version" are also required.
  8417. * Don't check them here, since even an unsupported websocket protocol
  8418. * request still IS a websocket request (in contrast to a standard HTTP
  8419. * request). It will fail later in handle_websocket_request.
  8420. */
  8421. return 1;
  8422. }
  8423. #endif /* !USE_WEBSOCKET */
  8424. static int
  8425. isbyte(int n)
  8426. {
  8427. return n >= 0 && n <= 255;
  8428. }
  8429. static int
  8430. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8431. {
  8432. int n, a, b, c, d, slash = 32, len = 0;
  8433. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8434. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8435. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8436. && slash < 33) {
  8437. len = n;
  8438. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8439. | (uint32_t)d;
  8440. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8441. }
  8442. return len;
  8443. }
  8444. static int
  8445. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8446. {
  8447. int throttle = 0;
  8448. struct vec vec, val;
  8449. uint32_t net, mask;
  8450. char mult;
  8451. double v;
  8452. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8453. mult = ',';
  8454. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8455. || (v < 0) || ((lowercase(&mult) != 'k')
  8456. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8457. continue;
  8458. }
  8459. v *= (lowercase(&mult) == 'k')
  8460. ? 1024
  8461. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8462. if (vec.len == 1 && vec.ptr[0] == '*') {
  8463. throttle = (int)v;
  8464. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8465. if ((remote_ip & mask) == net) {
  8466. throttle = (int)v;
  8467. }
  8468. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8469. throttle = (int)v;
  8470. }
  8471. }
  8472. return throttle;
  8473. }
  8474. static uint32_t
  8475. get_remote_ip(const struct mg_connection *conn)
  8476. {
  8477. if (!conn) {
  8478. return 0;
  8479. }
  8480. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8481. }
  8482. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8483. #include "handle_form.inl"
  8484. #if defined(MG_LEGACY_INTERFACE)
  8485. /* Implement the deprecated mg_upload function by calling the new
  8486. * mg_handle_form_request function. While mg_upload could only handle
  8487. * HTML forms sent as POST request in multipart/form-data format
  8488. * containing only file input elements, mg_handle_form_request can
  8489. * handle all form input elements and all standard request methods. */
  8490. struct mg_upload_user_data {
  8491. struct mg_connection *conn;
  8492. const char *destination_dir;
  8493. int num_uploaded_files;
  8494. };
  8495. /* Helper function for deprecated mg_upload. */
  8496. static int
  8497. mg_upload_field_found(const char *key,
  8498. const char *filename,
  8499. char *path,
  8500. size_t pathlen,
  8501. void *user_data)
  8502. {
  8503. int truncated = 0;
  8504. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8505. (void)key;
  8506. if (!filename) {
  8507. mg_cry(fud->conn, "%s: No filename set", __func__);
  8508. return FORM_FIELD_STORAGE_ABORT;
  8509. }
  8510. mg_snprintf(fud->conn,
  8511. &truncated,
  8512. path,
  8513. pathlen - 1,
  8514. "%s/%s",
  8515. fud->destination_dir,
  8516. filename);
  8517. if (!truncated) {
  8518. mg_cry(fud->conn, "%s: File path too long", __func__);
  8519. return FORM_FIELD_STORAGE_ABORT;
  8520. }
  8521. return FORM_FIELD_STORAGE_STORE;
  8522. }
  8523. /* Helper function for deprecated mg_upload. */
  8524. static int
  8525. mg_upload_field_get(const char *key,
  8526. const char *value,
  8527. size_t value_size,
  8528. void *user_data)
  8529. {
  8530. /* Function should never be called */
  8531. (void)key;
  8532. (void)value;
  8533. (void)value_size;
  8534. (void)user_data;
  8535. return 0;
  8536. }
  8537. /* Helper function for deprecated mg_upload. */
  8538. static int
  8539. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8540. {
  8541. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8542. (void)file_size;
  8543. fud->num_uploaded_files++;
  8544. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8545. return 0;
  8546. }
  8547. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8548. int
  8549. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8550. {
  8551. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8552. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8553. mg_upload_field_get,
  8554. mg_upload_field_stored,
  8555. 0};
  8556. int ret;
  8557. fdh.user_data = (void *)&fud;
  8558. ret = mg_handle_form_request(conn, &fdh);
  8559. if (ret < 0) {
  8560. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8561. }
  8562. return fud.num_uploaded_files;
  8563. }
  8564. #endif
  8565. static int
  8566. get_first_ssl_listener_index(const struct mg_context *ctx)
  8567. {
  8568. unsigned int i;
  8569. int idx = -1;
  8570. if (ctx) {
  8571. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8572. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8573. }
  8574. }
  8575. return idx;
  8576. }
  8577. static void
  8578. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8579. {
  8580. char host[1025];
  8581. const char *host_header;
  8582. size_t hostlen;
  8583. host_header = mg_get_header(conn, "Host");
  8584. hostlen = sizeof(host);
  8585. if (host_header != NULL) {
  8586. char *pos;
  8587. mg_strlcpy(host, host_header, hostlen);
  8588. host[hostlen - 1] = '\0';
  8589. pos = strchr(host, ':');
  8590. if (pos != NULL) {
  8591. *pos = '\0';
  8592. }
  8593. } else {
  8594. /* Cannot get host from the Host: header.
  8595. * Fallback to our IP address. */
  8596. if (conn) {
  8597. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8598. }
  8599. }
  8600. /* Send host, port, uri and (if it exists) ?query_string */
  8601. if (conn) {
  8602. mg_printf(conn,
  8603. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8604. host,
  8605. #if defined(USE_IPV6)
  8606. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8607. == AF_INET6)
  8608. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8609. .lsa.sin6.sin6_port)
  8610. :
  8611. #endif
  8612. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8613. .lsa.sin.sin_port),
  8614. conn->request_info.local_uri,
  8615. (conn->request_info.query_string == NULL) ? "" : "?",
  8616. (conn->request_info.query_string == NULL)
  8617. ? ""
  8618. : conn->request_info.query_string);
  8619. }
  8620. }
  8621. static void
  8622. mg_set_handler_type(struct mg_context *ctx,
  8623. const char *uri,
  8624. int handler_type,
  8625. int is_delete_request,
  8626. mg_request_handler handler,
  8627. mg_websocket_connect_handler connect_handler,
  8628. mg_websocket_ready_handler ready_handler,
  8629. mg_websocket_data_handler data_handler,
  8630. mg_websocket_close_handler close_handler,
  8631. mg_authorization_handler auth_handler,
  8632. void *cbdata)
  8633. {
  8634. struct mg_handler_info *tmp_rh, **lastref;
  8635. size_t urilen = strlen(uri);
  8636. if (handler_type == WEBSOCKET_HANDLER) {
  8637. /* assert(handler == NULL); */
  8638. /* assert(is_delete_request || connect_handler!=NULL ||
  8639. * ready_handler!=NULL || data_handler!=NULL ||
  8640. * close_handler!=NULL);
  8641. */
  8642. /* assert(auth_handler == NULL); */
  8643. if (handler != NULL) {
  8644. return;
  8645. }
  8646. if (!is_delete_request && connect_handler == NULL
  8647. && ready_handler == NULL
  8648. && data_handler == NULL
  8649. && close_handler == NULL) {
  8650. return;
  8651. }
  8652. if (auth_handler != NULL) {
  8653. return;
  8654. }
  8655. } else if (handler_type == REQUEST_HANDLER) {
  8656. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8657. * data_handler==NULL && close_handler==NULL); */
  8658. /* assert(is_delete_request || (handler!=NULL));
  8659. */
  8660. /* assert(auth_handler == NULL); */
  8661. if (connect_handler != NULL || ready_handler != NULL
  8662. || data_handler != NULL
  8663. || close_handler != NULL) {
  8664. return;
  8665. }
  8666. if (!is_delete_request && (handler == NULL)) {
  8667. return;
  8668. }
  8669. if (auth_handler != NULL) {
  8670. return;
  8671. }
  8672. } else { /* AUTH_HANDLER */
  8673. /* assert(handler == NULL); */
  8674. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8675. * data_handler==NULL && close_handler==NULL); */
  8676. /* assert(auth_handler != NULL); */
  8677. if (handler != NULL) {
  8678. return;
  8679. }
  8680. if (connect_handler != NULL || ready_handler != NULL
  8681. || data_handler != NULL
  8682. || close_handler != NULL) {
  8683. return;
  8684. }
  8685. if (!is_delete_request && (auth_handler == NULL)) {
  8686. return;
  8687. }
  8688. }
  8689. if (!ctx) {
  8690. return;
  8691. }
  8692. mg_lock_context(ctx);
  8693. /* first try to find an existing handler */
  8694. lastref = &(ctx->handlers);
  8695. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8696. if (tmp_rh->handler_type == handler_type) {
  8697. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8698. if (!is_delete_request) {
  8699. /* update existing handler */
  8700. if (handler_type == REQUEST_HANDLER) {
  8701. tmp_rh->handler = handler;
  8702. } else if (handler_type == WEBSOCKET_HANDLER) {
  8703. tmp_rh->connect_handler = connect_handler;
  8704. tmp_rh->ready_handler = ready_handler;
  8705. tmp_rh->data_handler = data_handler;
  8706. tmp_rh->close_handler = close_handler;
  8707. } else { /* AUTH_HANDLER */
  8708. tmp_rh->auth_handler = auth_handler;
  8709. }
  8710. tmp_rh->cbdata = cbdata;
  8711. } else {
  8712. /* remove existing handler */
  8713. *lastref = tmp_rh->next;
  8714. mg_free(tmp_rh->uri);
  8715. mg_free(tmp_rh);
  8716. }
  8717. mg_unlock_context(ctx);
  8718. return;
  8719. }
  8720. }
  8721. lastref = &(tmp_rh->next);
  8722. }
  8723. if (is_delete_request) {
  8724. /* no handler to set, this was a remove request to a non-existing
  8725. * handler */
  8726. mg_unlock_context(ctx);
  8727. return;
  8728. }
  8729. tmp_rh =
  8730. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8731. if (tmp_rh == NULL) {
  8732. mg_unlock_context(ctx);
  8733. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8734. return;
  8735. }
  8736. tmp_rh->uri = mg_strdup(uri);
  8737. if (!tmp_rh->uri) {
  8738. mg_unlock_context(ctx);
  8739. mg_free(tmp_rh);
  8740. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8741. return;
  8742. }
  8743. tmp_rh->uri_len = urilen;
  8744. if (handler_type == REQUEST_HANDLER) {
  8745. tmp_rh->handler = handler;
  8746. } else if (handler_type == WEBSOCKET_HANDLER) {
  8747. tmp_rh->connect_handler = connect_handler;
  8748. tmp_rh->ready_handler = ready_handler;
  8749. tmp_rh->data_handler = data_handler;
  8750. tmp_rh->close_handler = close_handler;
  8751. } else { /* AUTH_HANDLER */
  8752. tmp_rh->auth_handler = auth_handler;
  8753. }
  8754. tmp_rh->cbdata = cbdata;
  8755. tmp_rh->handler_type = handler_type;
  8756. tmp_rh->next = NULL;
  8757. *lastref = tmp_rh;
  8758. mg_unlock_context(ctx);
  8759. }
  8760. void
  8761. mg_set_request_handler(struct mg_context *ctx,
  8762. const char *uri,
  8763. mg_request_handler handler,
  8764. void *cbdata)
  8765. {
  8766. mg_set_handler_type(ctx,
  8767. uri,
  8768. REQUEST_HANDLER,
  8769. handler == NULL,
  8770. handler,
  8771. NULL,
  8772. NULL,
  8773. NULL,
  8774. NULL,
  8775. NULL,
  8776. cbdata);
  8777. }
  8778. void
  8779. mg_set_websocket_handler(struct mg_context *ctx,
  8780. const char *uri,
  8781. mg_websocket_connect_handler connect_handler,
  8782. mg_websocket_ready_handler ready_handler,
  8783. mg_websocket_data_handler data_handler,
  8784. mg_websocket_close_handler close_handler,
  8785. void *cbdata)
  8786. {
  8787. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8788. && (data_handler == NULL)
  8789. && (close_handler == NULL);
  8790. mg_set_handler_type(ctx,
  8791. uri,
  8792. WEBSOCKET_HANDLER,
  8793. is_delete_request,
  8794. NULL,
  8795. connect_handler,
  8796. ready_handler,
  8797. data_handler,
  8798. close_handler,
  8799. NULL,
  8800. cbdata);
  8801. }
  8802. void
  8803. mg_set_auth_handler(struct mg_context *ctx,
  8804. const char *uri,
  8805. mg_request_handler handler,
  8806. void *cbdata)
  8807. {
  8808. mg_set_handler_type(ctx,
  8809. uri,
  8810. AUTH_HANDLER,
  8811. handler == NULL,
  8812. NULL,
  8813. NULL,
  8814. NULL,
  8815. NULL,
  8816. NULL,
  8817. handler,
  8818. cbdata);
  8819. }
  8820. static int
  8821. get_request_handler(struct mg_connection *conn,
  8822. int handler_type,
  8823. mg_request_handler *handler,
  8824. mg_websocket_connect_handler *connect_handler,
  8825. mg_websocket_ready_handler *ready_handler,
  8826. mg_websocket_data_handler *data_handler,
  8827. mg_websocket_close_handler *close_handler,
  8828. mg_authorization_handler *auth_handler,
  8829. void **cbdata)
  8830. {
  8831. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8832. if (request_info) {
  8833. const char *uri = request_info->local_uri;
  8834. size_t urilen = strlen(uri);
  8835. struct mg_handler_info *tmp_rh;
  8836. if (!conn || !conn->ctx) {
  8837. return 0;
  8838. }
  8839. mg_lock_context(conn->ctx);
  8840. /* first try for an exact match */
  8841. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8842. tmp_rh = tmp_rh->next) {
  8843. if (tmp_rh->handler_type == handler_type) {
  8844. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8845. if (handler_type == WEBSOCKET_HANDLER) {
  8846. *connect_handler = tmp_rh->connect_handler;
  8847. *ready_handler = tmp_rh->ready_handler;
  8848. *data_handler = tmp_rh->data_handler;
  8849. *close_handler = tmp_rh->close_handler;
  8850. } else if (handler_type == REQUEST_HANDLER) {
  8851. *handler = tmp_rh->handler;
  8852. } else { /* AUTH_HANDLER */
  8853. *auth_handler = tmp_rh->auth_handler;
  8854. }
  8855. *cbdata = tmp_rh->cbdata;
  8856. mg_unlock_context(conn->ctx);
  8857. return 1;
  8858. }
  8859. }
  8860. }
  8861. /* next try for a partial match, we will accept uri/something */
  8862. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8863. tmp_rh = tmp_rh->next) {
  8864. if (tmp_rh->handler_type == handler_type) {
  8865. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8866. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8867. if (handler_type == WEBSOCKET_HANDLER) {
  8868. *connect_handler = tmp_rh->connect_handler;
  8869. *ready_handler = tmp_rh->ready_handler;
  8870. *data_handler = tmp_rh->data_handler;
  8871. *close_handler = tmp_rh->close_handler;
  8872. } else if (handler_type == REQUEST_HANDLER) {
  8873. *handler = tmp_rh->handler;
  8874. } else { /* AUTH_HANDLER */
  8875. *auth_handler = tmp_rh->auth_handler;
  8876. }
  8877. *cbdata = tmp_rh->cbdata;
  8878. mg_unlock_context(conn->ctx);
  8879. return 1;
  8880. }
  8881. }
  8882. }
  8883. /* finally try for pattern match */
  8884. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8885. tmp_rh = tmp_rh->next) {
  8886. if (tmp_rh->handler_type == handler_type) {
  8887. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8888. if (handler_type == WEBSOCKET_HANDLER) {
  8889. *connect_handler = tmp_rh->connect_handler;
  8890. *ready_handler = tmp_rh->ready_handler;
  8891. *data_handler = tmp_rh->data_handler;
  8892. *close_handler = tmp_rh->close_handler;
  8893. } else if (handler_type == REQUEST_HANDLER) {
  8894. *handler = tmp_rh->handler;
  8895. } else { /* AUTH_HANDLER */
  8896. *auth_handler = tmp_rh->auth_handler;
  8897. }
  8898. *cbdata = tmp_rh->cbdata;
  8899. mg_unlock_context(conn->ctx);
  8900. return 1;
  8901. }
  8902. }
  8903. }
  8904. mg_unlock_context(conn->ctx);
  8905. }
  8906. return 0; /* none found */
  8907. }
  8908. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8909. static int
  8910. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8911. void *cbdata)
  8912. {
  8913. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8914. if (pcallbacks->websocket_connect) {
  8915. return pcallbacks->websocket_connect(conn);
  8916. }
  8917. /* No handler set - assume "OK" */
  8918. return 0;
  8919. }
  8920. static void
  8921. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8922. {
  8923. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8924. if (pcallbacks->websocket_ready) {
  8925. pcallbacks->websocket_ready(conn);
  8926. }
  8927. }
  8928. static int
  8929. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8930. int bits,
  8931. char *data,
  8932. size_t len,
  8933. void *cbdata)
  8934. {
  8935. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8936. if (pcallbacks->websocket_data) {
  8937. return pcallbacks->websocket_data(conn, bits, data, len);
  8938. }
  8939. /* No handler set - assume "OK" */
  8940. return 1;
  8941. }
  8942. #endif
  8943. /* This is the heart of the Civetweb's logic.
  8944. * This function is called when the request is read, parsed and validated,
  8945. * and Civetweb must decide what action to take: serve a file, or
  8946. * a directory, or call embedded function, etcetera. */
  8947. static void
  8948. handle_request(struct mg_connection *conn)
  8949. {
  8950. if (conn) {
  8951. struct mg_request_info *ri = &conn->request_info;
  8952. char path[PATH_MAX];
  8953. int uri_len, ssl_index;
  8954. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8955. is_put_or_delete_request = 0, is_callback_resource = 0;
  8956. int i;
  8957. struct file file = STRUCT_FILE_INITIALIZER;
  8958. mg_request_handler callback_handler = NULL;
  8959. mg_websocket_connect_handler ws_connect_handler = NULL;
  8960. mg_websocket_ready_handler ws_ready_handler = NULL;
  8961. mg_websocket_data_handler ws_data_handler = NULL;
  8962. mg_websocket_close_handler ws_close_handler = NULL;
  8963. void *callback_data = NULL;
  8964. mg_authorization_handler auth_handler = NULL;
  8965. void *auth_callback_data = NULL;
  8966. #if !defined(NO_FILES)
  8967. time_t curtime = time(NULL);
  8968. char date[64];
  8969. #endif
  8970. path[0] = 0;
  8971. if (!ri) {
  8972. return;
  8973. }
  8974. /* 1. get the request url */
  8975. /* 1.1. split into url and query string */
  8976. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8977. != NULL) {
  8978. *((char *)conn->request_info.query_string++) = '\0';
  8979. }
  8980. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8981. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8982. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8983. if (ssl_index >= 0) {
  8984. redirect_to_https_port(conn, ssl_index);
  8985. } else {
  8986. /* A http to https forward port has been specified,
  8987. * but no https port to forward to. */
  8988. send_http_error(conn,
  8989. 503,
  8990. "%s",
  8991. "Error: SSL forward not configured properly");
  8992. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8993. }
  8994. return;
  8995. }
  8996. uri_len = (int)strlen(ri->local_uri);
  8997. /* 1.3. decode url (if config says so) */
  8998. if (should_decode_url(conn)) {
  8999. mg_url_decode(
  9000. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9001. }
  9002. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9003. * not possible */
  9004. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9005. /* step 1. completed, the url is known now */
  9006. uri_len = (int)strlen(ri->local_uri);
  9007. DEBUG_TRACE("URL: %s", ri->local_uri);
  9008. /* 3. if this ip has limited speed, set it for this connection */
  9009. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9010. get_remote_ip(conn),
  9011. ri->local_uri);
  9012. /* 4. call a "handle everything" callback, if registered */
  9013. if (conn->ctx->callbacks.begin_request != NULL) {
  9014. /* Note that since V1.7 the "begin_request" function is called
  9015. * before an authorization check. If an authorization check is
  9016. * required, use a request_handler instead. */
  9017. i = conn->ctx->callbacks.begin_request(conn);
  9018. if (i > 0) {
  9019. /* callback already processed the request. Store the
  9020. return value as a status code for the access log. */
  9021. conn->status_code = i;
  9022. discard_unread_request_data(conn);
  9023. return;
  9024. } else if (i == 0) {
  9025. /* civetweb should process the request */
  9026. } else {
  9027. /* unspecified - may change with the next version */
  9028. return;
  9029. }
  9030. }
  9031. /* request not yet handled by a handler or redirect, so the request
  9032. * is processed here */
  9033. /* 5. interpret the url to find out how the request must be handled
  9034. */
  9035. /* 5.1. first test, if the request targets the regular http(s)://
  9036. * protocol namespace or the websocket ws(s):// protocol namespace.
  9037. */
  9038. is_websocket_request = is_websocket_protocol(conn);
  9039. /* 5.2. check if the request will be handled by a callback */
  9040. if (get_request_handler(conn,
  9041. is_websocket_request ? WEBSOCKET_HANDLER
  9042. : REQUEST_HANDLER,
  9043. &callback_handler,
  9044. &ws_connect_handler,
  9045. &ws_ready_handler,
  9046. &ws_data_handler,
  9047. &ws_close_handler,
  9048. NULL,
  9049. &callback_data)) {
  9050. /* 5.2.1. A callback will handle this request. All requests
  9051. * handled
  9052. * by a callback have to be considered as requests to a script
  9053. * resource. */
  9054. is_callback_resource = 1;
  9055. is_script_resource = 1;
  9056. is_put_or_delete_request = is_put_or_delete_method(conn);
  9057. } else {
  9058. no_callback_resource:
  9059. /* 5.2.2. No callback is responsible for this request. The URI
  9060. * addresses a file based resource (static content or Lua/cgi
  9061. * scripts in the file system). */
  9062. is_callback_resource = 0;
  9063. interpret_uri(conn,
  9064. path,
  9065. sizeof(path),
  9066. &file,
  9067. &is_found,
  9068. &is_script_resource,
  9069. &is_websocket_request,
  9070. &is_put_or_delete_request);
  9071. }
  9072. /* 6. authorization check */
  9073. /* 6.1. a custom authorization handler is installed */
  9074. if (get_request_handler(conn,
  9075. AUTH_HANDLER,
  9076. NULL,
  9077. NULL,
  9078. NULL,
  9079. NULL,
  9080. NULL,
  9081. &auth_handler,
  9082. &auth_callback_data)) {
  9083. if (!auth_handler(conn, auth_callback_data)) {
  9084. return;
  9085. }
  9086. } else if (is_put_or_delete_request && !is_script_resource
  9087. && !is_callback_resource) {
  9088. /* 6.2. this request is a PUT/DELETE to a real file */
  9089. /* 6.2.1. thus, the server must have real files */
  9090. #if defined(NO_FILES)
  9091. if (1) {
  9092. #else
  9093. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9094. #endif
  9095. /* This server does not have any real files, thus the
  9096. * PUT/DELETE methods are not valid. */
  9097. send_http_error(conn,
  9098. 405,
  9099. "%s method not allowed",
  9100. conn->request_info.request_method);
  9101. return;
  9102. }
  9103. #if !defined(NO_FILES)
  9104. /* 6.2.2. Check if put authorization for static files is
  9105. * available.
  9106. */
  9107. if (!is_authorized_for_put(conn)) {
  9108. send_authorization_request(conn);
  9109. return;
  9110. }
  9111. #endif
  9112. } else {
  9113. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9114. * or it is a PUT or DELETE request to a resource that does not
  9115. * correspond to a file. Check authorization. */
  9116. if (!check_authorization(conn, path)) {
  9117. send_authorization_request(conn);
  9118. return;
  9119. }
  9120. }
  9121. /* request is authorized or does not need authorization */
  9122. /* 7. check if there are request handlers for this uri */
  9123. if (is_callback_resource) {
  9124. if (!is_websocket_request) {
  9125. i = callback_handler(conn, callback_data);
  9126. if (i > 0) {
  9127. /* Do nothing, callback has served the request. Store
  9128. * the
  9129. * return value as status code for the log and discard
  9130. * all
  9131. * data from the client not used by the callback. */
  9132. conn->status_code = i;
  9133. discard_unread_request_data(conn);
  9134. } else {
  9135. /* TODO (high): what if the handler did NOT handle the
  9136. * request */
  9137. /* The last version did handle this as a file request,
  9138. * but
  9139. * since a file request is not always a script resource,
  9140. * the authorization check might be different */
  9141. interpret_uri(conn,
  9142. path,
  9143. sizeof(path),
  9144. &file,
  9145. &is_found,
  9146. &is_script_resource,
  9147. &is_websocket_request,
  9148. &is_put_or_delete_request);
  9149. callback_handler = NULL;
  9150. /* TODO (very low): goto is deprecated but for the
  9151. * moment,
  9152. * a goto is simpler than some curious loop. */
  9153. /* The situation "callback does not handle the request"
  9154. * needs to be reconsidered anyway. */
  9155. goto no_callback_resource;
  9156. }
  9157. } else {
  9158. #if defined(USE_WEBSOCKET)
  9159. handle_websocket_request(conn,
  9160. path,
  9161. is_callback_resource,
  9162. ws_connect_handler,
  9163. ws_ready_handler,
  9164. ws_data_handler,
  9165. ws_close_handler,
  9166. callback_data);
  9167. #endif
  9168. }
  9169. return;
  9170. }
  9171. /* 8. handle websocket requests */
  9172. #if defined(USE_WEBSOCKET)
  9173. if (is_websocket_request) {
  9174. if (is_script_resource) {
  9175. /* Websocket Lua script */
  9176. handle_websocket_request(conn,
  9177. path,
  9178. 0 /* Lua Script */,
  9179. NULL,
  9180. NULL,
  9181. NULL,
  9182. NULL,
  9183. &conn->ctx->callbacks);
  9184. } else {
  9185. #if defined(MG_LEGACY_INTERFACE)
  9186. handle_websocket_request(
  9187. conn,
  9188. path,
  9189. !is_script_resource /* could be deprecated global callback */,
  9190. deprecated_websocket_connect_wrapper,
  9191. deprecated_websocket_ready_wrapper,
  9192. deprecated_websocket_data_wrapper,
  9193. NULL,
  9194. &conn->ctx->callbacks);
  9195. #else
  9196. send_http_error(conn, 404, "%s", "Not found");
  9197. #endif
  9198. }
  9199. return;
  9200. } else
  9201. #endif
  9202. #if defined(NO_FILES)
  9203. /* 9a. In case the server uses only callbacks, this uri is
  9204. * unknown.
  9205. * Then, all request handling ends here. */
  9206. send_http_error(conn, 404, "%s", "Not Found");
  9207. #else
  9208. /* 9b. This request is either for a static file or resource handled
  9209. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9210. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9211. send_http_error(conn, 404, "%s", "Not Found");
  9212. return;
  9213. }
  9214. /* 10. File is handled by a script. */
  9215. if (is_script_resource) {
  9216. handle_file_based_request(conn, path, &file);
  9217. return;
  9218. }
  9219. /* 11. Handle put/delete/mkcol requests */
  9220. if (is_put_or_delete_request) {
  9221. /* 11.1. PUT method */
  9222. if (!strcmp(ri->request_method, "PUT")) {
  9223. put_file(conn, path);
  9224. return;
  9225. }
  9226. /* 11.2. DELETE method */
  9227. if (!strcmp(ri->request_method, "DELETE")) {
  9228. delete_file(conn, path);
  9229. return;
  9230. }
  9231. /* 11.3. MKCOL method */
  9232. if (!strcmp(ri->request_method, "MKCOL")) {
  9233. mkcol(conn, path);
  9234. return;
  9235. }
  9236. /* 11.4. PATCH method
  9237. * This method is not supported for static resources,
  9238. * only for scripts (Lua, CGI) and callbacks. */
  9239. send_http_error(conn,
  9240. 405,
  9241. "%s method not allowed",
  9242. conn->request_info.request_method);
  9243. return;
  9244. }
  9245. /* 11. File does not exist, or it was configured that it should be
  9246. * hidden */
  9247. if (!is_found || (must_hide_file(conn, path))) {
  9248. send_http_error(conn, 404, "%s", "Not found");
  9249. return;
  9250. }
  9251. /* 12. Directory uris should end with a slash */
  9252. if (file.is_directory && (uri_len > 0)
  9253. && (ri->local_uri[uri_len - 1] != '/')) {
  9254. gmt_time_string(date, sizeof(date), &curtime);
  9255. mg_printf(conn,
  9256. "HTTP/1.1 301 Moved Permanently\r\n"
  9257. "Location: %s/\r\n"
  9258. "Date: %s\r\n"
  9259. /* "Cache-Control: private\r\n" (= default) */
  9260. "Content-Length: 0\r\n"
  9261. "Connection: %s\r\n\r\n",
  9262. ri->request_uri,
  9263. date,
  9264. suggest_connection_header(conn));
  9265. return;
  9266. }
  9267. /* 13. Handle other methods than GET/HEAD */
  9268. /* 13.1. Handle PROPFIND */
  9269. if (!strcmp(ri->request_method, "PROPFIND")) {
  9270. handle_propfind(conn, path, &file);
  9271. return;
  9272. }
  9273. /* 13.2. Handle OPTIONS for files */
  9274. if (!strcmp(ri->request_method, "OPTIONS")) {
  9275. /* This standard handler is only used for real files.
  9276. * Scripts should support the OPTIONS method themselves, to allow a
  9277. * maximum flexibility.
  9278. * Lua and CGI scripts may fully support CORS this way (including
  9279. * preflights). */
  9280. send_options(conn);
  9281. return;
  9282. }
  9283. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9284. if (0 != strcmp(ri->request_method, "GET")
  9285. && 0 != strcmp(ri->request_method, "HEAD")) {
  9286. send_http_error(conn,
  9287. 405,
  9288. "%s method not allowed",
  9289. conn->request_info.request_method);
  9290. return;
  9291. }
  9292. /* 14. directories */
  9293. if (file.is_directory) {
  9294. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9295. /* 14.1. use a substitute file */
  9296. /* TODO (high): substitute index may be a script resource.
  9297. * define what should be possible in this case. */
  9298. } else {
  9299. /* 14.2. no substitute file */
  9300. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9301. "yes")) {
  9302. handle_directory_request(conn, path);
  9303. } else {
  9304. send_http_error(conn,
  9305. 403,
  9306. "%s",
  9307. "Error: Directory listing denied");
  9308. }
  9309. return;
  9310. }
  9311. }
  9312. handle_file_based_request(conn, path, &file);
  9313. #endif /* !defined(NO_FILES) */
  9314. #if 0
  9315. /* Perform redirect and auth checks before calling begin_request()
  9316. * handler.
  9317. * Otherwise, begin_request() would need to perform auth checks and
  9318. * redirects. */
  9319. #endif
  9320. }
  9321. return;
  9322. }
  9323. static void
  9324. handle_file_based_request(struct mg_connection *conn,
  9325. const char *path,
  9326. struct file *file)
  9327. {
  9328. if (!conn || !conn->ctx) {
  9329. return;
  9330. }
  9331. if (0) {
  9332. #ifdef USE_LUA
  9333. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9334. strlen(
  9335. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9336. path) > 0) {
  9337. /* Lua server page: an SSI like page containing mostly plain html
  9338. * code
  9339. * plus some tags with server generated contents. */
  9340. handle_lsp_request(conn, path, file, NULL);
  9341. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9342. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9343. path) > 0) {
  9344. /* Lua in-server module script: a CGI like script used to generate
  9345. * the
  9346. * entire reply. */
  9347. mg_exec_lua_script(conn, path, NULL);
  9348. #endif
  9349. #if defined(USE_DUKTAPE)
  9350. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9351. strlen(
  9352. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9353. path) > 0) {
  9354. /* Call duktape to generate the page */
  9355. mg_exec_duktape_script(conn, path);
  9356. #endif
  9357. #if !defined(NO_CGI)
  9358. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9359. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9360. path) > 0) {
  9361. /* CGI scripts may support all HTTP methods */
  9362. handle_cgi_request(conn, path);
  9363. #endif /* !NO_CGI */
  9364. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9365. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9366. path) > 0) {
  9367. handle_ssi_file_request(conn, path, file);
  9368. #if !defined(NO_CACHING)
  9369. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9370. /* Send 304 "Not Modified" - this must not send any body data */
  9371. handle_not_modified_static_file_request(conn, file);
  9372. #endif /* !NO_CACHING */
  9373. } else {
  9374. handle_static_file_request(conn, path, file, NULL, NULL);
  9375. }
  9376. }
  9377. static void
  9378. close_all_listening_sockets(struct mg_context *ctx)
  9379. {
  9380. unsigned int i;
  9381. if (!ctx) {
  9382. return;
  9383. }
  9384. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9385. closesocket(ctx->listening_sockets[i].sock);
  9386. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9387. }
  9388. mg_free(ctx->listening_sockets);
  9389. ctx->listening_sockets = NULL;
  9390. mg_free(ctx->listening_socket_fds);
  9391. ctx->listening_socket_fds = NULL;
  9392. }
  9393. /* Valid listening port specification is: [ip_address:]port[s]
  9394. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9395. * Examples for IPv6: [::]:80, [::1]:80,
  9396. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9397. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9398. * In order to bind to both, IPv4 and IPv6, you can either add
  9399. * both ports using 8080,[::]:8080, or the short form +8080.
  9400. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9401. * one only accepting IPv4 the other only IPv6. +8080 creates
  9402. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9403. * environment, they might work differently, or might not work
  9404. * at all - it must be tested what options work best in the
  9405. * relevant network environment.
  9406. */
  9407. static int
  9408. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9409. {
  9410. unsigned int a, b, c, d, port;
  9411. int ch, len;
  9412. #if defined(USE_IPV6)
  9413. char buf[100] = {0};
  9414. #endif
  9415. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9416. * Also, all-zeroes in the socket address means binding to all addresses
  9417. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9418. memset(so, 0, sizeof(*so));
  9419. so->lsa.sin.sin_family = AF_INET;
  9420. *ip_version = 0;
  9421. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9422. == 5) {
  9423. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9424. so->lsa.sin.sin_addr.s_addr =
  9425. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9426. so->lsa.sin.sin_port = htons((uint16_t)port);
  9427. *ip_version = 4;
  9428. #if defined(USE_IPV6)
  9429. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9430. && mg_inet_pton(
  9431. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9432. /* IPv6 address, examples: see above */
  9433. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9434. */
  9435. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9436. *ip_version = 6;
  9437. #endif
  9438. } else if ((vec->ptr[0] == '+')
  9439. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9440. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9441. /* Add 1 to len for the + character we skipped before */
  9442. len++;
  9443. #if defined(USE_IPV6)
  9444. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9445. so->lsa.sin6.sin6_family = AF_INET6;
  9446. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9447. *ip_version = 4 + 6;
  9448. #else
  9449. /* Bind to IPv4 only, since IPv6 is not built in. */
  9450. so->lsa.sin.sin_port = htons((uint16_t)port);
  9451. *ip_version = 4;
  9452. #endif
  9453. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9454. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9455. so->lsa.sin.sin_port = htons((uint16_t)port);
  9456. *ip_version = 4;
  9457. } else {
  9458. /* Parsing failure. Make port invalid. */
  9459. port = 0;
  9460. len = 0;
  9461. }
  9462. /* sscanf and the option splitting code ensure the following condition
  9463. */
  9464. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9465. *ip_version = 0;
  9466. return 0;
  9467. }
  9468. ch = vec->ptr[len]; /* Next character after the port number */
  9469. so->is_ssl = (ch == 's');
  9470. so->ssl_redir = (ch == 'r');
  9471. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9472. if (is_valid_port(port)
  9473. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9474. return 1;
  9475. }
  9476. /* Reset ip_version to 0 of there is an error */
  9477. *ip_version = 0;
  9478. return 0;
  9479. }
  9480. static int
  9481. set_ports_option(struct mg_context *ctx)
  9482. {
  9483. const char *list;
  9484. int on = 1;
  9485. #if defined(USE_IPV6)
  9486. int off = 0;
  9487. #endif
  9488. struct vec vec;
  9489. struct socket so, *ptr;
  9490. struct pollfd *pfd;
  9491. union usa usa;
  9492. socklen_t len;
  9493. int ip_version;
  9494. int portsTotal = 0;
  9495. int portsOk = 0;
  9496. if (!ctx) {
  9497. return 0;
  9498. }
  9499. memset(&so, 0, sizeof(so));
  9500. memset(&usa, 0, sizeof(usa));
  9501. len = sizeof(usa);
  9502. list = ctx->config[LISTENING_PORTS];
  9503. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9504. portsTotal++;
  9505. if (!parse_port_string(&vec, &so, &ip_version)) {
  9506. mg_cry(fc(ctx),
  9507. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9508. (int)vec.len,
  9509. vec.ptr,
  9510. portsTotal,
  9511. "[IP_ADDRESS:]PORT[s|r]");
  9512. continue;
  9513. }
  9514. #if !defined(NO_SSL)
  9515. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9516. mg_cry(fc(ctx),
  9517. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9518. "option set?",
  9519. portsTotal);
  9520. continue;
  9521. }
  9522. #endif
  9523. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9524. == INVALID_SOCKET) {
  9525. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9526. continue;
  9527. }
  9528. #ifdef _WIN32
  9529. /* Windows SO_REUSEADDR lets many procs binds to a
  9530. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9531. * if someone already has the socket -- DTL */
  9532. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9533. * Windows might need a few seconds before
  9534. * the same port can be used again in the
  9535. * same process, so a short Sleep may be
  9536. * required between mg_stop and mg_start.
  9537. */
  9538. if (setsockopt(so.sock,
  9539. SOL_SOCKET,
  9540. SO_EXCLUSIVEADDRUSE,
  9541. (SOCK_OPT_TYPE)&on,
  9542. sizeof(on)) != 0) {
  9543. /* Set reuse option, but don't abort on errors. */
  9544. mg_cry(fc(ctx),
  9545. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9546. portsTotal);
  9547. }
  9548. #else
  9549. if (setsockopt(so.sock,
  9550. SOL_SOCKET,
  9551. SO_REUSEADDR,
  9552. (SOCK_OPT_TYPE)&on,
  9553. sizeof(on)) != 0) {
  9554. /* Set reuse option, but don't abort on errors. */
  9555. mg_cry(fc(ctx),
  9556. "cannot set socket option SO_REUSEADDR (entry %i)",
  9557. portsTotal);
  9558. }
  9559. #endif
  9560. if (ip_version > 4) {
  9561. #if defined(USE_IPV6)
  9562. if (ip_version == 6) {
  9563. if (so.lsa.sa.sa_family == AF_INET6
  9564. && setsockopt(so.sock,
  9565. IPPROTO_IPV6,
  9566. IPV6_V6ONLY,
  9567. (void *)&off,
  9568. sizeof(off)) != 0) {
  9569. /* Set IPv6 only option, but don't abort on errors. */
  9570. mg_cry(fc(ctx),
  9571. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9572. portsTotal);
  9573. }
  9574. }
  9575. #else
  9576. mg_cry(fc(ctx), "IPv6 not available");
  9577. closesocket(so.sock);
  9578. so.sock = INVALID_SOCKET;
  9579. continue;
  9580. #endif
  9581. }
  9582. if (so.lsa.sa.sa_family == AF_INET) {
  9583. len = sizeof(so.lsa.sin);
  9584. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9585. mg_cry(fc(ctx),
  9586. "cannot bind to %.*s: %d (%s)",
  9587. (int)vec.len,
  9588. vec.ptr,
  9589. (int)ERRNO,
  9590. strerror(errno));
  9591. closesocket(so.sock);
  9592. so.sock = INVALID_SOCKET;
  9593. continue;
  9594. }
  9595. }
  9596. #if defined(USE_IPV6)
  9597. else if (so.lsa.sa.sa_family == AF_INET6) {
  9598. len = sizeof(so.lsa.sin6);
  9599. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9600. mg_cry(fc(ctx),
  9601. "cannot bind to IPv6 %.*s: %d (%s)",
  9602. (int)vec.len,
  9603. vec.ptr,
  9604. (int)ERRNO,
  9605. strerror(errno));
  9606. closesocket(so.sock);
  9607. so.sock = INVALID_SOCKET;
  9608. continue;
  9609. }
  9610. }
  9611. #endif
  9612. else {
  9613. mg_cry(fc(ctx),
  9614. "cannot bind: address family not supported (entry %i)",
  9615. portsTotal);
  9616. continue;
  9617. }
  9618. if (listen(so.sock, SOMAXCONN) != 0) {
  9619. mg_cry(fc(ctx),
  9620. "cannot listen to %.*s: %d (%s)",
  9621. (int)vec.len,
  9622. vec.ptr,
  9623. (int)ERRNO,
  9624. strerror(errno));
  9625. closesocket(so.sock);
  9626. so.sock = INVALID_SOCKET;
  9627. continue;
  9628. }
  9629. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9630. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9631. int err = (int)ERRNO;
  9632. mg_cry(fc(ctx),
  9633. "call to getsockname failed %.*s: %d (%s)",
  9634. (int)vec.len,
  9635. vec.ptr,
  9636. err,
  9637. strerror(errno));
  9638. closesocket(so.sock);
  9639. so.sock = INVALID_SOCKET;
  9640. continue;
  9641. }
  9642. /* Update lsa port in case of random free ports */
  9643. #if defined(USE_IPV6)
  9644. if (so.lsa.sa.sa_family == AF_INET6) {
  9645. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9646. } else
  9647. #endif
  9648. {
  9649. so.lsa.sin.sin_port = usa.sin.sin_port;
  9650. }
  9651. if ((ptr = (struct socket *)
  9652. mg_realloc(ctx->listening_sockets,
  9653. (ctx->num_listening_sockets + 1)
  9654. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9655. mg_cry(fc(ctx), "%s", "Out of memory");
  9656. closesocket(so.sock);
  9657. so.sock = INVALID_SOCKET;
  9658. continue;
  9659. }
  9660. if ((pfd = (struct pollfd *)mg_realloc(
  9661. ctx->listening_socket_fds,
  9662. (ctx->num_listening_sockets + 1)
  9663. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9664. mg_cry(fc(ctx), "%s", "Out of memory");
  9665. closesocket(so.sock);
  9666. so.sock = INVALID_SOCKET;
  9667. mg_free(ptr);
  9668. continue;
  9669. }
  9670. set_close_on_exec(so.sock, fc(ctx));
  9671. ctx->listening_sockets = ptr;
  9672. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9673. ctx->listening_socket_fds = pfd;
  9674. ctx->num_listening_sockets++;
  9675. portsOk++;
  9676. }
  9677. if (portsOk != portsTotal) {
  9678. close_all_listening_sockets(ctx);
  9679. portsOk = 0;
  9680. }
  9681. return portsOk;
  9682. }
  9683. static const char *
  9684. header_val(const struct mg_connection *conn, const char *header)
  9685. {
  9686. const char *header_value;
  9687. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9688. return "-";
  9689. } else {
  9690. return header_value;
  9691. }
  9692. }
  9693. static void
  9694. log_access(const struct mg_connection *conn)
  9695. {
  9696. const struct mg_request_info *ri;
  9697. struct file fi;
  9698. char date[64], src_addr[IP_ADDR_STR_LEN];
  9699. struct tm *tm;
  9700. const char *referer;
  9701. const char *user_agent;
  9702. char buf[4096];
  9703. if (!conn || !conn->ctx) {
  9704. return;
  9705. }
  9706. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9707. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9708. == 0) {
  9709. fi.fp = NULL;
  9710. }
  9711. } else {
  9712. fi.fp = NULL;
  9713. }
  9714. /* Log is written to a file and/or a callback. If both are not set,
  9715. * executing the rest of the function is pointless. */
  9716. if ((fi.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9717. return;
  9718. }
  9719. tm = localtime(&conn->conn_birth_time);
  9720. if (tm != NULL) {
  9721. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9722. } else {
  9723. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9724. date[sizeof(date) - 1] = '\0';
  9725. }
  9726. ri = &conn->request_info;
  9727. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9728. referer = header_val(conn, "Referer");
  9729. user_agent = header_val(conn, "User-Agent");
  9730. mg_snprintf(conn,
  9731. NULL, /* Ignore truncation in access log */
  9732. buf,
  9733. sizeof(buf),
  9734. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9735. src_addr,
  9736. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9737. date,
  9738. ri->request_method ? ri->request_method : "-",
  9739. ri->request_uri ? ri->request_uri : "-",
  9740. ri->query_string ? "?" : "",
  9741. ri->query_string ? ri->query_string : "",
  9742. ri->http_version,
  9743. conn->status_code,
  9744. conn->num_bytes_sent,
  9745. referer,
  9746. user_agent);
  9747. if (conn->ctx->callbacks.log_access) {
  9748. conn->ctx->callbacks.log_access(conn, buf);
  9749. }
  9750. if (fi.fp) {
  9751. flockfile(fi.fp);
  9752. fprintf(fi.fp, "%s\n", buf);
  9753. fflush(fi.fp);
  9754. funlockfile(fi.fp);
  9755. mg_fclose(&fi);
  9756. }
  9757. }
  9758. /* Verify given socket address against the ACL.
  9759. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9760. */
  9761. static int
  9762. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9763. {
  9764. int allowed, flag;
  9765. uint32_t net, mask;
  9766. struct vec vec;
  9767. if (ctx) {
  9768. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9769. /* If any ACL is set, deny by default */
  9770. allowed = (list == NULL) ? '+' : '-';
  9771. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9772. flag = vec.ptr[0];
  9773. if ((flag != '+' && flag != '-')
  9774. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9775. mg_cry(fc(ctx),
  9776. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9777. __func__);
  9778. return -1;
  9779. }
  9780. if (net == (remote_ip & mask)) {
  9781. allowed = flag;
  9782. }
  9783. }
  9784. return allowed == '+';
  9785. }
  9786. return -1;
  9787. }
  9788. #if !defined(_WIN32)
  9789. static int
  9790. set_uid_option(struct mg_context *ctx)
  9791. {
  9792. struct passwd *pw;
  9793. if (ctx) {
  9794. const char *uid = ctx->config[RUN_AS_USER];
  9795. int success = 0;
  9796. if (uid == NULL) {
  9797. success = 1;
  9798. } else {
  9799. if ((pw = getpwnam(uid)) == NULL) {
  9800. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9801. } else if (setgid(pw->pw_gid) == -1) {
  9802. mg_cry(fc(ctx),
  9803. "%s: setgid(%s): %s",
  9804. __func__,
  9805. uid,
  9806. strerror(errno));
  9807. } else if (setgroups(0, NULL)) {
  9808. mg_cry(fc(ctx),
  9809. "%s: setgroups(): %s",
  9810. __func__,
  9811. strerror(errno));
  9812. } else if (setuid(pw->pw_uid) == -1) {
  9813. mg_cry(fc(ctx),
  9814. "%s: setuid(%s): %s",
  9815. __func__,
  9816. uid,
  9817. strerror(errno));
  9818. } else {
  9819. success = 1;
  9820. }
  9821. }
  9822. return success;
  9823. }
  9824. return 0;
  9825. }
  9826. #endif /* !_WIN32 */
  9827. static void
  9828. tls_dtor(void *key)
  9829. {
  9830. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9831. /* key == pthread_getspecific(sTlsKey); */
  9832. if (tls) {
  9833. if (tls->is_master == 2) {
  9834. tls->is_master = -3; /* Mark memory as dead */
  9835. mg_free(tls);
  9836. }
  9837. }
  9838. pthread_setspecific(sTlsKey, NULL);
  9839. }
  9840. #if !defined(NO_SSL)
  9841. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9842. static unsigned long
  9843. ssl_id_callback(void)
  9844. {
  9845. #ifdef _WIN32
  9846. return GetCurrentThreadId();
  9847. #else
  9848. #ifdef __clang__
  9849. #pragma clang diagnostic push
  9850. #pragma clang diagnostic ignored "-Wunreachable-code"
  9851. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9852. * or not, so one of the two conditions will be unreachable by construction.
  9853. * Unfortunately the C standard does not define a way to check this at
  9854. * compile time, since the #if preprocessor conditions can not use the sizeof
  9855. * operator as an argument. */
  9856. #endif
  9857. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9858. /* This is the problematic case for CRYPTO_set_id_callback:
  9859. * The OS pthread_t can not be cast to unsigned long. */
  9860. struct mg_workerTLS *tls =
  9861. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9862. if (tls == NULL) {
  9863. /* SSL called from an unknown thread: Create some thread index.
  9864. */
  9865. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9866. tls->is_master = -2; /* -2 means "3rd party thread" */
  9867. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9868. pthread_setspecific(sTlsKey, tls);
  9869. }
  9870. return tls->thread_idx;
  9871. } else {
  9872. /* pthread_t may be any data type, so a simple cast to unsigned long
  9873. * can rise a warning/error, depending on the platform.
  9874. * Here memcpy is used as an anything-to-anything cast. */
  9875. unsigned long ret = 0;
  9876. pthread_t t = pthread_self();
  9877. memcpy(&ret, &t, sizeof(pthread_t));
  9878. return ret;
  9879. }
  9880. #ifdef __clang__
  9881. #pragma clang diagnostic pop
  9882. #endif
  9883. #endif
  9884. }
  9885. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9886. static const char *ssl_error(void);
  9887. static int
  9888. refresh_trust(struct mg_connection *conn)
  9889. {
  9890. static int reload_lock = 0;
  9891. static long int data_check = 0;
  9892. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9893. struct stat cert_buf;
  9894. long int t;
  9895. char *pem;
  9896. int should_verify_peer;
  9897. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  9898. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  9899. * refresh_trust still can not work. */
  9900. return 0;
  9901. }
  9902. t = data_check;
  9903. if (stat(pem, &cert_buf) != -1) {
  9904. t = (long int)cert_buf.st_mtime;
  9905. }
  9906. if (data_check != t) {
  9907. data_check = t;
  9908. should_verify_peer =
  9909. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9910. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9911. == 0);
  9912. if (should_verify_peer) {
  9913. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9914. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9915. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9916. ca_file,
  9917. ca_path) != 1) {
  9918. mg_cry(fc(conn->ctx),
  9919. "SSL_CTX_load_verify_locations error: %s "
  9920. "ssl_verify_peer requires setting "
  9921. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9922. "present in "
  9923. "the .conf file?",
  9924. ssl_error());
  9925. return 0;
  9926. }
  9927. }
  9928. if (1 == mg_atomic_inc(p_reload_lock)) {
  9929. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9930. return 0;
  9931. }
  9932. *p_reload_lock = 0;
  9933. }
  9934. }
  9935. /* lock while cert is reloading */
  9936. while (*p_reload_lock) {
  9937. sleep(1);
  9938. }
  9939. return 1;
  9940. }
  9941. static pthread_mutex_t *ssl_mutexes;
  9942. static int
  9943. sslize(struct mg_connection *conn,
  9944. SSL_CTX *s,
  9945. int (*func)(SSL *),
  9946. volatile int *stop_server)
  9947. {
  9948. int ret, err;
  9949. int short_trust;
  9950. unsigned i;
  9951. if (!conn) {
  9952. return 0;
  9953. }
  9954. short_trust =
  9955. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9956. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9957. if (short_trust) {
  9958. int trust_ret = refresh_trust(conn);
  9959. if (!trust_ret) {
  9960. return trust_ret;
  9961. }
  9962. }
  9963. conn->ssl = SSL_new(s);
  9964. if (conn->ssl == NULL) {
  9965. return 0;
  9966. }
  9967. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9968. if (ret != 1) {
  9969. err = SSL_get_error(conn->ssl, ret);
  9970. (void)err; /* TODO: set some error message */
  9971. SSL_free(conn->ssl);
  9972. conn->ssl = NULL;
  9973. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9974. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9975. ERR_remove_state(0);
  9976. return 0;
  9977. }
  9978. /* SSL functions may fail and require to be called again:
  9979. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9980. * Here "func" could be SSL_connect or SSL_accept. */
  9981. for (i = 16; i <= 1024; i *= 2) {
  9982. ret = func(conn->ssl);
  9983. if (ret != 1) {
  9984. err = SSL_get_error(conn->ssl, ret);
  9985. if ((err == SSL_ERROR_WANT_CONNECT)
  9986. || (err == SSL_ERROR_WANT_ACCEPT)
  9987. || (err == SSL_ERROR_WANT_READ)
  9988. || (err == SSL_ERROR_WANT_WRITE)) {
  9989. /* Need to retry the function call "later".
  9990. * See https://linux.die.net/man/3/ssl_get_error
  9991. * This is typical for non-blocking sockets. */
  9992. if (*stop_server) {
  9993. /* Don't wait if the server is going to be stopped. */
  9994. break;
  9995. }
  9996. mg_sleep(i);
  9997. } else if (err == SSL_ERROR_SYSCALL) {
  9998. /* This is an IO error. Look at errno. */
  9999. err = errno;
  10000. /* TODO: set some error message */
  10001. break;
  10002. } else {
  10003. /* This is an SSL specific error */
  10004. /* TODO: set some error message */
  10005. break;
  10006. }
  10007. } else {
  10008. /* success */
  10009. break;
  10010. }
  10011. }
  10012. if (ret != 1) {
  10013. SSL_free(conn->ssl);
  10014. conn->ssl = NULL;
  10015. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10016. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10017. ERR_remove_state(0);
  10018. return 0;
  10019. }
  10020. return 1;
  10021. }
  10022. /* Return OpenSSL error message (from CRYPTO lib) */
  10023. static const char *
  10024. ssl_error(void)
  10025. {
  10026. unsigned long err;
  10027. err = ERR_get_error();
  10028. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10029. }
  10030. static int
  10031. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10032. {
  10033. int i;
  10034. const char hexdigit[] = "0123456789abcdef";
  10035. if (memlen <= 0 || buflen <= 0) {
  10036. return 0;
  10037. }
  10038. if (buflen < (3 * memlen)) {
  10039. return 0;
  10040. }
  10041. for (i = 0; i < memlen; i++) {
  10042. if (i > 0) {
  10043. buf[3 * i - 1] = ' ';
  10044. }
  10045. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10046. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10047. }
  10048. buf[3 * memlen - 1] = 0;
  10049. return 1;
  10050. }
  10051. static void
  10052. ssl_get_client_cert_info(struct mg_connection *conn)
  10053. {
  10054. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10055. if (cert) {
  10056. char str_subject[1024];
  10057. char str_issuer[1024];
  10058. char str_serial[1024];
  10059. char str_finger[1024];
  10060. unsigned char buf[256];
  10061. int len;
  10062. unsigned int ulen;
  10063. /* Handle to algorithm used for fingerprint */
  10064. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10065. /* Get Subject and issuer */
  10066. X509_NAME *subj = X509_get_subject_name(cert);
  10067. X509_NAME *iss = X509_get_issuer_name(cert);
  10068. /* Get serial number */
  10069. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10070. /* Translate subject and issuer to a string */
  10071. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10072. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10073. /* Translate serial number to a hex string */
  10074. len = i2c_ASN1_INTEGER(serial, NULL);
  10075. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10076. unsigned char *pbuf = buf;
  10077. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10078. if (!hexdump2string(
  10079. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10080. *str_serial = 0;
  10081. }
  10082. } else {
  10083. *str_serial = 0;
  10084. }
  10085. /* Calculate SHA1 fingerprint and store as a hex string */
  10086. ulen = 0;
  10087. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10088. if (!hexdump2string(
  10089. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10090. *str_finger = 0;
  10091. }
  10092. conn->request_info.client_cert =
  10093. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10094. if (conn->request_info.client_cert) {
  10095. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10096. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10097. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10098. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10099. } else {
  10100. /* TODO: write some OOM message */
  10101. }
  10102. X509_free(cert);
  10103. }
  10104. }
  10105. static void
  10106. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10107. {
  10108. (void)line;
  10109. (void)file;
  10110. if (mode & 1) {
  10111. /* 1 is CRYPTO_LOCK */
  10112. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10113. } else {
  10114. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10115. }
  10116. }
  10117. #if !defined(NO_SSL_DL)
  10118. static void *
  10119. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10120. {
  10121. union {
  10122. void *p;
  10123. void (*fp)(void);
  10124. } u;
  10125. void *dll_handle;
  10126. struct ssl_func *fp;
  10127. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10128. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10129. return NULL;
  10130. }
  10131. for (fp = sw; fp->name != NULL; fp++) {
  10132. #ifdef _WIN32
  10133. /* GetProcAddress() returns pointer to function */
  10134. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10135. #else
  10136. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10137. * pointers to function pointers. We need to use a union to make a
  10138. * cast. */
  10139. u.p = dlsym(dll_handle, fp->name);
  10140. #endif /* _WIN32 */
  10141. if (u.fp == NULL) {
  10142. mg_cry(fc(ctx),
  10143. "%s: %s: cannot find %s",
  10144. __func__,
  10145. dll_name,
  10146. fp->name);
  10147. dlclose(dll_handle);
  10148. return NULL;
  10149. } else {
  10150. fp->ptr = u.fp;
  10151. }
  10152. }
  10153. return dll_handle;
  10154. }
  10155. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10156. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10157. #endif /* NO_SSL_DL */
  10158. #if defined(SSL_ALREADY_INITIALIZED)
  10159. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10160. #else
  10161. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10162. #endif
  10163. static int
  10164. initialize_ssl(struct mg_context *ctx)
  10165. {
  10166. int i;
  10167. size_t size;
  10168. #if !defined(NO_SSL_DL)
  10169. if (!cryptolib_dll_handle) {
  10170. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10171. if (!cryptolib_dll_handle) {
  10172. return 0;
  10173. }
  10174. }
  10175. #endif /* NO_SSL_DL */
  10176. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10177. return 1;
  10178. }
  10179. /* Initialize locking callbacks, needed for thread safety.
  10180. * http://www.openssl.org/support/faq.html#PROG1
  10181. */
  10182. i = CRYPTO_num_locks();
  10183. if (i < 0) {
  10184. i = 0;
  10185. }
  10186. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10187. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10188. mg_cry(fc(ctx),
  10189. "%s: cannot allocate mutexes: %s",
  10190. __func__,
  10191. ssl_error());
  10192. return 0;
  10193. }
  10194. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10195. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10196. }
  10197. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10198. CRYPTO_set_id_callback(&ssl_id_callback);
  10199. return 1;
  10200. }
  10201. static int
  10202. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10203. {
  10204. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10205. mg_cry(fc(ctx),
  10206. "%s: cannot open certificate file %s: %s",
  10207. __func__,
  10208. pem,
  10209. ssl_error());
  10210. return 0;
  10211. }
  10212. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10213. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10214. mg_cry(fc(ctx),
  10215. "%s: cannot open private key file %s: %s",
  10216. __func__,
  10217. pem,
  10218. ssl_error());
  10219. return 0;
  10220. }
  10221. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10222. mg_cry(fc(ctx),
  10223. "%s: certificate and private key do not match: %s",
  10224. __func__,
  10225. pem);
  10226. return 0;
  10227. }
  10228. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10229. mg_cry(fc(ctx),
  10230. "%s: cannot use certificate chain file %s: %s",
  10231. __func__,
  10232. pem,
  10233. ssl_error());
  10234. return 0;
  10235. }
  10236. return 1;
  10237. }
  10238. static long
  10239. ssl_get_protocol(int version_id)
  10240. {
  10241. long ret = SSL_OP_ALL;
  10242. if (version_id > 0)
  10243. ret |= SSL_OP_NO_SSLv2;
  10244. if (version_id > 1)
  10245. ret |= SSL_OP_NO_SSLv3;
  10246. if (version_id > 2)
  10247. ret |= SSL_OP_NO_TLSv1;
  10248. if (version_id > 3)
  10249. ret |= SSL_OP_NO_TLSv1_1;
  10250. return ret;
  10251. }
  10252. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10253. static int
  10254. set_ssl_option(struct mg_context *ctx)
  10255. {
  10256. const char *pem;
  10257. int callback_ret;
  10258. int should_verify_peer;
  10259. const char *ca_path;
  10260. const char *ca_file;
  10261. int use_default_verify_paths;
  10262. int verify_depth;
  10263. time_t now_rt = time(NULL);
  10264. struct timespec now_mt;
  10265. md5_byte_t ssl_context_id[16];
  10266. md5_state_t md5state;
  10267. int protocol_ver;
  10268. /* If PEM file is not specified and the init_ssl callback
  10269. * is not specified, skip SSL initialization. */
  10270. if (!ctx) {
  10271. return 0;
  10272. }
  10273. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10274. && ctx->callbacks.init_ssl == NULL) {
  10275. return 1;
  10276. }
  10277. if (!initialize_ssl(ctx)) {
  10278. return 0;
  10279. }
  10280. #if !defined(NO_SSL_DL)
  10281. if (!ssllib_dll_handle) {
  10282. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10283. if (!ssllib_dll_handle) {
  10284. return 0;
  10285. }
  10286. }
  10287. #endif /* NO_SSL_DL */
  10288. /* Initialize SSL library */
  10289. SSL_library_init();
  10290. SSL_load_error_strings();
  10291. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10292. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10293. return 0;
  10294. }
  10295. SSL_CTX_clear_options(ctx->ssl_ctx,
  10296. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10297. | SSL_OP_NO_TLSv1_1);
  10298. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10299. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10300. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10301. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10302. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10303. /* If a callback has been specified, call it. */
  10304. callback_ret =
  10305. (ctx->callbacks.init_ssl == NULL)
  10306. ? 0
  10307. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10308. /* If callback returns 0, civetweb sets up the SSL certificate.
  10309. * If it returns 1, civetweb assumes the calback already did this.
  10310. * If it returns -1, initializing ssl fails. */
  10311. if (callback_ret < 0) {
  10312. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10313. return 0;
  10314. }
  10315. if (callback_ret > 0) {
  10316. if (pem != NULL) {
  10317. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10318. }
  10319. return 1;
  10320. }
  10321. /* Use some UID as session context ID. */
  10322. md5_init(&md5state);
  10323. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10324. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10325. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10326. md5_append(&md5state,
  10327. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10328. strlen(ctx->config[LISTENING_PORTS]));
  10329. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10330. md5_finish(&md5state, ssl_context_id);
  10331. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10332. (const unsigned char *)&ssl_context_id,
  10333. sizeof(ssl_context_id));
  10334. if (pem != NULL) {
  10335. if (!ssl_use_pem_file(ctx, pem)) {
  10336. return 0;
  10337. }
  10338. }
  10339. should_verify_peer =
  10340. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10341. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10342. use_default_verify_paths =
  10343. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10344. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10345. if (should_verify_peer) {
  10346. ca_path = ctx->config[SSL_CA_PATH];
  10347. ca_file = ctx->config[SSL_CA_FILE];
  10348. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10349. != 1) {
  10350. mg_cry(fc(ctx),
  10351. "SSL_CTX_load_verify_locations error: %s "
  10352. "ssl_verify_peer requires setting "
  10353. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10354. "present in "
  10355. "the .conf file?",
  10356. ssl_error());
  10357. return 0;
  10358. }
  10359. SSL_CTX_set_verify(ctx->ssl_ctx,
  10360. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10361. NULL);
  10362. if (use_default_verify_paths
  10363. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10364. mg_cry(fc(ctx),
  10365. "SSL_CTX_set_default_verify_paths error: %s",
  10366. ssl_error());
  10367. return 0;
  10368. }
  10369. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10370. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10371. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10372. }
  10373. }
  10374. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10375. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10376. != 1) {
  10377. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10378. }
  10379. }
  10380. return 1;
  10381. }
  10382. static void
  10383. uninitialize_ssl(struct mg_context *ctx)
  10384. {
  10385. int i;
  10386. (void)ctx;
  10387. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10388. /* Shutdown according to
  10389. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10390. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10391. */
  10392. CRYPTO_set_locking_callback(NULL);
  10393. CRYPTO_set_id_callback(NULL);
  10394. ENGINE_cleanup();
  10395. CONF_modules_unload(1);
  10396. ERR_free_strings();
  10397. EVP_cleanup();
  10398. CRYPTO_cleanup_all_ex_data();
  10399. ERR_remove_state(0);
  10400. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10401. pthread_mutex_destroy(&ssl_mutexes[i]);
  10402. }
  10403. mg_free(ssl_mutexes);
  10404. ssl_mutexes = NULL;
  10405. }
  10406. }
  10407. #endif /* !NO_SSL */
  10408. static int
  10409. set_gpass_option(struct mg_context *ctx)
  10410. {
  10411. if (ctx) {
  10412. struct file file = STRUCT_FILE_INITIALIZER;
  10413. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10414. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10415. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10416. return 0;
  10417. }
  10418. return 1;
  10419. }
  10420. return 0;
  10421. }
  10422. static int
  10423. set_acl_option(struct mg_context *ctx)
  10424. {
  10425. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10426. }
  10427. static void
  10428. reset_per_request_attributes(struct mg_connection *conn)
  10429. {
  10430. if (!conn) {
  10431. return;
  10432. }
  10433. conn->path_info = NULL;
  10434. conn->num_bytes_sent = conn->consumed_content = 0;
  10435. conn->status_code = -1;
  10436. conn->is_chunked = 0;
  10437. conn->must_close = conn->request_len = conn->throttle = 0;
  10438. conn->request_info.content_length = -1;
  10439. conn->request_info.remote_user = NULL;
  10440. conn->request_info.request_method = NULL;
  10441. conn->request_info.request_uri = NULL;
  10442. conn->request_info.local_uri = NULL;
  10443. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10444. * local_uri and request_uri */
  10445. conn->request_info.http_version = NULL;
  10446. conn->request_info.num_headers = 0;
  10447. conn->data_len = 0;
  10448. conn->chunk_remainder = 0;
  10449. conn->internal_error = 0;
  10450. }
  10451. static int
  10452. set_sock_timeout(SOCKET sock, int milliseconds)
  10453. {
  10454. int r0 = 0, r1, r2;
  10455. #ifdef _WIN32
  10456. /* Windows specific */
  10457. DWORD tv = (DWORD)milliseconds;
  10458. #else
  10459. /* Linux, ... (not Windows) */
  10460. struct timeval tv;
  10461. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10462. * max. time waiting for the acknowledged of TCP data before the connection
  10463. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10464. * If this option is not set, the default timeout of 20-30 minutes is used.
  10465. */
  10466. /* #define TCP_USER_TIMEOUT (18) */
  10467. #if defined(TCP_USER_TIMEOUT)
  10468. unsigned int uto = (unsigned int)milliseconds;
  10469. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10470. #endif
  10471. memset(&tv, 0, sizeof(tv));
  10472. tv.tv_sec = milliseconds / 1000;
  10473. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10474. #endif /* _WIN32 */
  10475. r1 = setsockopt(
  10476. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10477. r2 = setsockopt(
  10478. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10479. return r0 || r1 || r2;
  10480. }
  10481. static int
  10482. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10483. {
  10484. if (setsockopt(sock,
  10485. IPPROTO_TCP,
  10486. TCP_NODELAY,
  10487. (SOCK_OPT_TYPE)&nodelay_on,
  10488. sizeof(nodelay_on)) != 0) {
  10489. /* Error */
  10490. return 1;
  10491. }
  10492. /* OK */
  10493. return 0;
  10494. }
  10495. static void
  10496. close_socket_gracefully(struct mg_connection *conn)
  10497. {
  10498. #if defined(_WIN32)
  10499. char buf[MG_BUF_LEN];
  10500. int n;
  10501. #endif
  10502. struct linger linger;
  10503. int error_code = 0;
  10504. socklen_t opt_len = sizeof(error_code);
  10505. if (!conn) {
  10506. return;
  10507. }
  10508. /* Set linger option to avoid socket hanging out after close. This
  10509. * prevent ephemeral port exhaust problem under high QPS. */
  10510. linger.l_onoff = 1;
  10511. linger.l_linger = 1;
  10512. if (getsockopt(conn->client.sock,
  10513. SOL_SOCKET,
  10514. SO_ERROR,
  10515. (char *)&error_code,
  10516. &opt_len) != 0) {
  10517. /* Cannot determine if socket is already closed. This should
  10518. * not occur and never did in a test. Log an error message
  10519. * and continue. */
  10520. mg_cry(conn,
  10521. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10522. __func__,
  10523. strerror(ERRNO));
  10524. } else if (error_code == ECONNRESET) {
  10525. /* Socket already closed by client/peer, close socket without linger */
  10526. } else {
  10527. if (setsockopt(conn->client.sock,
  10528. SOL_SOCKET,
  10529. SO_LINGER,
  10530. (char *)&linger,
  10531. sizeof(linger)) != 0) {
  10532. mg_cry(conn,
  10533. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10534. __func__,
  10535. strerror(ERRNO));
  10536. }
  10537. }
  10538. /* Send FIN to the client */
  10539. shutdown(conn->client.sock, SHUTDOWN_WR);
  10540. set_non_blocking_mode(conn->client.sock);
  10541. #if defined(_WIN32)
  10542. /* Read and discard pending incoming data. If we do not do that and
  10543. * close
  10544. * the socket, the data in the send buffer may be discarded. This
  10545. * behaviour is seen on Windows, when client keeps sending data
  10546. * when server decides to close the connection; then when client
  10547. * does recv() it gets no data back. */
  10548. do {
  10549. n = pull(
  10550. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10551. } while (n > 0);
  10552. #endif
  10553. /* Now we know that our FIN is ACK-ed, safe to close */
  10554. closesocket(conn->client.sock);
  10555. conn->client.sock = INVALID_SOCKET;
  10556. }
  10557. static void
  10558. close_connection(struct mg_connection *conn)
  10559. {
  10560. if (!conn || !conn->ctx) {
  10561. return;
  10562. }
  10563. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10564. if (conn->lua_websocket_state) {
  10565. lua_websocket_close(conn, conn->lua_websocket_state);
  10566. conn->lua_websocket_state = NULL;
  10567. }
  10568. #endif
  10569. /* call the connection_close callback if assigned */
  10570. if ((conn->ctx->callbacks.connection_close != NULL)
  10571. && (conn->ctx->context_type == 1)) {
  10572. conn->ctx->callbacks.connection_close(conn);
  10573. }
  10574. mg_lock_connection(conn);
  10575. conn->must_close = 1;
  10576. #ifndef NO_SSL
  10577. if (conn->ssl != NULL) {
  10578. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10579. */
  10580. SSL_shutdown(conn->ssl);
  10581. SSL_free(conn->ssl);
  10582. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10583. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10584. ERR_remove_state(0);
  10585. conn->ssl = NULL;
  10586. }
  10587. #endif
  10588. if (conn->client.sock != INVALID_SOCKET) {
  10589. close_socket_gracefully(conn);
  10590. conn->client.sock = INVALID_SOCKET;
  10591. }
  10592. mg_unlock_connection(conn);
  10593. }
  10594. void
  10595. mg_close_connection(struct mg_connection *conn)
  10596. {
  10597. struct mg_context *client_ctx = NULL;
  10598. if (conn == NULL) {
  10599. return;
  10600. }
  10601. #if defined(USE_WEBSOCKET)
  10602. if (conn->ctx->context_type == 2) {
  10603. unsigned int i;
  10604. /* ws/wss client */
  10605. client_ctx = conn->ctx;
  10606. /* client context: loops must end */
  10607. conn->ctx->stop_flag = 1;
  10608. /* We need to get the client thread out of the select/recv call here. */
  10609. /* Since we use a sleep quantum of some seconds to check for recv
  10610. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10611. /* join worker thread */
  10612. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10613. if (client_ctx->workerthreadids[i] != 0) {
  10614. mg_join_thread(client_ctx->workerthreadids[i]);
  10615. }
  10616. }
  10617. }
  10618. #else
  10619. (void)client_ctx;
  10620. #endif
  10621. close_connection(conn);
  10622. #ifndef NO_SSL
  10623. if (conn->client_ssl_ctx != NULL) {
  10624. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10625. }
  10626. #endif
  10627. if (client_ctx != NULL) {
  10628. /* free context */
  10629. mg_free(client_ctx->workerthreadids);
  10630. mg_free(client_ctx);
  10631. (void)pthread_mutex_destroy(&conn->mutex);
  10632. mg_free(conn);
  10633. }
  10634. }
  10635. static struct mg_connection *
  10636. mg_connect_client_impl(const struct mg_client_options *client_options,
  10637. int use_ssl,
  10638. char *ebuf,
  10639. size_t ebuf_len)
  10640. {
  10641. static struct mg_context fake_ctx;
  10642. struct mg_connection *conn = NULL;
  10643. SOCKET sock;
  10644. union usa sa;
  10645. if (!connect_socket(&fake_ctx,
  10646. client_options->host,
  10647. client_options->port,
  10648. use_ssl,
  10649. ebuf,
  10650. ebuf_len,
  10651. &sock,
  10652. &sa)) {
  10653. ;
  10654. } else if ((conn = (struct mg_connection *)
  10655. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10656. mg_snprintf(NULL,
  10657. NULL, /* No truncation check for ebuf */
  10658. ebuf,
  10659. ebuf_len,
  10660. "calloc(): %s",
  10661. strerror(ERRNO));
  10662. closesocket(sock);
  10663. #ifndef NO_SSL
  10664. } else if (use_ssl
  10665. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10666. == NULL) {
  10667. mg_snprintf(NULL,
  10668. NULL, /* No truncation check for ebuf */
  10669. ebuf,
  10670. ebuf_len,
  10671. "SSL_CTX_new error");
  10672. closesocket(sock);
  10673. mg_free(conn);
  10674. conn = NULL;
  10675. #endif /* NO_SSL */
  10676. } else {
  10677. #ifdef USE_IPV6
  10678. socklen_t len = (sa.sa.sa_family == AF_INET)
  10679. ? sizeof(conn->client.rsa.sin)
  10680. : sizeof(conn->client.rsa.sin6);
  10681. struct sockaddr *psa =
  10682. (sa.sa.sa_family == AF_INET)
  10683. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10684. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10685. #else
  10686. socklen_t len = sizeof(conn->client.rsa.sin);
  10687. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10688. #endif
  10689. conn->buf_size = MAX_REQUEST_SIZE;
  10690. conn->buf = (char *)(conn + 1);
  10691. conn->ctx = &fake_ctx;
  10692. conn->client.sock = sock;
  10693. conn->client.lsa = sa;
  10694. if (getsockname(sock, psa, &len) != 0) {
  10695. mg_cry(conn,
  10696. "%s: getsockname() failed: %s",
  10697. __func__,
  10698. strerror(ERRNO));
  10699. }
  10700. conn->client.is_ssl = use_ssl ? 1 : 0;
  10701. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10702. #ifndef NO_SSL
  10703. if (use_ssl) {
  10704. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10705. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10706. * SSL_CTX_set_verify call is needed to switch off server
  10707. * certificate checking, which is off by default in OpenSSL and
  10708. * on in yaSSL. */
  10709. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10710. * SSL_VERIFY_PEER, verify_ssl_server); */
  10711. if (client_options->client_cert) {
  10712. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10713. mg_snprintf(NULL,
  10714. NULL, /* No truncation check for ebuf */
  10715. ebuf,
  10716. ebuf_len,
  10717. "Can not use SSL client certificate");
  10718. SSL_CTX_free(conn->client_ssl_ctx);
  10719. closesocket(sock);
  10720. mg_free(conn);
  10721. conn = NULL;
  10722. }
  10723. }
  10724. if (client_options->server_cert) {
  10725. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10726. client_options->server_cert,
  10727. NULL);
  10728. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10729. } else {
  10730. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10731. }
  10732. if (!sslize(conn,
  10733. conn->client_ssl_ctx,
  10734. SSL_connect,
  10735. &(conn->ctx->stop_flag))) {
  10736. mg_snprintf(NULL,
  10737. NULL, /* No truncation check for ebuf */
  10738. ebuf,
  10739. ebuf_len,
  10740. "SSL connection error");
  10741. SSL_CTX_free(conn->client_ssl_ctx);
  10742. closesocket(sock);
  10743. mg_free(conn);
  10744. conn = NULL;
  10745. }
  10746. }
  10747. #endif
  10748. }
  10749. return conn;
  10750. }
  10751. CIVETWEB_API struct mg_connection *
  10752. mg_connect_client_secure(const struct mg_client_options *client_options,
  10753. char *error_buffer,
  10754. size_t error_buffer_size)
  10755. {
  10756. return mg_connect_client_impl(client_options,
  10757. 1,
  10758. error_buffer,
  10759. error_buffer_size);
  10760. }
  10761. struct mg_connection *
  10762. mg_connect_client(const char *host,
  10763. int port,
  10764. int use_ssl,
  10765. char *error_buffer,
  10766. size_t error_buffer_size)
  10767. {
  10768. struct mg_client_options opts;
  10769. memset(&opts, 0, sizeof(opts));
  10770. opts.host = host;
  10771. opts.port = port;
  10772. return mg_connect_client_impl(&opts,
  10773. use_ssl,
  10774. error_buffer,
  10775. error_buffer_size);
  10776. }
  10777. static const struct {
  10778. const char *proto;
  10779. size_t proto_len;
  10780. unsigned default_port;
  10781. } abs_uri_protocols[] = {{"http://", 7, 80},
  10782. {"https://", 8, 443},
  10783. {"ws://", 5, 80},
  10784. {"wss://", 6, 443},
  10785. {NULL, 0, 0}};
  10786. /* Check if the uri is valid.
  10787. * return 0 for invalid uri,
  10788. * return 1 for *,
  10789. * return 2 for relative uri,
  10790. * return 3 for absolute uri without port,
  10791. * return 4 for absolute uri with port */
  10792. static int
  10793. get_uri_type(const char *uri)
  10794. {
  10795. int i;
  10796. char *hostend, *portbegin, *portend;
  10797. unsigned long port;
  10798. /* According to the HTTP standard
  10799. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10800. * URI can be an asterisk (*) or should start with slash (relative uri),
  10801. * or it should start with the protocol (absolute uri). */
  10802. if (uri[0] == '*' && uri[1] == '\0') {
  10803. /* asterisk */
  10804. return 1;
  10805. }
  10806. /* Valid URIs according to RFC 3986
  10807. * (https://www.ietf.org/rfc/rfc3986.txt)
  10808. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10809. * and unreserved characters A-Z a-z 0-9 and -._~
  10810. * and % encoded symbols.
  10811. */
  10812. for (i = 0; uri[i] != 0; i++) {
  10813. if (uri[i] < 33) {
  10814. /* control characters and spaces are invalid */
  10815. return 0;
  10816. }
  10817. if (uri[i] > 126) {
  10818. /* non-ascii characters must be % encoded */
  10819. return 0;
  10820. } else {
  10821. switch (uri[i]) {
  10822. case '"': /* 34 */
  10823. case '<': /* 60 */
  10824. case '>': /* 62 */
  10825. case '\\': /* 92 */
  10826. case '^': /* 94 */
  10827. case '`': /* 96 */
  10828. case '{': /* 123 */
  10829. case '|': /* 124 */
  10830. case '}': /* 125 */
  10831. return 0;
  10832. default:
  10833. /* character is ok */
  10834. break;
  10835. }
  10836. }
  10837. }
  10838. /* A relative uri starts with a / character */
  10839. if (uri[0] == '/') {
  10840. /* relative uri */
  10841. return 2;
  10842. }
  10843. /* It could be an absolute uri: */
  10844. /* This function only checks if the uri is valid, not if it is
  10845. * addressing the current server. So civetweb can also be used
  10846. * as a proxy server. */
  10847. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10848. if (mg_strncasecmp(uri,
  10849. abs_uri_protocols[i].proto,
  10850. abs_uri_protocols[i].proto_len) == 0) {
  10851. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10852. if (!hostend) {
  10853. return 0;
  10854. }
  10855. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10856. if (!portbegin) {
  10857. return 3;
  10858. }
  10859. port = strtoul(portbegin + 1, &portend, 10);
  10860. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10861. return 0;
  10862. }
  10863. return 4;
  10864. }
  10865. }
  10866. return 0;
  10867. }
  10868. /* Return NULL or the relative uri at the current server */
  10869. static const char *
  10870. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10871. {
  10872. const char *server_domain;
  10873. size_t server_domain_len;
  10874. size_t request_domain_len = 0;
  10875. unsigned long port = 0;
  10876. int i;
  10877. const char *hostbegin = NULL;
  10878. const char *hostend = NULL;
  10879. const char *portbegin;
  10880. char *portend;
  10881. /* DNS is case insensitive, so use case insensitive string compare here
  10882. */
  10883. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10884. if (!server_domain) {
  10885. return 0;
  10886. }
  10887. server_domain_len = strlen(server_domain);
  10888. if (!server_domain_len) {
  10889. return 0;
  10890. }
  10891. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10892. if (mg_strncasecmp(uri,
  10893. abs_uri_protocols[i].proto,
  10894. abs_uri_protocols[i].proto_len) == 0) {
  10895. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10896. hostend = strchr(hostbegin, '/');
  10897. if (!hostend) {
  10898. return 0;
  10899. }
  10900. portbegin = strchr(hostbegin, ':');
  10901. if ((!portbegin) || (portbegin > hostend)) {
  10902. port = abs_uri_protocols[i].default_port;
  10903. request_domain_len = (size_t)(hostend - hostbegin);
  10904. } else {
  10905. port = strtoul(portbegin + 1, &portend, 10);
  10906. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10907. return 0;
  10908. }
  10909. request_domain_len = (size_t)(portbegin - hostbegin);
  10910. }
  10911. /* protocol found, port set */
  10912. break;
  10913. }
  10914. }
  10915. if (!port) {
  10916. /* port remains 0 if the protocol is not found */
  10917. return 0;
  10918. }
  10919. /* Check if the request is directed to a different server. */
  10920. /* First check if the port is the same (IPv4 and IPv6). */
  10921. #if defined(USE_IPV6)
  10922. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10923. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10924. /* Request is directed to a different port */
  10925. return 0;
  10926. }
  10927. } else
  10928. #endif
  10929. {
  10930. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10931. /* Request is directed to a different port */
  10932. return 0;
  10933. }
  10934. }
  10935. /* Finally check if the server corresponds to the authentication
  10936. * domain of the server (the server domain).
  10937. * Allow full matches (like http://mydomain.com/path/file.ext), and
  10938. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  10939. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  10940. * or http://mydomain.com.fake/path/file.ext).
  10941. */
  10942. if ((request_domain_len == server_domain_len)
  10943. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  10944. /* Request is directed to this server - full name match. */
  10945. } else {
  10946. if (request_domain_len < (server_domain_len + 2)) {
  10947. /* Request is directed to another server: The server name is longer
  10948. * than
  10949. * the request name. Drop this case here to avoid overflows in the
  10950. * following checks. */
  10951. return 0;
  10952. }
  10953. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  10954. /* Request is directed to another server: It could be a substring
  10955. * like notmyserver.com */
  10956. return 0;
  10957. }
  10958. if (0 != memcmp(server_domain,
  10959. hostbegin + request_domain_len - server_domain_len,
  10960. server_domain_len)) {
  10961. /* Request is directed to another server:
  10962. * The server name is different. */
  10963. return 0;
  10964. }
  10965. }
  10966. return hostend;
  10967. }
  10968. static int
  10969. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10970. {
  10971. const char *cl;
  10972. if (ebuf_len > 0) {
  10973. ebuf[0] = '\0';
  10974. }
  10975. *err = 0;
  10976. reset_per_request_attributes(conn);
  10977. if (!conn) {
  10978. mg_snprintf(conn,
  10979. NULL, /* No truncation check for ebuf */
  10980. ebuf,
  10981. ebuf_len,
  10982. "%s",
  10983. "Internal error");
  10984. *err = 500;
  10985. return 0;
  10986. }
  10987. /* Set the time the request was received. This value should be used for
  10988. * timeouts. */
  10989. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10990. conn->request_len =
  10991. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10992. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10993. */
  10994. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10995. mg_snprintf(conn,
  10996. NULL, /* No truncation check for ebuf */
  10997. ebuf,
  10998. ebuf_len,
  10999. "%s",
  11000. "Invalid request size");
  11001. *err = 500;
  11002. return 0;
  11003. }
  11004. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11005. mg_snprintf(conn,
  11006. NULL, /* No truncation check for ebuf */
  11007. ebuf,
  11008. ebuf_len,
  11009. "%s",
  11010. "Request Too Large");
  11011. *err = 413;
  11012. return 0;
  11013. } else if (conn->request_len <= 0) {
  11014. if (conn->data_len > 0) {
  11015. mg_snprintf(conn,
  11016. NULL, /* No truncation check for ebuf */
  11017. ebuf,
  11018. ebuf_len,
  11019. "%s",
  11020. "Client sent malformed request");
  11021. *err = 400;
  11022. } else {
  11023. /* Server did not send anything -> just close the connection */
  11024. conn->must_close = 1;
  11025. mg_snprintf(conn,
  11026. NULL, /* No truncation check for ebuf */
  11027. ebuf,
  11028. ebuf_len,
  11029. "%s",
  11030. "Client did not send a request");
  11031. *err = 0;
  11032. }
  11033. return 0;
  11034. } else if (parse_http_message(conn->buf,
  11035. conn->buf_size,
  11036. &conn->request_info) <= 0) {
  11037. mg_snprintf(conn,
  11038. NULL, /* No truncation check for ebuf */
  11039. ebuf,
  11040. ebuf_len,
  11041. "%s",
  11042. "Bad Request");
  11043. *err = 400;
  11044. return 0;
  11045. } else {
  11046. /* Message is a valid request or response */
  11047. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11048. /* Request/response has content length set */
  11049. char *endptr = NULL;
  11050. conn->content_len = strtoll(cl, &endptr, 10);
  11051. if (endptr == cl) {
  11052. mg_snprintf(conn,
  11053. NULL, /* No truncation check for ebuf */
  11054. ebuf,
  11055. ebuf_len,
  11056. "%s",
  11057. "Bad Request");
  11058. *err = 411;
  11059. return 0;
  11060. }
  11061. /* Publish the content length back to the request info. */
  11062. conn->request_info.content_length = conn->content_len;
  11063. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11064. != NULL
  11065. && !mg_strcasecmp(cl, "chunked")) {
  11066. conn->is_chunked = 1;
  11067. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11068. || !mg_strcasecmp(conn->request_info.request_method,
  11069. "PUT")) {
  11070. /* POST or PUT request without content length set */
  11071. conn->content_len = -1;
  11072. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11073. "HTTP/",
  11074. 5)) {
  11075. /* Response without content length set */
  11076. conn->content_len = -1;
  11077. } else {
  11078. /* Other request */
  11079. conn->content_len = 0;
  11080. }
  11081. }
  11082. return 1;
  11083. }
  11084. int
  11085. mg_get_response(struct mg_connection *conn,
  11086. char *ebuf,
  11087. size_t ebuf_len,
  11088. int timeout)
  11089. {
  11090. if (conn) {
  11091. /* Implementation of API function for HTTP clients */
  11092. int err, ret;
  11093. struct mg_context *octx = conn->ctx;
  11094. struct mg_context rctx = *(conn->ctx);
  11095. char txt[32]; /* will not overflow */
  11096. if (timeout >= 0) {
  11097. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11098. rctx.config[REQUEST_TIMEOUT] = txt;
  11099. set_sock_timeout(conn->client.sock, timeout);
  11100. } else {
  11101. rctx.config[REQUEST_TIMEOUT] = NULL;
  11102. }
  11103. conn->ctx = &rctx;
  11104. ret = getreq(conn, ebuf, ebuf_len, &err);
  11105. conn->ctx = octx;
  11106. /* TODO: 1) uri is deprecated;
  11107. * 2) here, ri.uri is the http response code */
  11108. conn->request_info.uri = conn->request_info.request_uri;
  11109. /* TODO (mid): Define proper return values - maybe return length?
  11110. * For the first test use <0 for error and >0 for OK */
  11111. return (ret == 0) ? -1 : +1;
  11112. }
  11113. return -1;
  11114. }
  11115. struct mg_connection *
  11116. mg_download(const char *host,
  11117. int port,
  11118. int use_ssl,
  11119. char *ebuf,
  11120. size_t ebuf_len,
  11121. const char *fmt,
  11122. ...)
  11123. {
  11124. struct mg_connection *conn;
  11125. va_list ap;
  11126. int i;
  11127. int reqerr;
  11128. va_start(ap, fmt);
  11129. ebuf[0] = '\0';
  11130. /* open a connection */
  11131. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11132. if (conn != NULL) {
  11133. i = mg_vprintf(conn, fmt, ap);
  11134. if (i <= 0) {
  11135. mg_snprintf(conn,
  11136. NULL, /* No truncation check for ebuf */
  11137. ebuf,
  11138. ebuf_len,
  11139. "%s",
  11140. "Error sending request");
  11141. } else {
  11142. getreq(conn, ebuf, ebuf_len, &reqerr);
  11143. /* TODO: 1) uri is deprecated;
  11144. * 2) here, ri.uri is the http response code */
  11145. conn->request_info.uri = conn->request_info.request_uri;
  11146. }
  11147. }
  11148. /* if an error occured, close the connection */
  11149. if (ebuf[0] != '\0' && conn != NULL) {
  11150. mg_close_connection(conn);
  11151. conn = NULL;
  11152. }
  11153. va_end(ap);
  11154. return conn;
  11155. }
  11156. struct websocket_client_thread_data {
  11157. struct mg_connection *conn;
  11158. mg_websocket_data_handler data_handler;
  11159. mg_websocket_close_handler close_handler;
  11160. void *callback_data;
  11161. };
  11162. #if defined(USE_WEBSOCKET)
  11163. #ifdef _WIN32
  11164. static unsigned __stdcall websocket_client_thread(void *data)
  11165. #else
  11166. static void *
  11167. websocket_client_thread(void *data)
  11168. #endif
  11169. {
  11170. struct websocket_client_thread_data *cdata =
  11171. (struct websocket_client_thread_data *)data;
  11172. mg_set_thread_name("ws-clnt");
  11173. if (cdata->conn->ctx) {
  11174. if (cdata->conn->ctx->callbacks.init_thread) {
  11175. /* 3 indicates a websocket client thread */
  11176. /* TODO: check if conn->ctx can be set */
  11177. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11178. }
  11179. }
  11180. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11181. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11182. if (cdata->close_handler != NULL) {
  11183. cdata->close_handler(cdata->conn, cdata->callback_data);
  11184. }
  11185. /* The websocket_client context has only this thread. If it runs out,
  11186. set the stop_flag to 2 (= "stopped"). */
  11187. cdata->conn->ctx->stop_flag = 2;
  11188. mg_free((void *)cdata);
  11189. #ifdef _WIN32
  11190. return 0;
  11191. #else
  11192. return NULL;
  11193. #endif
  11194. }
  11195. #endif
  11196. struct mg_connection *
  11197. mg_connect_websocket_client(const char *host,
  11198. int port,
  11199. int use_ssl,
  11200. char *error_buffer,
  11201. size_t error_buffer_size,
  11202. const char *path,
  11203. const char *origin,
  11204. mg_websocket_data_handler data_func,
  11205. mg_websocket_close_handler close_func,
  11206. void *user_data)
  11207. {
  11208. struct mg_connection *conn = NULL;
  11209. #if defined(USE_WEBSOCKET)
  11210. struct mg_context *newctx = NULL;
  11211. struct websocket_client_thread_data *thread_data;
  11212. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11213. static const char *handshake_req;
  11214. if (origin != NULL) {
  11215. handshake_req = "GET %s HTTP/1.1\r\n"
  11216. "Host: %s\r\n"
  11217. "Upgrade: websocket\r\n"
  11218. "Connection: Upgrade\r\n"
  11219. "Sec-WebSocket-Key: %s\r\n"
  11220. "Sec-WebSocket-Version: 13\r\n"
  11221. "Origin: %s\r\n"
  11222. "\r\n";
  11223. } else {
  11224. handshake_req = "GET %s HTTP/1.1\r\n"
  11225. "Host: %s\r\n"
  11226. "Upgrade: websocket\r\n"
  11227. "Connection: Upgrade\r\n"
  11228. "Sec-WebSocket-Key: %s\r\n"
  11229. "Sec-WebSocket-Version: 13\r\n"
  11230. "\r\n";
  11231. }
  11232. /* Establish the client connection and request upgrade */
  11233. conn = mg_download(host,
  11234. port,
  11235. use_ssl,
  11236. error_buffer,
  11237. error_buffer_size,
  11238. handshake_req,
  11239. path,
  11240. host,
  11241. magic,
  11242. origin);
  11243. /* Connection object will be null if something goes wrong */
  11244. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11245. if (!*error_buffer) {
  11246. /* if there is a connection, but it did not return 101,
  11247. * error_buffer is not yet set */
  11248. mg_snprintf(conn,
  11249. NULL, /* No truncation check for ebuf */
  11250. error_buffer,
  11251. error_buffer_size,
  11252. "Unexpected server reply");
  11253. }
  11254. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11255. if (conn != NULL) {
  11256. mg_free(conn);
  11257. conn = NULL;
  11258. }
  11259. return conn;
  11260. }
  11261. /* For client connections, mg_context is fake. Since we need to set a
  11262. * callback function, we need to create a copy and modify it. */
  11263. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11264. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11265. newctx->user_data = user_data;
  11266. newctx->context_type = 2; /* ws/wss client context type */
  11267. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11268. newctx->workerthreadids =
  11269. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11270. conn->ctx = newctx;
  11271. thread_data = (struct websocket_client_thread_data *)
  11272. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11273. thread_data->conn = conn;
  11274. thread_data->data_handler = data_func;
  11275. thread_data->close_handler = close_func;
  11276. thread_data->callback_data = NULL;
  11277. /* Start a thread to read the websocket client connection
  11278. * This thread will automatically stop when mg_disconnect is
  11279. * called on the client connection */
  11280. if (mg_start_thread_with_id(websocket_client_thread,
  11281. (void *)thread_data,
  11282. newctx->workerthreadids) != 0) {
  11283. mg_free((void *)thread_data);
  11284. mg_free((void *)newctx->workerthreadids);
  11285. mg_free((void *)newctx);
  11286. mg_free((void *)conn);
  11287. conn = NULL;
  11288. DEBUG_TRACE("%s",
  11289. "Websocket client connect thread could not be started\r\n");
  11290. }
  11291. #else
  11292. /* Appease "unused parameter" warnings */
  11293. (void)host;
  11294. (void)port;
  11295. (void)use_ssl;
  11296. (void)error_buffer;
  11297. (void)error_buffer_size;
  11298. (void)path;
  11299. (void)origin;
  11300. (void)user_data;
  11301. (void)data_func;
  11302. (void)close_func;
  11303. #endif
  11304. return conn;
  11305. }
  11306. static void
  11307. process_new_connection(struct mg_connection *conn)
  11308. {
  11309. if (conn && conn->ctx) {
  11310. struct mg_request_info *ri = &conn->request_info;
  11311. int keep_alive_enabled, keep_alive, discard_len;
  11312. char ebuf[100];
  11313. const char *hostend;
  11314. int reqerr, uri_type;
  11315. keep_alive_enabled =
  11316. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11317. /* Important: on new connection, reset the receiving buffer. Credit
  11318. * goes to crule42. */
  11319. conn->data_len = 0;
  11320. do {
  11321. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11322. /* The request sent by the client could not be understood by
  11323. * the server, or it was incomplete or a timeout. Send an
  11324. * error message and close the connection. */
  11325. if (reqerr > 0) {
  11326. /*assert(ebuf[0] != '\0');*/
  11327. send_http_error(conn, reqerr, "%s", ebuf);
  11328. }
  11329. } else if (strcmp(ri->http_version, "1.0")
  11330. && strcmp(ri->http_version, "1.1")) {
  11331. mg_snprintf(conn,
  11332. NULL, /* No truncation check for ebuf */
  11333. ebuf,
  11334. sizeof(ebuf),
  11335. "Bad HTTP version: [%s]",
  11336. ri->http_version);
  11337. send_http_error(conn, 505, "%s", ebuf);
  11338. }
  11339. if (ebuf[0] == '\0') {
  11340. uri_type = get_uri_type(conn->request_info.request_uri);
  11341. switch (uri_type) {
  11342. case 1:
  11343. /* Asterisk */
  11344. conn->request_info.local_uri = NULL;
  11345. break;
  11346. case 2:
  11347. /* relative uri */
  11348. conn->request_info.local_uri =
  11349. conn->request_info.request_uri;
  11350. break;
  11351. case 3:
  11352. case 4:
  11353. /* absolute uri (with/without port) */
  11354. hostend = get_rel_url_at_current_server(
  11355. conn->request_info.request_uri, conn);
  11356. if (hostend) {
  11357. conn->request_info.local_uri = hostend;
  11358. } else {
  11359. conn->request_info.local_uri = NULL;
  11360. }
  11361. break;
  11362. default:
  11363. mg_snprintf(conn,
  11364. NULL, /* No truncation check for ebuf */
  11365. ebuf,
  11366. sizeof(ebuf),
  11367. "Invalid URI");
  11368. send_http_error(conn, 400, "%s", ebuf);
  11369. conn->request_info.local_uri = NULL;
  11370. break;
  11371. }
  11372. /* TODO: cleanup uri, local_uri and request_uri */
  11373. conn->request_info.uri = conn->request_info.local_uri;
  11374. }
  11375. if (ebuf[0] == '\0') {
  11376. if (conn->request_info.local_uri) {
  11377. /* handle request to local server */
  11378. handle_request(conn);
  11379. if (conn->ctx->callbacks.end_request != NULL) {
  11380. conn->ctx->callbacks.end_request(conn,
  11381. conn->status_code);
  11382. }
  11383. log_access(conn);
  11384. } else {
  11385. /* TODO: handle non-local request (PROXY) */
  11386. conn->must_close = 1;
  11387. }
  11388. } else {
  11389. conn->must_close = 1;
  11390. }
  11391. if (ri->remote_user != NULL) {
  11392. mg_free((void *)ri->remote_user);
  11393. /* Important! When having connections with and without auth
  11394. * would cause double free and then crash */
  11395. ri->remote_user = NULL;
  11396. }
  11397. /* NOTE(lsm): order is important here. should_keep_alive() call
  11398. * is
  11399. * using parsed request, which will be invalid after memmove's
  11400. * below.
  11401. * Therefore, memorize should_keep_alive() result now for later
  11402. * use
  11403. * in loop exit condition. */
  11404. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11405. && conn->content_len >= 0 && should_keep_alive(conn);
  11406. /* Discard all buffered data for this request */
  11407. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11408. && ((conn->request_len + conn->content_len)
  11409. < (int64_t)conn->data_len))
  11410. ? (int)(conn->request_len + conn->content_len)
  11411. : conn->data_len;
  11412. /*assert(discard_len >= 0);*/
  11413. if (discard_len < 0)
  11414. break;
  11415. conn->data_len -= discard_len;
  11416. if (conn->data_len > 0) {
  11417. memmove(conn->buf,
  11418. conn->buf + discard_len,
  11419. (size_t)conn->data_len);
  11420. }
  11421. /* assert(conn->data_len >= 0); */
  11422. /* assert(conn->data_len <= conn->buf_size); */
  11423. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11424. break;
  11425. }
  11426. } while (keep_alive);
  11427. }
  11428. }
  11429. #if defined(ALTERNATIVE_QUEUE)
  11430. static void
  11431. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11432. {
  11433. unsigned int i;
  11434. for (;;) {
  11435. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11436. /* find a free worker slot and signal it */
  11437. if (ctx->client_socks[i].in_use == 0) {
  11438. ctx->client_socks[i] = *sp;
  11439. ctx->client_socks[i].in_use = 1;
  11440. event_signal(ctx->client_wait_events[i]);
  11441. return;
  11442. }
  11443. }
  11444. /* queue is full */
  11445. mg_sleep(1);
  11446. }
  11447. }
  11448. static int
  11449. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11450. {
  11451. ctx->client_socks[thread_index].in_use = 0;
  11452. event_wait(ctx->client_wait_events[thread_index]);
  11453. *sp = ctx->client_socks[thread_index];
  11454. return !ctx->stop_flag;
  11455. }
  11456. #else /* ALTERNATIVE_QUEUE */
  11457. /* Worker threads take accepted socket from the queue */
  11458. static int
  11459. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11460. {
  11461. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11462. (void)thread_index;
  11463. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11464. DEBUG_TRACE("%s", "going idle");
  11465. /* If the queue is empty, wait. We're idle at this point. */
  11466. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11467. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11468. }
  11469. /* If we're stopping, sq_head may be equal to sq_tail. */
  11470. if (ctx->sq_head > ctx->sq_tail) {
  11471. /* Copy socket from the queue and increment tail */
  11472. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11473. ctx->sq_tail++;
  11474. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11475. /* Wrap pointers if needed */
  11476. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11477. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11478. ctx->sq_head -= QUEUE_SIZE(ctx);
  11479. }
  11480. }
  11481. (void)pthread_cond_signal(&ctx->sq_empty);
  11482. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11483. return !ctx->stop_flag;
  11484. #undef QUEUE_SIZE
  11485. }
  11486. /* Master thread adds accepted socket to a queue */
  11487. static void
  11488. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11489. {
  11490. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11491. if (!ctx) {
  11492. return;
  11493. }
  11494. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11495. /* If the queue is full, wait */
  11496. while (ctx->stop_flag == 0
  11497. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11498. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11499. }
  11500. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11501. /* Copy socket to the queue and increment head */
  11502. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11503. ctx->sq_head++;
  11504. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11505. }
  11506. (void)pthread_cond_signal(&ctx->sq_full);
  11507. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11508. #undef QUEUE_SIZE
  11509. }
  11510. #endif /* ALTERNATIVE_QUEUE */
  11511. struct worker_thread_args {
  11512. struct mg_context *ctx;
  11513. int index;
  11514. };
  11515. static void *
  11516. worker_thread_run(struct worker_thread_args *thread_args)
  11517. {
  11518. struct mg_context *ctx = thread_args->ctx;
  11519. struct mg_connection *conn;
  11520. struct mg_workerTLS tls;
  11521. #if defined(MG_LEGACY_INTERFACE)
  11522. uint32_t addr;
  11523. #endif
  11524. mg_set_thread_name("worker");
  11525. tls.is_master = 0;
  11526. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11527. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11528. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11529. #endif
  11530. if (ctx->callbacks.init_thread) {
  11531. /* call init_thread for a worker thread (type 1) */
  11532. ctx->callbacks.init_thread(ctx, 1);
  11533. }
  11534. conn =
  11535. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11536. if (conn == NULL) {
  11537. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11538. } else {
  11539. pthread_setspecific(sTlsKey, &tls);
  11540. conn->buf_size = MAX_REQUEST_SIZE;
  11541. conn->buf = (char *)(conn + 1);
  11542. conn->ctx = ctx;
  11543. conn->thread_index = thread_args->index;
  11544. conn->request_info.user_data = ctx->user_data;
  11545. /* Allocate a mutex for this connection to allow communication both
  11546. * within the request handler and from elsewhere in the application
  11547. */
  11548. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11549. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11550. * signal sq_empty condvar to wake up the master waiting in
  11551. * produce_socket() */
  11552. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11553. conn->conn_birth_time = time(NULL);
  11554. /* Fill in IP, port info early so even if SSL setup below fails,
  11555. * error handler would have the corresponding info.
  11556. * Thanks to Johannes Winkelmann for the patch.
  11557. */
  11558. #if defined(USE_IPV6)
  11559. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11560. conn->request_info.remote_port =
  11561. ntohs(conn->client.rsa.sin6.sin6_port);
  11562. } else
  11563. #endif
  11564. {
  11565. conn->request_info.remote_port =
  11566. ntohs(conn->client.rsa.sin.sin_port);
  11567. }
  11568. sockaddr_to_string(conn->request_info.remote_addr,
  11569. sizeof(conn->request_info.remote_addr),
  11570. &conn->client.rsa);
  11571. #if defined(MG_LEGACY_INTERFACE)
  11572. /* This legacy interface only works for the IPv4 case */
  11573. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11574. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11575. #endif
  11576. conn->request_info.is_ssl = conn->client.is_ssl;
  11577. if (conn->client.is_ssl) {
  11578. #ifndef NO_SSL
  11579. /* HTTPS connection */
  11580. if (sslize(conn,
  11581. conn->ctx->ssl_ctx,
  11582. SSL_accept,
  11583. &(conn->ctx->stop_flag))) {
  11584. /* Get SSL client certificate information (if set) */
  11585. ssl_get_client_cert_info(conn);
  11586. /* process HTTPS connection */
  11587. process_new_connection(conn);
  11588. /* Free client certificate info */
  11589. if (conn->request_info.client_cert) {
  11590. mg_free(
  11591. (void *)(conn->request_info.client_cert->subject));
  11592. mg_free(
  11593. (void *)(conn->request_info.client_cert->issuer));
  11594. mg_free(
  11595. (void *)(conn->request_info.client_cert->serial));
  11596. mg_free(
  11597. (void *)(conn->request_info.client_cert->finger));
  11598. conn->request_info.client_cert->subject = 0;
  11599. conn->request_info.client_cert->issuer = 0;
  11600. conn->request_info.client_cert->serial = 0;
  11601. conn->request_info.client_cert->finger = 0;
  11602. mg_free(conn->request_info.client_cert);
  11603. conn->request_info.client_cert = 0;
  11604. }
  11605. }
  11606. #endif
  11607. } else {
  11608. /* process HTTP connection */
  11609. process_new_connection(conn);
  11610. }
  11611. close_connection(conn);
  11612. }
  11613. }
  11614. pthread_setspecific(sTlsKey, NULL);
  11615. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11616. CloseHandle(tls.pthread_cond_helper_mutex);
  11617. #endif
  11618. pthread_mutex_destroy(&conn->mutex);
  11619. mg_free(conn);
  11620. DEBUG_TRACE("%s", "exiting");
  11621. return NULL;
  11622. }
  11623. /* Threads have different return types on Windows and Unix. */
  11624. #ifdef _WIN32
  11625. static unsigned __stdcall worker_thread(void *thread_func_param)
  11626. {
  11627. struct worker_thread_args *pwta =
  11628. (struct worker_thread_args *)thread_func_param;
  11629. worker_thread_run(pwta);
  11630. mg_free(thread_func_param);
  11631. return 0;
  11632. }
  11633. #else
  11634. static void *
  11635. worker_thread(void *thread_func_param)
  11636. {
  11637. struct worker_thread_args *pwta =
  11638. (struct worker_thread_args *)thread_func_param;
  11639. worker_thread_run(pwta);
  11640. mg_free(thread_func_param);
  11641. return NULL;
  11642. }
  11643. #endif /* _WIN32 */
  11644. static void
  11645. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11646. {
  11647. struct socket so;
  11648. char src_addr[IP_ADDR_STR_LEN];
  11649. socklen_t len = sizeof(so.rsa);
  11650. int on = 1;
  11651. int timeout;
  11652. if (!listener) {
  11653. return;
  11654. }
  11655. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11656. == INVALID_SOCKET) {
  11657. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11658. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11659. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11660. closesocket(so.sock);
  11661. so.sock = INVALID_SOCKET;
  11662. } else {
  11663. /* Put so socket structure into the queue */
  11664. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11665. set_close_on_exec(so.sock, fc(ctx));
  11666. so.is_ssl = listener->is_ssl;
  11667. so.ssl_redir = listener->ssl_redir;
  11668. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11669. mg_cry(fc(ctx),
  11670. "%s: getsockname() failed: %s",
  11671. __func__,
  11672. strerror(ERRNO));
  11673. }
  11674. /* Set TCP keep-alive. This is needed because if HTTP-level
  11675. * keep-alive
  11676. * is enabled, and client resets the connection, server won't get
  11677. * TCP FIN or RST and will keep the connection open forever. With
  11678. * TCP keep-alive, next keep-alive handshake will figure out that
  11679. * the client is down and will close the server end.
  11680. * Thanks to Igor Klopov who suggested the patch. */
  11681. if (setsockopt(so.sock,
  11682. SOL_SOCKET,
  11683. SO_KEEPALIVE,
  11684. (SOCK_OPT_TYPE)&on,
  11685. sizeof(on)) != 0) {
  11686. mg_cry(fc(ctx),
  11687. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11688. __func__,
  11689. strerror(ERRNO));
  11690. }
  11691. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11692. * to effectively fill up the underlying IP packet payload and
  11693. * reduce the overhead of sending lots of small buffers. However
  11694. * this hurts the server's throughput (ie. operations per second)
  11695. * when HTTP 1.1 persistent connections are used and the responses
  11696. * are relatively small (eg. less than 1400 bytes).
  11697. */
  11698. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11699. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11700. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11701. mg_cry(fc(ctx),
  11702. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11703. __func__,
  11704. strerror(ERRNO));
  11705. }
  11706. }
  11707. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11708. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11709. } else {
  11710. timeout = -1;
  11711. }
  11712. /* TODO: if non blocking sockets are used, timeouts are implemented
  11713. * differently */
  11714. // if (timeout > 0) {
  11715. // set_sock_timeout(so.sock, timeout);
  11716. //}
  11717. (void)timeout;
  11718. set_non_blocking_mode(so.sock);
  11719. produce_socket(ctx, &so);
  11720. }
  11721. }
  11722. static void
  11723. master_thread_run(void *thread_func_param)
  11724. {
  11725. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11726. struct mg_workerTLS tls;
  11727. struct pollfd *pfd;
  11728. unsigned int i;
  11729. unsigned int workerthreadcount;
  11730. if (!ctx) {
  11731. return;
  11732. }
  11733. mg_set_thread_name("master");
  11734. /* Increase priority of the master thread */
  11735. #if defined(_WIN32)
  11736. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11737. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11738. int min_prio = sched_get_priority_min(SCHED_RR);
  11739. int max_prio = sched_get_priority_max(SCHED_RR);
  11740. if ((min_prio >= 0) && (max_prio >= 0)
  11741. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11742. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11743. struct sched_param sched_param = {0};
  11744. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11745. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11746. }
  11747. #endif
  11748. /* Initialize thread local storage */
  11749. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11750. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11751. #endif
  11752. tls.is_master = 1;
  11753. pthread_setspecific(sTlsKey, &tls);
  11754. if (ctx->callbacks.init_thread) {
  11755. /* Callback for the master thread (type 0) */
  11756. ctx->callbacks.init_thread(ctx, 0);
  11757. }
  11758. /* Server starts *now* */
  11759. ctx->start_time = time(NULL);
  11760. /* Start the server */
  11761. pfd = ctx->listening_socket_fds;
  11762. while (ctx->stop_flag == 0) {
  11763. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11764. pfd[i].fd = ctx->listening_sockets[i].sock;
  11765. pfd[i].events = POLLIN;
  11766. }
  11767. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11768. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11769. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11770. * successful poll, and POLLIN is defined as
  11771. * (POLLRDNORM | POLLRDBAND)
  11772. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11773. * pfd[i].revents == POLLIN. */
  11774. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11775. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11776. }
  11777. }
  11778. }
  11779. }
  11780. /* Here stop_flag is 1 - Initiate shutdown. */
  11781. DEBUG_TRACE("%s", "stopping workers");
  11782. /* Stop signal received: somebody called mg_stop. Quit. */
  11783. close_all_listening_sockets(ctx);
  11784. /* Wakeup workers that are waiting for connections to handle. */
  11785. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11786. #if defined(ALTERNATIVE_QUEUE)
  11787. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11788. event_signal(ctx->client_wait_events[i]);
  11789. /* Since we know all sockets, we can shutdown the connections. */
  11790. if (ctx->client_socks[i].in_use) {
  11791. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11792. }
  11793. }
  11794. #else
  11795. pthread_cond_broadcast(&ctx->sq_full);
  11796. #endif
  11797. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11798. /* Join all worker threads to avoid leaking threads. */
  11799. workerthreadcount = ctx->cfg_worker_threads;
  11800. for (i = 0; i < workerthreadcount; i++) {
  11801. if (ctx->workerthreadids[i] != 0) {
  11802. mg_join_thread(ctx->workerthreadids[i]);
  11803. }
  11804. }
  11805. #if !defined(NO_SSL)
  11806. if (ctx->ssl_ctx != NULL) {
  11807. uninitialize_ssl(ctx);
  11808. }
  11809. #endif
  11810. DEBUG_TRACE("%s", "exiting");
  11811. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11812. CloseHandle(tls.pthread_cond_helper_mutex);
  11813. #endif
  11814. pthread_setspecific(sTlsKey, NULL);
  11815. /* Signal mg_stop() that we're done.
  11816. * WARNING: This must be the very last thing this
  11817. * thread does, as ctx becomes invalid after this line. */
  11818. ctx->stop_flag = 2;
  11819. }
  11820. /* Threads have different return types on Windows and Unix. */
  11821. #ifdef _WIN32
  11822. static unsigned __stdcall master_thread(void *thread_func_param)
  11823. {
  11824. master_thread_run(thread_func_param);
  11825. return 0;
  11826. }
  11827. #else
  11828. static void *
  11829. master_thread(void *thread_func_param)
  11830. {
  11831. master_thread_run(thread_func_param);
  11832. return NULL;
  11833. }
  11834. #endif /* _WIN32 */
  11835. static void
  11836. free_context(struct mg_context *ctx)
  11837. {
  11838. int i;
  11839. struct mg_handler_info *tmp_rh;
  11840. if (ctx == NULL) {
  11841. return;
  11842. }
  11843. if (ctx->callbacks.exit_context) {
  11844. ctx->callbacks.exit_context(ctx);
  11845. }
  11846. /* All threads exited, no sync is needed. Destroy thread mutex and
  11847. * condvars
  11848. */
  11849. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11850. #if defined(ALTERNATIVE_QUEUE)
  11851. mg_free(ctx->client_socks);
  11852. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11853. event_destroy(ctx->client_wait_events[i]);
  11854. }
  11855. mg_free(ctx->client_wait_events);
  11856. #else
  11857. (void)pthread_cond_destroy(&ctx->sq_empty);
  11858. (void)pthread_cond_destroy(&ctx->sq_full);
  11859. #endif
  11860. /* Destroy other context global data structures mutex */
  11861. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11862. #if defined(USE_TIMERS)
  11863. timers_exit(ctx);
  11864. #endif
  11865. /* Deallocate config parameters */
  11866. for (i = 0; i < NUM_OPTIONS; i++) {
  11867. if (ctx->config[i] != NULL) {
  11868. #if defined(_MSC_VER)
  11869. #pragma warning(suppress : 6001)
  11870. #endif
  11871. mg_free(ctx->config[i]);
  11872. }
  11873. }
  11874. /* Deallocate request handlers */
  11875. while (ctx->handlers) {
  11876. tmp_rh = ctx->handlers;
  11877. ctx->handlers = tmp_rh->next;
  11878. mg_free(tmp_rh->uri);
  11879. mg_free(tmp_rh);
  11880. }
  11881. #ifndef NO_SSL
  11882. /* Deallocate SSL context */
  11883. if (ctx->ssl_ctx != NULL) {
  11884. SSL_CTX_free(ctx->ssl_ctx);
  11885. }
  11886. #endif /* !NO_SSL */
  11887. /* Deallocate worker thread ID array */
  11888. if (ctx->workerthreadids != NULL) {
  11889. mg_free(ctx->workerthreadids);
  11890. }
  11891. /* Deallocate the tls variable */
  11892. if (mg_atomic_dec(&sTlsInit) == 0) {
  11893. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11894. DeleteCriticalSection(&global_log_file_lock);
  11895. #endif /* _WIN32 && !__SYMBIAN32__ */
  11896. #if !defined(_WIN32)
  11897. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11898. #endif
  11899. pthread_key_delete(sTlsKey);
  11900. #if defined(USE_LUA)
  11901. lua_exit_optional_libraries();
  11902. #endif
  11903. }
  11904. /* deallocate system name string */
  11905. mg_free(ctx->systemName);
  11906. /* Deallocate context itself */
  11907. mg_free(ctx);
  11908. }
  11909. void
  11910. mg_stop(struct mg_context *ctx)
  11911. {
  11912. pthread_t mt;
  11913. if (!ctx) {
  11914. return;
  11915. }
  11916. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11917. * two threads is not allowed. */
  11918. mt = ctx->masterthreadid;
  11919. if (mt == 0) {
  11920. return;
  11921. }
  11922. ctx->masterthreadid = 0;
  11923. /* Set stop flag, so all threads know they have to exit. */
  11924. ctx->stop_flag = 1;
  11925. /* Wait until everything has stopped. */
  11926. while (ctx->stop_flag != 2) {
  11927. (void)mg_sleep(10);
  11928. }
  11929. mg_join_thread(mt);
  11930. free_context(ctx);
  11931. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11932. (void)WSACleanup();
  11933. #endif /* _WIN32 && !__SYMBIAN32__ */
  11934. }
  11935. static void
  11936. get_system_name(char **sysName)
  11937. {
  11938. #if defined(_WIN32)
  11939. #if !defined(__SYMBIAN32__)
  11940. #if defined(_WIN32_WCE)
  11941. *sysName = mg_strdup("WinCE");
  11942. #else
  11943. char name[128];
  11944. DWORD dwVersion = 0;
  11945. DWORD dwMajorVersion = 0;
  11946. DWORD dwMinorVersion = 0;
  11947. DWORD dwBuild = 0;
  11948. #ifdef _MSC_VER
  11949. #pragma warning(push)
  11950. /* GetVersion was declared deprecated */
  11951. #pragma warning(disable : 4996)
  11952. #endif
  11953. dwVersion = GetVersion();
  11954. #ifdef _MSC_VER
  11955. #pragma warning(pop)
  11956. #endif
  11957. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11958. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11959. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11960. (void)dwBuild;
  11961. sprintf(name,
  11962. "Windows %u.%u",
  11963. (unsigned)dwMajorVersion,
  11964. (unsigned)dwMinorVersion);
  11965. *sysName = mg_strdup(name);
  11966. #endif
  11967. #else
  11968. *sysName = mg_strdup("Symbian");
  11969. #endif
  11970. #else
  11971. struct utsname name;
  11972. memset(&name, 0, sizeof(name));
  11973. uname(&name);
  11974. *sysName = mg_strdup(name.sysname);
  11975. #endif
  11976. }
  11977. struct mg_context *
  11978. mg_start(const struct mg_callbacks *callbacks,
  11979. void *user_data,
  11980. const char **options)
  11981. {
  11982. struct mg_context *ctx;
  11983. const char *name, *value, *default_value;
  11984. int idx, ok, workerthreadcount;
  11985. unsigned int i;
  11986. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11987. struct mg_workerTLS tls;
  11988. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11989. WSADATA data;
  11990. WSAStartup(MAKEWORD(2, 2), &data);
  11991. #endif /* _WIN32 && !__SYMBIAN32__ */
  11992. /* Allocate context and initialize reasonable general case defaults. */
  11993. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11994. return NULL;
  11995. }
  11996. /* Random number generator will initialize at the first call */
  11997. ctx->auth_nonce_mask =
  11998. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11999. if (mg_atomic_inc(&sTlsInit) == 1) {
  12000. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12001. InitializeCriticalSection(&global_log_file_lock);
  12002. #endif /* _WIN32 && !__SYMBIAN32__ */
  12003. #if !defined(_WIN32)
  12004. pthread_mutexattr_init(&pthread_mutex_attr);
  12005. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12006. #endif
  12007. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12008. /* Fatal error - abort start. However, this situation should
  12009. * never
  12010. * occur in practice. */
  12011. mg_atomic_dec(&sTlsInit);
  12012. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12013. mg_free(ctx);
  12014. return NULL;
  12015. }
  12016. #if defined(USE_LUA)
  12017. lua_init_optional_libraries();
  12018. #endif
  12019. } else {
  12020. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12021. * initialized. */
  12022. mg_sleep(1);
  12023. }
  12024. tls.is_master = -1;
  12025. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12026. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12027. tls.pthread_cond_helper_mutex = NULL;
  12028. #endif
  12029. pthread_setspecific(sTlsKey, &tls);
  12030. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12031. #if !defined(ALTERNATIVE_QUEUE)
  12032. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12033. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12034. #endif
  12035. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12036. if (!ok) {
  12037. /* Fatal error - abort start. However, this situation should never
  12038. * occur in practice. */
  12039. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12040. mg_free(ctx);
  12041. pthread_setspecific(sTlsKey, NULL);
  12042. return NULL;
  12043. }
  12044. if (callbacks) {
  12045. ctx->callbacks = *callbacks;
  12046. exit_callback = callbacks->exit_context;
  12047. ctx->callbacks.exit_context = 0;
  12048. }
  12049. ctx->user_data = user_data;
  12050. ctx->handlers = NULL;
  12051. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12052. ctx->shared_lua_websockets = 0;
  12053. #endif
  12054. while (options && (name = *options++) != NULL) {
  12055. if ((idx = get_option_index(name)) == -1) {
  12056. mg_cry(fc(ctx), "Invalid option: %s", name);
  12057. free_context(ctx);
  12058. pthread_setspecific(sTlsKey, NULL);
  12059. return NULL;
  12060. } else if ((value = *options++) == NULL) {
  12061. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12062. free_context(ctx);
  12063. pthread_setspecific(sTlsKey, NULL);
  12064. return NULL;
  12065. }
  12066. if (ctx->config[idx] != NULL) {
  12067. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12068. mg_free(ctx->config[idx]);
  12069. }
  12070. ctx->config[idx] = mg_strdup(value);
  12071. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12072. }
  12073. /* Set default value if needed */
  12074. for (i = 0; config_options[i].name != NULL; i++) {
  12075. default_value = config_options[i].default_value;
  12076. if (ctx->config[i] == NULL && default_value != NULL) {
  12077. ctx->config[i] = mg_strdup(default_value);
  12078. }
  12079. }
  12080. #if defined(NO_FILES)
  12081. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12082. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12083. free_context(ctx);
  12084. pthread_setspecific(sTlsKey, NULL);
  12085. return NULL;
  12086. }
  12087. #endif
  12088. get_system_name(&ctx->systemName);
  12089. /* NOTE(lsm): order is important here. SSL certificates must
  12090. * be initialized before listening ports. UID must be set last. */
  12091. if (!set_gpass_option(ctx) ||
  12092. #if !defined(NO_SSL)
  12093. !set_ssl_option(ctx) ||
  12094. #endif
  12095. !set_ports_option(ctx) ||
  12096. #if !defined(_WIN32)
  12097. !set_uid_option(ctx) ||
  12098. #endif
  12099. !set_acl_option(ctx)) {
  12100. free_context(ctx);
  12101. pthread_setspecific(sTlsKey, NULL);
  12102. return NULL;
  12103. }
  12104. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12105. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12106. * won't kill the whole process. */
  12107. (void)signal(SIGPIPE, SIG_IGN);
  12108. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12109. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12110. if (workerthreadcount > MAX_WORKER_THREADS) {
  12111. mg_cry(fc(ctx), "Too many worker threads");
  12112. free_context(ctx);
  12113. pthread_setspecific(sTlsKey, NULL);
  12114. return NULL;
  12115. }
  12116. if (workerthreadcount > 0) {
  12117. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12118. ctx->workerthreadids =
  12119. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12120. if (ctx->workerthreadids == NULL) {
  12121. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12122. free_context(ctx);
  12123. pthread_setspecific(sTlsKey, NULL);
  12124. return NULL;
  12125. }
  12126. #if defined(ALTERNATIVE_QUEUE)
  12127. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  12128. ctx->cfg_worker_threads);
  12129. if (ctx->client_wait_events == NULL) {
  12130. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12131. mg_free(ctx->workerthreadids);
  12132. free_context(ctx);
  12133. pthread_setspecific(sTlsKey, NULL);
  12134. return NULL;
  12135. }
  12136. ctx->client_socks =
  12137. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12138. if (ctx->client_wait_events == NULL) {
  12139. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12140. mg_free(ctx->client_socks);
  12141. mg_free(ctx->workerthreadids);
  12142. free_context(ctx);
  12143. pthread_setspecific(sTlsKey, NULL);
  12144. return NULL;
  12145. }
  12146. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12147. ctx->client_wait_events[i] = event_create();
  12148. if (ctx->client_wait_events[i] == 0) {
  12149. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12150. /* TODO: clean all and exit */
  12151. }
  12152. }
  12153. #endif
  12154. }
  12155. #if defined(USE_TIMERS)
  12156. if (timers_init(ctx) != 0) {
  12157. mg_cry(fc(ctx), "Error creating timers");
  12158. free_context(ctx);
  12159. pthread_setspecific(sTlsKey, NULL);
  12160. return NULL;
  12161. }
  12162. #endif
  12163. /* Context has been created - init user libraries */
  12164. if (ctx->callbacks.init_context) {
  12165. ctx->callbacks.init_context(ctx);
  12166. }
  12167. ctx->callbacks.exit_context = exit_callback;
  12168. ctx->context_type = 1; /* server context */
  12169. /* Start master (listening) thread */
  12170. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12171. /* Start worker threads */
  12172. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12173. struct worker_thread_args *wta =
  12174. mg_malloc(sizeof(struct worker_thread_args));
  12175. if (wta) {
  12176. wta->ctx = ctx;
  12177. wta->index = (int)i;
  12178. }
  12179. if ((wta == NULL)
  12180. || (mg_start_thread_with_id(worker_thread,
  12181. wta,
  12182. &ctx->workerthreadids[i]) != 0)) {
  12183. /* thread was not created */
  12184. if (wta != NULL) {
  12185. mg_free(wta);
  12186. }
  12187. if (i > 0) {
  12188. mg_cry(fc(ctx),
  12189. "Cannot start worker thread %i: error %ld",
  12190. i + 1,
  12191. (long)ERRNO);
  12192. } else {
  12193. mg_cry(fc(ctx),
  12194. "Cannot create threads: error %ld",
  12195. (long)ERRNO);
  12196. free_context(ctx);
  12197. pthread_setspecific(sTlsKey, NULL);
  12198. return NULL;
  12199. }
  12200. break;
  12201. }
  12202. }
  12203. pthread_setspecific(sTlsKey, NULL);
  12204. return ctx;
  12205. }
  12206. /* Feature check API function */
  12207. unsigned
  12208. mg_check_feature(unsigned feature)
  12209. {
  12210. static const unsigned feature_set = 0
  12211. /* Set bits for available features according to API documentation.
  12212. * This bit mask is created at compile time, according to the active
  12213. * preprocessor defines. It is a single const value at runtime. */
  12214. #if !defined(NO_FILES)
  12215. | 0x0001u
  12216. #endif
  12217. #if !defined(NO_SSL)
  12218. | 0x0002u
  12219. #endif
  12220. #if !defined(NO_CGI)
  12221. | 0x0004u
  12222. #endif
  12223. #if defined(USE_IPV6)
  12224. | 0x0008u
  12225. #endif
  12226. #if defined(USE_WEBSOCKET)
  12227. | 0x0010u
  12228. #endif
  12229. #if defined(USE_LUA)
  12230. | 0x0020u
  12231. #endif
  12232. #if defined(USE_DUKTAPE)
  12233. | 0x0040u
  12234. #endif
  12235. #if !defined(NO_CACHING)
  12236. | 0x0080u
  12237. #endif
  12238. /* Set some extra bits not defined in the API documentation.
  12239. * These bits may change without further notice. */
  12240. #if defined(MG_LEGACY_INTERFACE)
  12241. | 0x8000u
  12242. #endif
  12243. #if defined(MEMORY_DEBUGGING)
  12244. | 0x0100u
  12245. #endif
  12246. #if defined(USE_TIMERS)
  12247. | 0x0200u
  12248. #endif
  12249. #if !defined(NO_NONCE_CHECK)
  12250. | 0x0400u
  12251. #endif
  12252. #if !defined(NO_POPEN)
  12253. | 0x0800u
  12254. #endif
  12255. ;
  12256. return (feature & feature_set);
  12257. }