civetweb.c 582 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613
  1. /* Copyright (c) 2013-2020 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(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0502
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE (1024 * 16)
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #if !defined(DEBUG_TRACE_STREAM)
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #define DEBUG_ASSERT(cond) \
  220. do { \
  221. if (!(cond)) { \
  222. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  223. exit(2); /* Exit with error */ \
  224. } \
  225. } while (0)
  226. #else
  227. #define DEBUG_ASSERT(cond)
  228. #endif /* DEBUG */
  229. #endif
  230. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  231. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  232. __attribute__((no_instrument_function));
  233. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  234. __attribute__((no_instrument_function));
  235. void
  236. __cyg_profile_func_enter(void *this_fn, void *call_site)
  237. {
  238. if ((void *)this_fn != (void *)printf) {
  239. printf("E %p %p\n", this_fn, call_site);
  240. }
  241. }
  242. void
  243. __cyg_profile_func_exit(void *this_fn, void *call_site)
  244. {
  245. if ((void *)this_fn != (void *)printf) {
  246. printf("X %p %p\n", this_fn, call_site);
  247. }
  248. }
  249. #endif
  250. #if !defined(IGNORE_UNUSED_RESULT)
  251. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  252. #endif
  253. #if defined(__GNUC__) || defined(__MINGW32__)
  254. /* GCC unused function attribute seems fundamentally broken.
  255. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  256. * OR UNUSED" for individual functions failed.
  257. * Either the compiler creates an "unused-function" warning if a
  258. * function is not marked with __attribute__((unused)).
  259. * On the other hand, if the function is marked with this attribute,
  260. * but is used, the compiler raises a completely idiotic
  261. * "used-but-marked-unused" warning - and
  262. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  263. * raises error: unknown option after "#pragma GCC diagnostic".
  264. * Disable this warning completely, until the GCC guys sober up
  265. * again.
  266. */
  267. #pragma GCC diagnostic ignored "-Wunused-function"
  268. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  269. #else
  270. #define FUNCTION_MAY_BE_UNUSED
  271. #endif
  272. /* Some ANSI #includes are not available on Windows CE */
  273. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  274. #include <errno.h>
  275. #include <fcntl.h>
  276. #include <signal.h>
  277. #include <stdlib.h>
  278. #include <sys/stat.h>
  279. #include <sys/types.h>
  280. #endif /* !_WIN32_WCE */
  281. #if defined(__clang__)
  282. /* When using -Weverything, clang does not accept it's own headers
  283. * in a release build configuration. Disable what is too much in
  284. * -Weverything. */
  285. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  286. #endif
  287. #if defined(__GNUC__) || defined(__MINGW32__)
  288. /* Who on earth came to the conclusion, using __DATE__ should rise
  289. * an "expansion of date or time macro is not reproducible"
  290. * warning. That's exactly what was intended by using this macro.
  291. * Just disable this nonsense warning. */
  292. /* And disabling them does not work either:
  293. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  294. * #pragma clang diagnostic ignored "-Wdate-time"
  295. * So we just have to disable ALL warnings for some lines
  296. * of code.
  297. * This seems to be a known GCC bug, not resolved since 2012:
  298. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  299. */
  300. #endif
  301. #if defined(__MACH__) /* Apple OSX section */
  302. #if defined(__clang__)
  303. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  304. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  305. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  306. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  307. #endif
  308. #endif
  309. #define CLOCK_MONOTONIC (1)
  310. #define CLOCK_REALTIME (2)
  311. #include <mach/clock.h>
  312. #include <mach/mach.h>
  313. #include <mach/mach_time.h>
  314. #include <sys/errno.h>
  315. #include <sys/time.h>
  316. /* clock_gettime is not implemented on OSX prior to 10.12 */
  317. static int
  318. _civet_clock_gettime(int clk_id, struct timespec *t)
  319. {
  320. memset(t, 0, sizeof(*t));
  321. if (clk_id == CLOCK_REALTIME) {
  322. struct timeval now;
  323. int rv = gettimeofday(&now, NULL);
  324. if (rv) {
  325. return rv;
  326. }
  327. t->tv_sec = now.tv_sec;
  328. t->tv_nsec = now.tv_usec * 1000;
  329. return 0;
  330. } else if (clk_id == CLOCK_MONOTONIC) {
  331. static uint64_t clock_start_time = 0;
  332. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  333. uint64_t now = mach_absolute_time();
  334. if (clock_start_time == 0) {
  335. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  336. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  337. /* appease "unused variable" warning for release builds */
  338. (void)mach_status;
  339. clock_start_time = now;
  340. }
  341. now = (uint64_t)((double)(now - clock_start_time)
  342. * (double)timebase_ifo.numer
  343. / (double)timebase_ifo.denom);
  344. t->tv_sec = now / 1000000000;
  345. t->tv_nsec = now % 1000000000;
  346. return 0;
  347. }
  348. return -1; /* EINVAL - Clock ID is unknown */
  349. }
  350. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  351. #if defined(__CLOCK_AVAILABILITY)
  352. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  353. * declared but it may be NULL at runtime. So we need to check before using
  354. * it. */
  355. static int
  356. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  357. {
  358. if (clock_gettime) {
  359. return clock_gettime(clk_id, t);
  360. }
  361. return _civet_clock_gettime(clk_id, t);
  362. }
  363. #define clock_gettime _civet_safe_clock_gettime
  364. #else
  365. #define clock_gettime _civet_clock_gettime
  366. #endif
  367. #endif
  368. #if !defined(_WIN32)
  369. /* Unix might return different error codes indicating to try again.
  370. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  371. * decades ago, but better check both and let the compile optimize it. */
  372. #define ERROR_TRY_AGAIN(err) \
  373. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  374. #endif
  375. #if defined(USE_ZLIB)
  376. #include "zconf.h"
  377. #include "zlib.h"
  378. #endif
  379. /********************************************************************/
  380. /* CivetWeb configuration defines */
  381. /********************************************************************/
  382. /* Maximum number of threads that can be configured.
  383. * The number of threads actually created depends on the "num_threads"
  384. * configuration parameter, but this is the upper limit. */
  385. #if !defined(MAX_WORKER_THREADS)
  386. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  387. #endif
  388. /* Timeout interval for select/poll calls.
  389. * The timeouts depend on "*_timeout_ms" configuration values, but long
  390. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  391. * This reduces the time required to stop the server. */
  392. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  393. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  394. #endif
  395. /* Do not try to compress files smaller than this limit. */
  396. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  397. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  398. #endif
  399. #if !defined(PASSWORDS_FILE_NAME)
  400. #define PASSWORDS_FILE_NAME ".htpasswd"
  401. #endif
  402. /* Initial buffer size for all CGI environment variables. In case there is
  403. * not enough space, another block is allocated. */
  404. #if !defined(CGI_ENVIRONMENT_SIZE)
  405. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  406. #endif
  407. /* Maximum number of environment variables. */
  408. #if !defined(MAX_CGI_ENVIR_VARS)
  409. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  410. #endif
  411. /* General purpose buffer size. */
  412. #if !defined(MG_BUF_LEN) /* in bytes */
  413. #define MG_BUF_LEN (1024 * 8)
  414. #endif
  415. /********************************************************************/
  416. /* Helper makros */
  417. #if !defined(ARRAY_SIZE)
  418. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  419. #endif
  420. #include <stdint.h>
  421. /* Standard defines */
  422. #if !defined(INT64_MAX)
  423. #define INT64_MAX (9223372036854775807)
  424. #endif
  425. #define SHUTDOWN_RD (0)
  426. #define SHUTDOWN_WR (1)
  427. #define SHUTDOWN_BOTH (2)
  428. mg_static_assert(MAX_WORKER_THREADS >= 1,
  429. "worker threads must be a positive number");
  430. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  431. "size_t data type size check");
  432. #if defined(_WIN32) /* WINDOWS include block */
  433. #include <malloc.h> /* *alloc( */
  434. #include <stdlib.h> /* *alloc( */
  435. #include <time.h> /* struct timespec */
  436. #include <windows.h>
  437. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  438. #include <ws2tcpip.h>
  439. typedef const char *SOCK_OPT_TYPE;
  440. #if defined(_WIN32)
  441. /* For a detailed description of these defines, see
  442. * https://github.com/civetweb/civetweb/issues/937 (Nov 15, 2020). */
  443. /* The Microsoft SDK does not define PATH_MAX, but mingw does. */
  444. #ifdef PATH_MAX
  445. #undef PATH_MAX
  446. #endif
  447. /* PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  448. * null termination, rounded up to the next 4 bytes boundary */
  449. #define PATH_MAX (3 * 260)
  450. /* W_PATH_MAX is the wchar_t buffer size required for 259 BMP characters
  451. * plus termination. (Note: wchar_t is 16 bit on Windows) */
  452. #define W_PATH_MAX (260)
  453. #endif
  454. mg_static_assert(PATH_MAX >= 12, "path length must be a positive number");
  455. #if !defined(_IN_PORT_T)
  456. #if !defined(in_port_t)
  457. #define in_port_t u_short
  458. #endif
  459. #endif
  460. #if !defined(_WIN32_WCE)
  461. #include <direct.h>
  462. #include <io.h>
  463. #include <process.h>
  464. #else /* _WIN32_WCE */
  465. #define NO_CGI /* WinCE has no pipes */
  466. #define NO_POPEN /* WinCE has no popen */
  467. typedef long off_t;
  468. #define errno ((int)(GetLastError()))
  469. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  470. #endif /* _WIN32_WCE */
  471. #define MAKEUQUAD(lo, hi) \
  472. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  473. #define RATE_DIFF (10000000) /* 100 nsecs */
  474. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  475. #define SYS2UNIX_TIME(lo, hi) \
  476. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  477. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  478. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  479. * Also use _strtoui64 on modern M$ compilers */
  480. #if defined(_MSC_VER)
  481. #if (_MSC_VER < 1300)
  482. #define STRX(x) #x
  483. #define STR(x) STRX(x)
  484. #define __func__ __FILE__ ":" STR(__LINE__)
  485. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  486. #define strtoll(x, y, z) (_atoi64(x))
  487. #else
  488. #define __func__ __FUNCTION__
  489. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  490. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  491. #endif
  492. #endif /* _MSC_VER */
  493. #define ERRNO ((int)(GetLastError()))
  494. #define NO_SOCKLEN_T
  495. #if defined(_WIN64) || defined(__MINGW64__)
  496. #if !defined(SSL_LIB)
  497. #if defined(OPENSSL_API_1_1)
  498. #define SSL_LIB "libssl-1_1-x64.dll"
  499. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  500. #endif /* OPENSSL_API_1_1 */
  501. #if defined(OPENSSL_API_1_0)
  502. #define SSL_LIB "ssleay64.dll"
  503. #define CRYPTO_LIB "libeay64.dll"
  504. #endif /* OPENSSL_API_1_0 */
  505. #endif
  506. #else /* defined(_WIN64) || defined(__MINGW64__) */
  507. #if !defined(SSL_LIB)
  508. #if defined(OPENSSL_API_1_1)
  509. #define SSL_LIB "libssl-1_1.dll"
  510. #define CRYPTO_LIB "libcrypto-1_1.dll"
  511. #endif /* OPENSSL_API_1_1 */
  512. #if defined(OPENSSL_API_1_0)
  513. #define SSL_LIB "ssleay32.dll"
  514. #define CRYPTO_LIB "libeay32.dll"
  515. #endif /* OPENSSL_API_1_0 */
  516. #endif /* SSL_LIB */
  517. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  518. #define O_NONBLOCK (0)
  519. #if !defined(W_OK)
  520. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  521. #endif
  522. #define _POSIX_
  523. #define INT64_FMT "I64d"
  524. #define UINT64_FMT "I64u"
  525. #define WINCDECL __cdecl
  526. #define vsnprintf_impl _vsnprintf
  527. #define access _access
  528. #define mg_sleep(x) (Sleep(x))
  529. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  530. #if !defined(popen)
  531. #define popen(x, y) (_popen(x, y))
  532. #endif
  533. #if !defined(pclose)
  534. #define pclose(x) (_pclose(x))
  535. #endif
  536. #define close(x) (_close(x))
  537. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  538. #define RTLD_LAZY (0)
  539. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  540. #define fdopen(x, y) (_fdopen((x), (y)))
  541. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  542. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  543. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  544. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  545. #define sleep(x) (Sleep((x)*1000))
  546. #define rmdir(x) (_rmdir(x))
  547. #if defined(_WIN64) || !defined(__MINGW32__)
  548. /* Only MinGW 32 bit is missing this function */
  549. #define timegm(x) (_mkgmtime(x))
  550. #else
  551. time_t timegm(struct tm *tm);
  552. #define NEED_TIMEGM
  553. #endif
  554. #if !defined(fileno)
  555. #define fileno(x) (_fileno(x))
  556. #endif /* !fileno MINGW #defines fileno */
  557. typedef struct {
  558. CRITICAL_SECTION sec; /* Immovable */
  559. } pthread_mutex_t;
  560. typedef DWORD pthread_key_t;
  561. typedef HANDLE pthread_t;
  562. typedef struct {
  563. pthread_mutex_t threadIdSec;
  564. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  565. } pthread_cond_t;
  566. #if !defined(__clockid_t_defined)
  567. typedef DWORD clockid_t;
  568. #endif
  569. #if !defined(CLOCK_MONOTONIC)
  570. #define CLOCK_MONOTONIC (1)
  571. #endif
  572. #if !defined(CLOCK_REALTIME)
  573. #define CLOCK_REALTIME (2)
  574. #endif
  575. #if !defined(CLOCK_THREAD)
  576. #define CLOCK_THREAD (3)
  577. #endif
  578. #if !defined(CLOCK_PROCESS)
  579. #define CLOCK_PROCESS (4)
  580. #endif
  581. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  582. #define _TIMESPEC_DEFINED
  583. #endif
  584. #if !defined(_TIMESPEC_DEFINED)
  585. struct timespec {
  586. time_t tv_sec; /* seconds */
  587. long tv_nsec; /* nanoseconds */
  588. };
  589. #endif
  590. #if !defined(WIN_PTHREADS_TIME_H)
  591. #define MUST_IMPLEMENT_CLOCK_GETTIME
  592. #endif
  593. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  594. #define clock_gettime mg_clock_gettime
  595. static int
  596. clock_gettime(clockid_t clk_id, struct timespec *tp)
  597. {
  598. FILETIME ft;
  599. ULARGE_INTEGER li, li2;
  600. BOOL ok = FALSE;
  601. double d;
  602. static double perfcnt_per_sec = 0.0;
  603. static BOOL initialized = FALSE;
  604. if (!initialized) {
  605. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  606. perfcnt_per_sec = 1.0 / li.QuadPart;
  607. initialized = TRUE;
  608. }
  609. if (tp) {
  610. memset(tp, 0, sizeof(*tp));
  611. if (clk_id == CLOCK_REALTIME) {
  612. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  613. GetSystemTimeAsFileTime(&ft);
  614. li.LowPart = ft.dwLowDateTime;
  615. li.HighPart = ft.dwHighDateTime;
  616. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  617. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  618. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  619. ok = TRUE;
  620. /* END: CLOCK_REALTIME */
  621. } else if (clk_id == CLOCK_MONOTONIC) {
  622. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  623. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  624. d = li.QuadPart * perfcnt_per_sec;
  625. tp->tv_sec = (time_t)d;
  626. d -= (double)tp->tv_sec;
  627. tp->tv_nsec = (long)(d * 1.0E9);
  628. ok = TRUE;
  629. /* END: CLOCK_MONOTONIC */
  630. } else if (clk_id == CLOCK_THREAD) {
  631. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  632. FILETIME t_create, t_exit, t_kernel, t_user;
  633. if (GetThreadTimes(GetCurrentThread(),
  634. &t_create,
  635. &t_exit,
  636. &t_kernel,
  637. &t_user)) {
  638. li.LowPart = t_user.dwLowDateTime;
  639. li.HighPart = t_user.dwHighDateTime;
  640. li2.LowPart = t_kernel.dwLowDateTime;
  641. li2.HighPart = t_kernel.dwHighDateTime;
  642. li.QuadPart += li2.QuadPart;
  643. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  644. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  645. ok = TRUE;
  646. }
  647. /* END: CLOCK_THREAD */
  648. } else if (clk_id == CLOCK_PROCESS) {
  649. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  650. FILETIME t_create, t_exit, t_kernel, t_user;
  651. if (GetProcessTimes(GetCurrentProcess(),
  652. &t_create,
  653. &t_exit,
  654. &t_kernel,
  655. &t_user)) {
  656. li.LowPart = t_user.dwLowDateTime;
  657. li.HighPart = t_user.dwHighDateTime;
  658. li2.LowPart = t_kernel.dwLowDateTime;
  659. li2.HighPart = t_kernel.dwHighDateTime;
  660. li.QuadPart += li2.QuadPart;
  661. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  662. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  663. ok = TRUE;
  664. }
  665. /* END: CLOCK_PROCESS */
  666. } else {
  667. /* BEGIN: unknown clock */
  668. /* ok = FALSE; already set by init */
  669. /* END: unknown clock */
  670. }
  671. }
  672. return ok ? 0 : -1;
  673. }
  674. #endif
  675. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  676. static int pthread_mutex_lock(pthread_mutex_t *);
  677. static int pthread_mutex_unlock(pthread_mutex_t *);
  678. static void path_to_unicode(const struct mg_connection *conn,
  679. const char *path,
  680. wchar_t *wbuf,
  681. size_t wbuf_len);
  682. /* All file operations need to be rewritten to solve #246. */
  683. struct mg_file;
  684. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  685. /* POSIX dirent interface */
  686. struct dirent {
  687. char d_name[PATH_MAX];
  688. };
  689. typedef struct DIR {
  690. HANDLE handle;
  691. WIN32_FIND_DATAW info;
  692. struct dirent result;
  693. } DIR;
  694. #if defined(HAVE_POLL)
  695. #define mg_pollfd pollfd
  696. #else
  697. struct mg_pollfd {
  698. SOCKET fd;
  699. short events;
  700. short revents;
  701. };
  702. #endif
  703. /* Mark required libraries */
  704. #if defined(_MSC_VER)
  705. #pragma comment(lib, "Ws2_32.lib")
  706. #endif
  707. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  708. #include <inttypes.h>
  709. typedef const void *SOCK_OPT_TYPE;
  710. #if defined(ANDROID)
  711. typedef unsigned short int in_port_t;
  712. #endif
  713. #if !defined(__ZEPHYR__)
  714. #include <arpa/inet.h>
  715. #include <ctype.h>
  716. #include <dirent.h>
  717. #include <grp.h>
  718. #include <limits.h>
  719. #include <netdb.h>
  720. #include <netinet/in.h>
  721. #include <netinet/tcp.h>
  722. #include <pthread.h>
  723. #include <pwd.h>
  724. #include <stdarg.h>
  725. #include <stddef.h>
  726. #include <stdio.h>
  727. #include <stdlib.h>
  728. #include <string.h>
  729. #include <sys/poll.h>
  730. #include <sys/socket.h>
  731. #include <sys/time.h>
  732. #include <sys/utsname.h>
  733. #include <sys/wait.h>
  734. #include <time.h>
  735. #include <unistd.h>
  736. #if defined(USE_X_DOM_SOCKET)
  737. #include <sys/un.h>
  738. #endif
  739. #endif
  740. #define vsnprintf_impl vsnprintf
  741. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  742. #include <dlfcn.h>
  743. #endif
  744. #if defined(__MACH__)
  745. #define SSL_LIB "libssl.dylib"
  746. #define CRYPTO_LIB "libcrypto.dylib"
  747. #else
  748. #if !defined(SSL_LIB)
  749. #define SSL_LIB "libssl.so"
  750. #endif
  751. #if !defined(CRYPTO_LIB)
  752. #define CRYPTO_LIB "libcrypto.so"
  753. #endif
  754. #endif
  755. #if !defined(O_BINARY)
  756. #define O_BINARY (0)
  757. #endif /* O_BINARY */
  758. #define closesocket(a) (close(a))
  759. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  760. #define mg_remove(conn, x) (remove(x))
  761. #define mg_sleep(x) (usleep((x)*1000))
  762. #define mg_opendir(conn, x) (opendir(x))
  763. #define mg_closedir(x) (closedir(x))
  764. #define mg_readdir(x) (readdir(x))
  765. #define ERRNO (errno)
  766. #define INVALID_SOCKET (-1)
  767. #define INT64_FMT PRId64
  768. #define UINT64_FMT PRIu64
  769. typedef int SOCKET;
  770. #define WINCDECL
  771. #if defined(__hpux)
  772. /* HPUX 11 does not have monotonic, fall back to realtime */
  773. #if !defined(CLOCK_MONOTONIC)
  774. #define CLOCK_MONOTONIC CLOCK_REALTIME
  775. #endif
  776. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  777. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  778. * the prototypes use int* rather than socklen_t* which matches the
  779. * actual library expectation. When called with the wrong size arg
  780. * accept() returns a zero client inet addr and check_acl() always
  781. * fails. Since socklen_t is widely used below, just force replace
  782. * their typedef with int. - DTL
  783. */
  784. #define socklen_t int
  785. #endif /* hpux */
  786. #define mg_pollfd pollfd
  787. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  788. /* In case our C library is missing "timegm", provide an implementation */
  789. #if defined(NEED_TIMEGM)
  790. static inline int
  791. is_leap(int y)
  792. {
  793. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  794. }
  795. static inline int
  796. count_leap(int y)
  797. {
  798. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  799. }
  800. time_t
  801. timegm(struct tm *tm)
  802. {
  803. static const unsigned short ydays[] = {
  804. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  805. int year = tm->tm_year + 1900;
  806. int mon = tm->tm_mon;
  807. int mday = tm->tm_mday - 1;
  808. int hour = tm->tm_hour;
  809. int min = tm->tm_min;
  810. int sec = tm->tm_sec;
  811. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  812. || (mday >= ydays[mon + 1] - ydays[mon]
  813. + (mon == 1 && is_leap(year) ? 1 : 0))
  814. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  815. return -1;
  816. time_t res = year - 1970;
  817. res *= 365;
  818. res += mday;
  819. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  820. res += count_leap(year);
  821. res *= 24;
  822. res += hour;
  823. res *= 60;
  824. res += min;
  825. res *= 60;
  826. res += sec;
  827. return res;
  828. }
  829. #endif /* NEED_TIMEGM */
  830. /* va_copy should always be a macro, C99 and C++11 - DTL */
  831. #if !defined(va_copy)
  832. #define va_copy(x, y) ((x) = (y))
  833. #endif
  834. #if defined(_WIN32)
  835. /* Create substitutes for POSIX functions in Win32. */
  836. #if defined(GCC_DIAGNOSTIC)
  837. /* Show no warning in case system functions are not used. */
  838. #pragma GCC diagnostic push
  839. #pragma GCC diagnostic ignored "-Wunused-function"
  840. #endif
  841. static pthread_mutex_t global_log_file_lock;
  842. FUNCTION_MAY_BE_UNUSED
  843. static DWORD
  844. pthread_self(void)
  845. {
  846. return GetCurrentThreadId();
  847. }
  848. FUNCTION_MAY_BE_UNUSED
  849. static int
  850. pthread_key_create(
  851. pthread_key_t *key,
  852. void (*_ignored)(void *) /* destructor not supported for Windows */
  853. )
  854. {
  855. (void)_ignored;
  856. if ((key != 0)) {
  857. *key = TlsAlloc();
  858. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  859. }
  860. return -2;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static int
  864. pthread_key_delete(pthread_key_t key)
  865. {
  866. return TlsFree(key) ? 0 : 1;
  867. }
  868. FUNCTION_MAY_BE_UNUSED
  869. static int
  870. pthread_setspecific(pthread_key_t key, void *value)
  871. {
  872. return TlsSetValue(key, value) ? 0 : 1;
  873. }
  874. FUNCTION_MAY_BE_UNUSED
  875. static void *
  876. pthread_getspecific(pthread_key_t key)
  877. {
  878. return TlsGetValue(key);
  879. }
  880. #if defined(GCC_DIAGNOSTIC)
  881. /* Enable unused function warning again */
  882. #pragma GCC diagnostic pop
  883. #endif
  884. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  885. #else
  886. static pthread_mutexattr_t pthread_mutex_attr;
  887. #endif /* _WIN32 */
  888. #if defined(_WIN32_WCE)
  889. /* Create substitutes for POSIX functions in Win32. */
  890. #if defined(GCC_DIAGNOSTIC)
  891. /* Show no warning in case system functions are not used. */
  892. #pragma GCC diagnostic push
  893. #pragma GCC diagnostic ignored "-Wunused-function"
  894. #endif
  895. FUNCTION_MAY_BE_UNUSED
  896. static time_t
  897. time(time_t *ptime)
  898. {
  899. time_t t;
  900. SYSTEMTIME st;
  901. FILETIME ft;
  902. GetSystemTime(&st);
  903. SystemTimeToFileTime(&st, &ft);
  904. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  905. if (ptime != NULL) {
  906. *ptime = t;
  907. }
  908. return t;
  909. }
  910. FUNCTION_MAY_BE_UNUSED
  911. static struct tm *
  912. localtime_s(const time_t *ptime, struct tm *ptm)
  913. {
  914. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  915. FILETIME ft, lft;
  916. SYSTEMTIME st;
  917. TIME_ZONE_INFORMATION tzinfo;
  918. if (ptm == NULL) {
  919. return NULL;
  920. }
  921. *(int64_t *)&ft = t;
  922. FileTimeToLocalFileTime(&ft, &lft);
  923. FileTimeToSystemTime(&lft, &st);
  924. ptm->tm_year = st.wYear - 1900;
  925. ptm->tm_mon = st.wMonth - 1;
  926. ptm->tm_wday = st.wDayOfWeek;
  927. ptm->tm_mday = st.wDay;
  928. ptm->tm_hour = st.wHour;
  929. ptm->tm_min = st.wMinute;
  930. ptm->tm_sec = st.wSecond;
  931. ptm->tm_yday = 0; /* hope nobody uses this */
  932. ptm->tm_isdst =
  933. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  934. return ptm;
  935. }
  936. FUNCTION_MAY_BE_UNUSED
  937. static struct tm *
  938. gmtime_s(const time_t *ptime, struct tm *ptm)
  939. {
  940. /* FIXME(lsm): fix this. */
  941. return localtime_s(ptime, ptm);
  942. }
  943. static ptrdiff_t mg_atomic_inc(volatile ptrdiff_t *addr);
  944. static struct tm tm_array[MAX_WORKER_THREADS]; /* Must be 2^n */
  945. static volatile ptrdiff_t tm_index = 0;
  946. FUNCTION_MAY_BE_UNUSED
  947. static struct tm *
  948. localtime(const time_t *ptime)
  949. {
  950. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  951. return localtime_s(ptime, tm_array + i);
  952. }
  953. FUNCTION_MAY_BE_UNUSED
  954. static struct tm *
  955. gmtime(const time_t *ptime)
  956. {
  957. ptrdiff_t i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  958. return gmtime_s(ptime, tm_array + i);
  959. }
  960. FUNCTION_MAY_BE_UNUSED
  961. static size_t
  962. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  963. {
  964. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  965. * for WinCE"); */
  966. return 0;
  967. }
  968. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  969. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  970. #define remove(f) mg_remove(NULL, f)
  971. FUNCTION_MAY_BE_UNUSED
  972. static int
  973. rename(const char *a, const char *b)
  974. {
  975. wchar_t wa[W_PATH_MAX];
  976. wchar_t wb[W_PATH_MAX];
  977. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  978. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  979. return MoveFileW(wa, wb) ? 0 : -1;
  980. }
  981. struct stat {
  982. int64_t st_size;
  983. time_t st_mtime;
  984. };
  985. FUNCTION_MAY_BE_UNUSED
  986. static int
  987. stat(const char *name, struct stat *st)
  988. {
  989. wchar_t wbuf[W_PATH_MAX];
  990. WIN32_FILE_ATTRIBUTE_DATA attr;
  991. time_t creation_time, write_time;
  992. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  993. memset(&attr, 0, sizeof(attr));
  994. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  995. st->st_size =
  996. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  997. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  998. attr.ftLastWriteTime.dwHighDateTime);
  999. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  1000. attr.ftCreationTime.dwHighDateTime);
  1001. if (creation_time > write_time) {
  1002. st->st_mtime = creation_time;
  1003. } else {
  1004. st->st_mtime = write_time;
  1005. }
  1006. return 0;
  1007. }
  1008. #define access(x, a) 1 /* not required anyway */
  1009. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  1010. /* Values from errno.h in Windows SDK (Visual Studio). */
  1011. #define EEXIST 17
  1012. #define EACCES 13
  1013. #define ENOENT 2
  1014. #if defined(GCC_DIAGNOSTIC)
  1015. /* Enable unused function warning again */
  1016. #pragma GCC diagnostic pop
  1017. #endif
  1018. #endif /* defined(_WIN32_WCE) */
  1019. #if defined(GCC_DIAGNOSTIC)
  1020. /* Show no warning in case system functions are not used. */
  1021. #pragma GCC diagnostic push
  1022. #pragma GCC diagnostic ignored "-Wunused-function"
  1023. #endif /* defined(GCC_DIAGNOSTIC) */
  1024. #if defined(__clang__)
  1025. /* Show no warning in case system functions are not used. */
  1026. #pragma clang diagnostic push
  1027. #pragma clang diagnostic ignored "-Wunused-function"
  1028. #endif
  1029. static pthread_mutex_t global_lock_mutex;
  1030. FUNCTION_MAY_BE_UNUSED
  1031. static void
  1032. mg_global_lock(void)
  1033. {
  1034. (void)pthread_mutex_lock(&global_lock_mutex);
  1035. }
  1036. FUNCTION_MAY_BE_UNUSED
  1037. static void
  1038. mg_global_unlock(void)
  1039. {
  1040. (void)pthread_mutex_unlock(&global_lock_mutex);
  1041. }
  1042. #if defined(_WIN64)
  1043. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  1044. #elif defined(_WIN32)
  1045. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  1046. #endif
  1047. /* Atomic functions working on ptrdiff_t ("signed size_t").
  1048. * Operations: Increment, Decrement, Add, Maximum.
  1049. * Up to size_t, they do not an atomic "load" operation.
  1050. */
  1051. FUNCTION_MAY_BE_UNUSED
  1052. static ptrdiff_t
  1053. mg_atomic_inc(volatile ptrdiff_t *addr)
  1054. {
  1055. ptrdiff_t ret;
  1056. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1057. ret = InterlockedIncrement64(addr);
  1058. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1059. ret = InterlockedIncrement(addr);
  1060. #elif defined(__GNUC__) \
  1061. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1062. && !defined(NO_ATOMICS)
  1063. ret = __sync_add_and_fetch(addr, 1);
  1064. #else
  1065. mg_global_lock();
  1066. ret = (++(*addr));
  1067. mg_global_unlock();
  1068. #endif
  1069. return ret;
  1070. }
  1071. FUNCTION_MAY_BE_UNUSED
  1072. static ptrdiff_t
  1073. mg_atomic_dec(volatile ptrdiff_t *addr)
  1074. {
  1075. ptrdiff_t ret;
  1076. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1077. ret = InterlockedDecrement64(addr);
  1078. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1079. ret = InterlockedDecrement(addr);
  1080. #elif defined(__GNUC__) \
  1081. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1082. && !defined(NO_ATOMICS)
  1083. ret = __sync_sub_and_fetch(addr, 1);
  1084. #else
  1085. mg_global_lock();
  1086. ret = (--(*addr));
  1087. mg_global_unlock();
  1088. #endif
  1089. return ret;
  1090. }
  1091. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  1092. static ptrdiff_t
  1093. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1094. {
  1095. ptrdiff_t ret;
  1096. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1097. ret = InterlockedAdd64(addr, value);
  1098. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1099. ret = InterlockedExchangeAdd(addr, value) + value;
  1100. #elif defined(__GNUC__) \
  1101. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1102. && !defined(NO_ATOMICS)
  1103. ret = __sync_add_and_fetch(addr, value);
  1104. #else
  1105. mg_global_lock();
  1106. *addr += value;
  1107. ret = (*addr);
  1108. mg_global_unlock();
  1109. #endif
  1110. return ret;
  1111. }
  1112. FUNCTION_MAY_BE_UNUSED
  1113. static ptrdiff_t
  1114. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1115. ptrdiff_t oldval,
  1116. ptrdiff_t newval)
  1117. {
  1118. ptrdiff_t ret;
  1119. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1120. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1121. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1122. ret = InterlockedCompareExchange(addr, newval, oldval);
  1123. #elif defined(__GNUC__) \
  1124. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1125. && !defined(NO_ATOMICS)
  1126. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1127. #else
  1128. mg_global_lock();
  1129. ret = *addr;
  1130. if ((ret != newval) && (ret == oldval)) {
  1131. *addr = newval;
  1132. }
  1133. mg_global_unlock();
  1134. #endif
  1135. return ret;
  1136. }
  1137. static void
  1138. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1139. {
  1140. register ptrdiff_t tmp = *addr;
  1141. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1142. while (tmp < value) {
  1143. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1144. }
  1145. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1146. while (tmp < value) {
  1147. tmp = InterlockedCompareExchange(addr, value, tmp);
  1148. }
  1149. #elif defined(__GNUC__) \
  1150. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1151. && !defined(NO_ATOMICS)
  1152. while (tmp < value) {
  1153. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1154. }
  1155. #else
  1156. mg_global_lock();
  1157. if (*addr < value) {
  1158. *addr = value;
  1159. }
  1160. mg_global_unlock();
  1161. #endif
  1162. }
  1163. static int64_t
  1164. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1165. {
  1166. int64_t ret;
  1167. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1168. ret = InterlockedAdd64(addr, value);
  1169. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1170. ret = InterlockedExchangeAdd64(addr, value) + value;
  1171. #elif defined(__GNUC__) \
  1172. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1173. && !defined(NO_ATOMICS)
  1174. ret = __sync_add_and_fetch(addr, value);
  1175. #else
  1176. mg_global_lock();
  1177. *addr += value;
  1178. ret = (*addr);
  1179. mg_global_unlock();
  1180. #endif
  1181. return ret;
  1182. }
  1183. #endif
  1184. #if defined(GCC_DIAGNOSTIC)
  1185. /* Show no warning in case system functions are not used. */
  1186. #pragma GCC diagnostic pop
  1187. #endif /* defined(GCC_DIAGNOSTIC) */
  1188. #if defined(__clang__)
  1189. /* Show no warning in case system functions are not used. */
  1190. #pragma clang diagnostic pop
  1191. #endif
  1192. #if defined(USE_SERVER_STATS)
  1193. struct mg_memory_stat {
  1194. volatile ptrdiff_t totalMemUsed;
  1195. volatile ptrdiff_t maxMemUsed;
  1196. volatile ptrdiff_t blockCount;
  1197. };
  1198. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1199. static void *
  1200. mg_malloc_ex(size_t size,
  1201. struct mg_context *ctx,
  1202. const char *file,
  1203. unsigned line)
  1204. {
  1205. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1206. void *memory = 0;
  1207. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1208. #if defined(MEMORY_DEBUGGING)
  1209. char mallocStr[256];
  1210. #else
  1211. (void)file;
  1212. (void)line;
  1213. #endif
  1214. if (data) {
  1215. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1216. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1217. mg_atomic_inc(&mstat->blockCount);
  1218. ((uintptr_t *)data)[0] = size;
  1219. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1220. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1221. }
  1222. #if defined(MEMORY_DEBUGGING)
  1223. sprintf(mallocStr,
  1224. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1225. memory,
  1226. (unsigned long)size,
  1227. (unsigned long)mstat->totalMemUsed,
  1228. (unsigned long)mstat->blockCount,
  1229. file,
  1230. line);
  1231. DEBUG_TRACE("%s", mallocStr);
  1232. #endif
  1233. return memory;
  1234. }
  1235. static void *
  1236. mg_calloc_ex(size_t count,
  1237. size_t size,
  1238. struct mg_context *ctx,
  1239. const char *file,
  1240. unsigned line)
  1241. {
  1242. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1243. if (data) {
  1244. memset(data, 0, size * count);
  1245. }
  1246. return data;
  1247. }
  1248. static void
  1249. mg_free_ex(void *memory, const char *file, unsigned line)
  1250. {
  1251. #if defined(MEMORY_DEBUGGING)
  1252. char mallocStr[256];
  1253. #else
  1254. (void)file;
  1255. (void)line;
  1256. #endif
  1257. if (memory) {
  1258. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1259. uintptr_t size = ((uintptr_t *)data)[0];
  1260. struct mg_memory_stat *mstat =
  1261. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1262. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1263. mg_atomic_dec(&mstat->blockCount);
  1264. #if defined(MEMORY_DEBUGGING)
  1265. sprintf(mallocStr,
  1266. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1267. memory,
  1268. (unsigned long)size,
  1269. (unsigned long)mstat->totalMemUsed,
  1270. (unsigned long)mstat->blockCount,
  1271. file,
  1272. line);
  1273. DEBUG_TRACE("%s", mallocStr);
  1274. #endif
  1275. free(data);
  1276. }
  1277. }
  1278. static void *
  1279. mg_realloc_ex(void *memory,
  1280. size_t newsize,
  1281. struct mg_context *ctx,
  1282. const char *file,
  1283. unsigned line)
  1284. {
  1285. void *data;
  1286. void *_realloc;
  1287. uintptr_t oldsize;
  1288. #if defined(MEMORY_DEBUGGING)
  1289. char mallocStr[256];
  1290. #else
  1291. (void)file;
  1292. (void)line;
  1293. #endif
  1294. if (newsize) {
  1295. if (memory) {
  1296. /* Reallocate existing block */
  1297. struct mg_memory_stat *mstat;
  1298. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1299. oldsize = ((uintptr_t *)data)[0];
  1300. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1301. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1302. if (_realloc) {
  1303. data = _realloc;
  1304. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1305. #if defined(MEMORY_DEBUGGING)
  1306. sprintf(mallocStr,
  1307. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1308. memory,
  1309. (unsigned long)oldsize,
  1310. (unsigned long)mstat->totalMemUsed,
  1311. (unsigned long)mstat->blockCount,
  1312. file,
  1313. line);
  1314. DEBUG_TRACE("%s", mallocStr);
  1315. #endif
  1316. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1317. #if defined(MEMORY_DEBUGGING)
  1318. sprintf(mallocStr,
  1319. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1320. memory,
  1321. (unsigned long)newsize,
  1322. (unsigned long)mstat->totalMemUsed,
  1323. (unsigned long)mstat->blockCount,
  1324. file,
  1325. line);
  1326. DEBUG_TRACE("%s", mallocStr);
  1327. #endif
  1328. *(uintptr_t *)data = newsize;
  1329. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1330. } else {
  1331. #if defined(MEMORY_DEBUGGING)
  1332. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1333. #endif
  1334. return _realloc;
  1335. }
  1336. } else {
  1337. /* Allocate new block */
  1338. data = mg_malloc_ex(newsize, ctx, file, line);
  1339. }
  1340. } else {
  1341. /* Free existing block */
  1342. data = 0;
  1343. mg_free_ex(memory, file, line);
  1344. }
  1345. return data;
  1346. }
  1347. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1348. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1349. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1350. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1351. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1352. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1353. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1354. #else /* USE_SERVER_STATS */
  1355. static __inline void *
  1356. mg_malloc(size_t a)
  1357. {
  1358. return malloc(a);
  1359. }
  1360. static __inline void *
  1361. mg_calloc(size_t a, size_t b)
  1362. {
  1363. return calloc(a, b);
  1364. }
  1365. static __inline void *
  1366. mg_realloc(void *a, size_t b)
  1367. {
  1368. return realloc(a, b);
  1369. }
  1370. static __inline void
  1371. mg_free(void *a)
  1372. {
  1373. free(a);
  1374. }
  1375. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1376. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1377. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1378. #define mg_free_ctx(a, c) mg_free(a)
  1379. #endif /* USE_SERVER_STATS */
  1380. static void mg_vsnprintf(const struct mg_connection *conn,
  1381. int *truncated,
  1382. char *buf,
  1383. size_t buflen,
  1384. const char *fmt,
  1385. va_list ap);
  1386. static void mg_snprintf(const struct mg_connection *conn,
  1387. int *truncated,
  1388. char *buf,
  1389. size_t buflen,
  1390. PRINTF_FORMAT_STRING(const char *fmt),
  1391. ...) PRINTF_ARGS(5, 6);
  1392. /* This following lines are just meant as a reminder to use the mg-functions
  1393. * for memory management */
  1394. #if defined(malloc)
  1395. #undef malloc
  1396. #endif
  1397. #if defined(calloc)
  1398. #undef calloc
  1399. #endif
  1400. #if defined(realloc)
  1401. #undef realloc
  1402. #endif
  1403. #if defined(free)
  1404. #undef free
  1405. #endif
  1406. #if defined(snprintf)
  1407. #undef snprintf
  1408. #endif
  1409. #if defined(vsnprintf)
  1410. #undef vsnprintf
  1411. #endif
  1412. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1413. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1414. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1415. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1416. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1417. #if defined(_WIN32)
  1418. /* vsnprintf must not be used in any system,
  1419. * but this define only works well for Windows. */
  1420. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1421. #endif
  1422. /* mg_init_library counter */
  1423. static int mg_init_library_called = 0;
  1424. #if !defined(NO_SSL)
  1425. static int mg_ssl_initialized = 0;
  1426. /* TODO: Selection of SSL library and version */
  1427. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1)
  1428. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1429. #endif
  1430. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1431. #error "Multiple OPENSSL_API versions defined"
  1432. #endif
  1433. #endif /* NO_SSL */
  1434. static pthread_key_t sTlsKey; /* Thread local storage index */
  1435. static volatile ptrdiff_t thread_idx_max = 0;
  1436. #if defined(MG_LEGACY_INTERFACE)
  1437. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1438. #endif
  1439. struct mg_workerTLS {
  1440. int is_master;
  1441. unsigned long thread_idx;
  1442. void *user_ptr;
  1443. #if defined(_WIN32)
  1444. HANDLE pthread_cond_helper_mutex;
  1445. struct mg_workerTLS *next_waiting_thread;
  1446. #endif
  1447. const char *alpn_proto;
  1448. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1449. char txtbuf[4];
  1450. #endif
  1451. };
  1452. #if defined(GCC_DIAGNOSTIC)
  1453. /* Show no warning in case system functions are not used. */
  1454. #pragma GCC diagnostic push
  1455. #pragma GCC diagnostic ignored "-Wunused-function"
  1456. #endif /* defined(GCC_DIAGNOSTIC) */
  1457. #if defined(__clang__)
  1458. /* Show no warning in case system functions are not used. */
  1459. #pragma clang diagnostic push
  1460. #pragma clang diagnostic ignored "-Wunused-function"
  1461. #endif
  1462. /* Get a unique thread ID as unsigned long, independent from the data type
  1463. * of thread IDs defined by the operating system API.
  1464. * If two calls to mg_current_thread_id return the same value, they calls
  1465. * are done from the same thread. If they return different values, they are
  1466. * done from different threads. (Provided this function is used in the same
  1467. * process context and threads are not repeatedly created and deleted, but
  1468. * CivetWeb does not do that).
  1469. * This function must match the signature required for SSL id callbacks:
  1470. * CRYPTO_set_id_callback
  1471. */
  1472. FUNCTION_MAY_BE_UNUSED
  1473. static unsigned long
  1474. mg_current_thread_id(void)
  1475. {
  1476. #if defined(_WIN32)
  1477. return GetCurrentThreadId();
  1478. #else
  1479. #if defined(__clang__)
  1480. #pragma clang diagnostic push
  1481. #pragma clang diagnostic ignored "-Wunreachable-code"
  1482. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1483. * or not, so one of the two conditions will be unreachable by construction.
  1484. * Unfortunately the C standard does not define a way to check this at
  1485. * compile time, since the #if preprocessor conditions can not use the sizeof
  1486. * operator as an argument. */
  1487. #endif
  1488. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1489. /* This is the problematic case for CRYPTO_set_id_callback:
  1490. * The OS pthread_t can not be cast to unsigned long. */
  1491. struct mg_workerTLS *tls =
  1492. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1493. if (tls == NULL) {
  1494. /* SSL called from an unknown thread: Create some thread index.
  1495. */
  1496. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1497. tls->is_master = -2; /* -2 means "3rd party thread" */
  1498. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1499. pthread_setspecific(sTlsKey, tls);
  1500. }
  1501. return tls->thread_idx;
  1502. } else {
  1503. /* pthread_t may be any data type, so a simple cast to unsigned long
  1504. * can rise a warning/error, depending on the platform.
  1505. * Here memcpy is used as an anything-to-anything cast. */
  1506. unsigned long ret = 0;
  1507. pthread_t t = pthread_self();
  1508. memcpy(&ret, &t, sizeof(pthread_t));
  1509. return ret;
  1510. }
  1511. #if defined(__clang__)
  1512. #pragma clang diagnostic pop
  1513. #endif
  1514. #endif
  1515. }
  1516. FUNCTION_MAY_BE_UNUSED
  1517. static uint64_t
  1518. mg_get_current_time_ns(void)
  1519. {
  1520. struct timespec tsnow;
  1521. clock_gettime(CLOCK_REALTIME, &tsnow);
  1522. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1523. }
  1524. #if defined(GCC_DIAGNOSTIC)
  1525. /* Show no warning in case system functions are not used. */
  1526. #pragma GCC diagnostic pop
  1527. #endif /* defined(GCC_DIAGNOSTIC) */
  1528. #if defined(__clang__)
  1529. /* Show no warning in case system functions are not used. */
  1530. #pragma clang diagnostic pop
  1531. #endif
  1532. #if defined(NEED_DEBUG_TRACE_FUNC)
  1533. static void
  1534. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1535. {
  1536. va_list args;
  1537. struct timespec tsnow;
  1538. /* Get some operating system independent thread id */
  1539. unsigned long thread_id = mg_current_thread_id();
  1540. clock_gettime(CLOCK_REALTIME, &tsnow);
  1541. flockfile(DEBUG_TRACE_STREAM);
  1542. fprintf(DEBUG_TRACE_STREAM,
  1543. "*** %lu.%09lu %lu %s:%u: ",
  1544. (unsigned long)tsnow.tv_sec,
  1545. (unsigned long)tsnow.tv_nsec,
  1546. thread_id,
  1547. func,
  1548. line);
  1549. va_start(args, fmt);
  1550. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1551. va_end(args);
  1552. putc('\n', DEBUG_TRACE_STREAM);
  1553. fflush(DEBUG_TRACE_STREAM);
  1554. funlockfile(DEBUG_TRACE_STREAM);
  1555. }
  1556. #endif /* NEED_DEBUG_TRACE_FUNC */
  1557. #define MD5_STATIC static
  1558. #include "md5.inl"
  1559. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1560. #if defined(NO_SOCKLEN_T)
  1561. typedef int socklen_t;
  1562. #endif /* NO_SOCKLEN_T */
  1563. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1564. #if !defined(MSG_NOSIGNAL)
  1565. #define MSG_NOSIGNAL (0)
  1566. #endif
  1567. #if defined(NO_SSL)
  1568. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1569. typedef struct SSL_CTX SSL_CTX;
  1570. #else
  1571. #if defined(NO_SSL_DL)
  1572. #include <openssl/bn.h>
  1573. #include <openssl/conf.h>
  1574. #include <openssl/crypto.h>
  1575. #include <openssl/dh.h>
  1576. #include <openssl/engine.h>
  1577. #include <openssl/err.h>
  1578. #include <openssl/opensslv.h>
  1579. #include <openssl/pem.h>
  1580. #include <openssl/ssl.h>
  1581. #include <openssl/tls1.h>
  1582. #include <openssl/x509.h>
  1583. #if defined(WOLFSSL_VERSION)
  1584. /* Additional defines for WolfSSL, see
  1585. * https://github.com/civetweb/civetweb/issues/583 */
  1586. #include "wolfssl_extras.inl"
  1587. #endif
  1588. #if defined(OPENSSL_IS_BORINGSSL)
  1589. /* From boringssl/src/include/openssl/mem.h:
  1590. *
  1591. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1592. * However, that was written in a time before Valgrind and ASAN. Since we now
  1593. * have those tools, the OpenSSL allocation functions are simply macros around
  1594. * the standard memory functions.
  1595. *
  1596. * #define OPENSSL_free free */
  1597. #define free free
  1598. // disable for boringssl
  1599. #define CONF_modules_unload(a) ((void)0)
  1600. #define ENGINE_cleanup() ((void)0)
  1601. #endif
  1602. /* If OpenSSL headers are included, automatically select the API version */
  1603. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1604. #if !defined(OPENSSL_API_1_1)
  1605. #define OPENSSL_API_1_1
  1606. #endif
  1607. #define OPENSSL_REMOVE_THREAD_STATE()
  1608. #else
  1609. #if !defined(OPENSSL_API_1_0)
  1610. #define OPENSSL_API_1_0
  1611. #endif
  1612. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1613. #endif
  1614. #else
  1615. /* SSL loaded dynamically from DLL.
  1616. * I put the prototypes here to be independent from OpenSSL source
  1617. * installation. */
  1618. typedef struct ssl_st SSL;
  1619. typedef struct ssl_method_st SSL_METHOD;
  1620. typedef struct ssl_ctx_st SSL_CTX;
  1621. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1622. typedef struct x509_name X509_NAME;
  1623. typedef struct asn1_integer ASN1_INTEGER;
  1624. typedef struct bignum BIGNUM;
  1625. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1626. typedef struct evp_md EVP_MD;
  1627. typedef struct x509 X509;
  1628. #define SSL_CTRL_OPTIONS (32)
  1629. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1630. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1631. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1632. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1633. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1634. #define SSL_VERIFY_NONE (0)
  1635. #define SSL_VERIFY_PEER (1)
  1636. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1637. #define SSL_VERIFY_CLIENT_ONCE (4)
  1638. #define SSL_OP_ALL (0x80000BFFul)
  1639. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1640. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1641. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1642. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1643. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1644. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1645. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1646. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1647. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1648. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1649. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1650. #define SSL_CB_HANDSHAKE_START (0x10)
  1651. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1652. #define SSL_ERROR_NONE (0)
  1653. #define SSL_ERROR_SSL (1)
  1654. #define SSL_ERROR_WANT_READ (2)
  1655. #define SSL_ERROR_WANT_WRITE (3)
  1656. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1657. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1658. #define SSL_ERROR_ZERO_RETURN (6)
  1659. #define SSL_ERROR_WANT_CONNECT (7)
  1660. #define SSL_ERROR_WANT_ACCEPT (8)
  1661. #define TLSEXT_TYPE_server_name (0)
  1662. #define TLSEXT_NAMETYPE_host_name (0)
  1663. #define SSL_TLSEXT_ERR_OK (0)
  1664. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1665. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1666. #define SSL_TLSEXT_ERR_NOACK (3)
  1667. #define SSL_SESS_CACHE_BOTH (3)
  1668. enum ssl_func_category {
  1669. TLS_Mandatory, /* required for HTTPS */
  1670. TLS_ALPN, /* required for Application Layer Protocol Negotiation */
  1671. TLS_END_OF_LIST
  1672. };
  1673. /* Check if all TLS functions/features are available */
  1674. static int tls_feature_missing[TLS_END_OF_LIST] = {0};
  1675. struct ssl_func {
  1676. const char *name; /* SSL function name */
  1677. enum ssl_func_category required; /* Mandatory or optional */
  1678. void (*ptr)(void); /* Function pointer */
  1679. };
  1680. #if defined(OPENSSL_API_1_1)
  1681. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1682. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1683. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1684. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1685. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1686. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1687. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1688. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1689. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1690. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1691. #define OPENSSL_init_ssl \
  1692. (*(int (*)(uint64_t opts, \
  1693. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1694. .ptr)
  1695. #define SSL_CTX_use_PrivateKey_file \
  1696. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1697. #define SSL_CTX_use_certificate_file \
  1698. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1699. #define SSL_CTX_set_default_passwd_cb \
  1700. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1701. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1702. #define SSL_CTX_use_certificate_chain_file \
  1703. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1704. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1705. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1706. #define SSL_CTX_set_verify \
  1707. (*(void (*)(SSL_CTX *, \
  1708. int, \
  1709. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1710. .ptr)
  1711. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1712. #define SSL_CTX_load_verify_locations \
  1713. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1714. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1715. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1716. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1717. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1718. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1719. #define SSL_CIPHER_get_name \
  1720. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1721. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1722. #define SSL_CTX_set_session_id_context \
  1723. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1724. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1725. #define SSL_CTX_set_cipher_list \
  1726. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1727. #define SSL_CTX_set_options \
  1728. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1729. #define SSL_CTX_set_info_callback \
  1730. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1731. ssl_sw[32] \
  1732. .ptr)
  1733. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1734. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1735. #define SSL_CTX_callback_ctrl \
  1736. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1737. #define SSL_get_servername \
  1738. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1739. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1740. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1741. #define SSL_CTX_set_alpn_protos \
  1742. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1743. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1744. const unsigned char **out,
  1745. unsigned char *outlen,
  1746. const unsigned char *in,
  1747. unsigned int inlen,
  1748. void *arg);
  1749. #define SSL_CTX_set_alpn_select_cb \
  1750. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1751. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1752. const unsigned char **out,
  1753. unsigned int *outlen,
  1754. void *arg);
  1755. #define SSL_CTX_set_next_protos_advertised_cb \
  1756. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1757. .ptr)
  1758. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1759. #define SSL_CTX_clear_options(ctx, op) \
  1760. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1761. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1762. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1763. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1764. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1765. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1766. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1767. SSL_CTX_callback_ctrl(ctx, \
  1768. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1769. (void (*)(void))cb)
  1770. #define SSL_set_tlsext_host_name(ctx, arg) \
  1771. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1772. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1773. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1774. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1775. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1776. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1777. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1778. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1779. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1780. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1781. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1782. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1783. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1784. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1785. #define X509_NAME_oneline \
  1786. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1787. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1788. #define EVP_get_digestbyname \
  1789. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1790. #define EVP_Digest \
  1791. (*(int (*)( \
  1792. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1793. crypto_sw[9] \
  1794. .ptr)
  1795. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1796. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1797. #define ASN1_INTEGER_to_BN \
  1798. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1799. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1800. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1801. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1802. #define OPENSSL_free(a) CRYPTO_free(a)
  1803. #define OPENSSL_REMOVE_THREAD_STATE()
  1804. /* init_ssl_ctx() function updates this array.
  1805. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1806. * of respective functions. The macros above (like SSL_connect()) are really
  1807. * just calling these functions indirectly via the pointer. */
  1808. static struct ssl_func ssl_sw[] = {
  1809. {"SSL_free", TLS_Mandatory, NULL},
  1810. {"SSL_accept", TLS_Mandatory, NULL},
  1811. {"SSL_connect", TLS_Mandatory, NULL},
  1812. {"SSL_read", TLS_Mandatory, NULL},
  1813. {"SSL_write", TLS_Mandatory, NULL},
  1814. {"SSL_get_error", TLS_Mandatory, NULL},
  1815. {"SSL_set_fd", TLS_Mandatory, NULL},
  1816. {"SSL_new", TLS_Mandatory, NULL},
  1817. {"SSL_CTX_new", TLS_Mandatory, NULL},
  1818. {"TLS_server_method", TLS_Mandatory, NULL},
  1819. {"OPENSSL_init_ssl", TLS_Mandatory, NULL},
  1820. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  1821. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  1822. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  1823. {"SSL_CTX_free", TLS_Mandatory, NULL},
  1824. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  1825. {"TLS_client_method", TLS_Mandatory, NULL},
  1826. {"SSL_pending", TLS_Mandatory, NULL},
  1827. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  1828. {"SSL_shutdown", TLS_Mandatory, NULL},
  1829. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  1830. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  1831. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  1832. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  1833. {"SSL_get_version", TLS_Mandatory, NULL},
  1834. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  1835. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  1836. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  1837. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  1838. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  1839. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  1840. {"SSL_CTX_set_options", TLS_Mandatory, NULL},
  1841. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  1842. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  1843. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  1844. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  1845. {"SSL_get_servername", TLS_Mandatory, NULL},
  1846. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  1847. {"SSL_ctrl", TLS_Mandatory, NULL},
  1848. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  1849. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  1850. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  1851. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  1852. {NULL, TLS_END_OF_LIST, NULL}};
  1853. /* Similar array as ssl_sw. These functions could be located in different
  1854. * lib. */
  1855. static struct ssl_func crypto_sw[] = {
  1856. {"ERR_get_error", TLS_Mandatory, NULL},
  1857. {"ERR_error_string", TLS_Mandatory, NULL},
  1858. {"CONF_modules_unload", TLS_Mandatory, NULL},
  1859. {"X509_free", TLS_Mandatory, NULL},
  1860. {"X509_get_subject_name", TLS_Mandatory, NULL},
  1861. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  1862. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  1863. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  1864. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  1865. {"EVP_Digest", TLS_Mandatory, NULL},
  1866. {"i2d_X509", TLS_Mandatory, NULL},
  1867. {"BN_bn2hex", TLS_Mandatory, NULL},
  1868. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  1869. {"BN_free", TLS_Mandatory, NULL},
  1870. {"CRYPTO_free", TLS_Mandatory, NULL},
  1871. {"ERR_clear_error", TLS_Mandatory, NULL},
  1872. {NULL, TLS_END_OF_LIST, NULL}};
  1873. #else
  1874. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1875. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1876. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1877. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1878. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1879. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1880. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1881. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1882. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1883. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1884. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1885. #define SSL_CTX_use_PrivateKey_file \
  1886. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1887. #define SSL_CTX_use_certificate_file \
  1888. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1889. #define SSL_CTX_set_default_passwd_cb \
  1890. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1891. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1892. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1893. #define SSL_CTX_use_certificate_chain_file \
  1894. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1895. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1896. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1897. #define SSL_CTX_set_verify \
  1898. (*(void (*)(SSL_CTX *, \
  1899. int, \
  1900. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1901. .ptr)
  1902. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1903. #define SSL_CTX_load_verify_locations \
  1904. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1905. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1906. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1907. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1908. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1909. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1910. #define SSL_CIPHER_get_name \
  1911. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1912. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1913. #define SSL_CTX_set_session_id_context \
  1914. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1915. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1916. #define SSL_CTX_set_cipher_list \
  1917. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1918. #define SSL_CTX_set_info_callback \
  1919. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1920. .ptr)
  1921. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1922. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1923. #define SSL_CTX_callback_ctrl \
  1924. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1925. #define SSL_get_servername \
  1926. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1927. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1928. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1929. #define SSL_CTX_set_alpn_protos \
  1930. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned))ssl_sw[39].ptr)
  1931. typedef int (*tSSL_alpn_select_cb)(SSL *ssl,
  1932. const unsigned char **out,
  1933. unsigned char *outlen,
  1934. const unsigned char *in,
  1935. unsigned int inlen,
  1936. void *arg);
  1937. #define SSL_CTX_set_alpn_select_cb \
  1938. (*(void (*)(SSL_CTX *, tSSL_alpn_select_cb, void *))ssl_sw[40].ptr)
  1939. typedef int (*tSSL_next_protos_advertised_cb)(SSL *ssl,
  1940. const unsigned char **out,
  1941. unsigned int *outlen,
  1942. void *arg);
  1943. #define SSL_CTX_set_next_protos_advertised_cb \
  1944. (*(void (*)(SSL_CTX *, tSSL_next_protos_advertised_cb, void *))ssl_sw[41] \
  1945. .ptr)
  1946. #define SSL_CTX_set_timeout (*(long (*)(SSL_CTX *, long))ssl_sw[42].ptr)
  1947. #define SSL_CTX_set_options(ctx, op) \
  1948. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1949. #define SSL_CTX_clear_options(ctx, op) \
  1950. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1951. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1952. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1953. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1954. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1955. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1956. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1957. SSL_CTX_callback_ctrl(ctx, \
  1958. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1959. (void (*)(void))cb)
  1960. #define SSL_set_tlsext_host_name(ctx, arg) \
  1961. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1962. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1963. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1964. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1965. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1966. #define SSL_CTX_sess_set_cache_size(ctx, size) SSL_CTX_ctrl(ctx, 42, size, NULL)
  1967. #define SSL_CTX_set_session_cache_mode(ctx, mode) \
  1968. SSL_CTX_ctrl(ctx, 44, mode, NULL)
  1969. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1970. #define CRYPTO_set_locking_callback \
  1971. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1972. #define CRYPTO_set_id_callback \
  1973. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1974. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1975. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1976. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1977. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1978. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1979. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1980. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1981. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1982. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1983. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1984. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1985. #define X509_NAME_oneline \
  1986. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1987. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1988. #define i2c_ASN1_INTEGER \
  1989. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1990. #define EVP_get_digestbyname \
  1991. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1992. #define EVP_Digest \
  1993. (*(int (*)( \
  1994. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1995. crypto_sw[18] \
  1996. .ptr)
  1997. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1998. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1999. #define ASN1_INTEGER_to_BN \
  2000. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  2001. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  2002. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  2003. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  2004. #define OPENSSL_free(a) CRYPTO_free(a)
  2005. /* use here ERR_remove_state,
  2006. * while on some platforms function is not included into library due to
  2007. * deprication */
  2008. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  2009. /* init_ssl_ctx() function updates this array.
  2010. * It loads SSL library dynamically and changes NULLs to the actual addresses
  2011. * of respective functions. The macros above (like SSL_connect()) are really
  2012. * just calling these functions indirectly via the pointer. */
  2013. static struct ssl_func ssl_sw[] = {
  2014. {"SSL_free", TLS_Mandatory, NULL},
  2015. {"SSL_accept", TLS_Mandatory, NULL},
  2016. {"SSL_connect", TLS_Mandatory, NULL},
  2017. {"SSL_read", TLS_Mandatory, NULL},
  2018. {"SSL_write", TLS_Mandatory, NULL},
  2019. {"SSL_get_error", TLS_Mandatory, NULL},
  2020. {"SSL_set_fd", TLS_Mandatory, NULL},
  2021. {"SSL_new", TLS_Mandatory, NULL},
  2022. {"SSL_CTX_new", TLS_Mandatory, NULL},
  2023. {"SSLv23_server_method", TLS_Mandatory, NULL},
  2024. {"SSL_library_init", TLS_Mandatory, NULL},
  2025. {"SSL_CTX_use_PrivateKey_file", TLS_Mandatory, NULL},
  2026. {"SSL_CTX_use_certificate_file", TLS_Mandatory, NULL},
  2027. {"SSL_CTX_set_default_passwd_cb", TLS_Mandatory, NULL},
  2028. {"SSL_CTX_free", TLS_Mandatory, NULL},
  2029. {"SSL_load_error_strings", TLS_Mandatory, NULL},
  2030. {"SSL_CTX_use_certificate_chain_file", TLS_Mandatory, NULL},
  2031. {"SSLv23_client_method", TLS_Mandatory, NULL},
  2032. {"SSL_pending", TLS_Mandatory, NULL},
  2033. {"SSL_CTX_set_verify", TLS_Mandatory, NULL},
  2034. {"SSL_shutdown", TLS_Mandatory, NULL},
  2035. {"SSL_CTX_load_verify_locations", TLS_Mandatory, NULL},
  2036. {"SSL_CTX_set_default_verify_paths", TLS_Mandatory, NULL},
  2037. {"SSL_CTX_set_verify_depth", TLS_Mandatory, NULL},
  2038. {"SSL_get_peer_certificate", TLS_Mandatory, NULL},
  2039. {"SSL_get_version", TLS_Mandatory, NULL},
  2040. {"SSL_get_current_cipher", TLS_Mandatory, NULL},
  2041. {"SSL_CIPHER_get_name", TLS_Mandatory, NULL},
  2042. {"SSL_CTX_check_private_key", TLS_Mandatory, NULL},
  2043. {"SSL_CTX_set_session_id_context", TLS_Mandatory, NULL},
  2044. {"SSL_CTX_ctrl", TLS_Mandatory, NULL},
  2045. {"SSL_CTX_set_cipher_list", TLS_Mandatory, NULL},
  2046. {"SSL_CTX_set_info_callback", TLS_Mandatory, NULL},
  2047. {"SSL_get_ex_data", TLS_Mandatory, NULL},
  2048. {"SSL_set_ex_data", TLS_Mandatory, NULL},
  2049. {"SSL_CTX_callback_ctrl", TLS_Mandatory, NULL},
  2050. {"SSL_get_servername", TLS_Mandatory, NULL},
  2051. {"SSL_set_SSL_CTX", TLS_Mandatory, NULL},
  2052. {"SSL_ctrl", TLS_Mandatory, NULL},
  2053. {"SSL_CTX_set_alpn_protos", TLS_ALPN, NULL},
  2054. {"SSL_CTX_set_alpn_select_cb", TLS_ALPN, NULL},
  2055. {"SSL_CTX_set_next_protos_advertised_cb", TLS_ALPN, NULL},
  2056. {"SSL_CTX_set_timeout", TLS_Mandatory, NULL},
  2057. {NULL, TLS_END_OF_LIST, NULL}};
  2058. /* Similar array as ssl_sw. These functions could be located in different
  2059. * lib. */
  2060. static struct ssl_func crypto_sw[] = {
  2061. {"CRYPTO_num_locks", TLS_Mandatory, NULL},
  2062. {"CRYPTO_set_locking_callback", TLS_Mandatory, NULL},
  2063. {"CRYPTO_set_id_callback", TLS_Mandatory, NULL},
  2064. {"ERR_get_error", TLS_Mandatory, NULL},
  2065. {"ERR_error_string", TLS_Mandatory, NULL},
  2066. {"ERR_remove_state", TLS_Mandatory, NULL},
  2067. {"ERR_free_strings", TLS_Mandatory, NULL},
  2068. {"ENGINE_cleanup", TLS_Mandatory, NULL},
  2069. {"CONF_modules_unload", TLS_Mandatory, NULL},
  2070. {"CRYPTO_cleanup_all_ex_data", TLS_Mandatory, NULL},
  2071. {"EVP_cleanup", TLS_Mandatory, NULL},
  2072. {"X509_free", TLS_Mandatory, NULL},
  2073. {"X509_get_subject_name", TLS_Mandatory, NULL},
  2074. {"X509_get_issuer_name", TLS_Mandatory, NULL},
  2075. {"X509_NAME_oneline", TLS_Mandatory, NULL},
  2076. {"X509_get_serialNumber", TLS_Mandatory, NULL},
  2077. {"i2c_ASN1_INTEGER", TLS_Mandatory, NULL},
  2078. {"EVP_get_digestbyname", TLS_Mandatory, NULL},
  2079. {"EVP_Digest", TLS_Mandatory, NULL},
  2080. {"i2d_X509", TLS_Mandatory, NULL},
  2081. {"BN_bn2hex", TLS_Mandatory, NULL},
  2082. {"ASN1_INTEGER_to_BN", TLS_Mandatory, NULL},
  2083. {"BN_free", TLS_Mandatory, NULL},
  2084. {"CRYPTO_free", TLS_Mandatory, NULL},
  2085. {"ERR_clear_error", TLS_Mandatory, NULL},
  2086. {NULL, TLS_END_OF_LIST, NULL}};
  2087. #endif /* OPENSSL_API_1_1 */
  2088. #endif /* NO_SSL_DL */
  2089. #endif /* NO_SSL */
  2090. #if !defined(NO_CACHING)
  2091. static const char month_names[][4] = {"Jan",
  2092. "Feb",
  2093. "Mar",
  2094. "Apr",
  2095. "May",
  2096. "Jun",
  2097. "Jul",
  2098. "Aug",
  2099. "Sep",
  2100. "Oct",
  2101. "Nov",
  2102. "Dec"};
  2103. #endif /* !NO_CACHING */
  2104. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  2105. * the union u. */
  2106. union usa {
  2107. struct sockaddr sa;
  2108. struct sockaddr_in sin;
  2109. #if defined(USE_IPV6)
  2110. struct sockaddr_in6 sin6;
  2111. #endif
  2112. #if defined(USE_X_DOM_SOCKET)
  2113. struct sockaddr_un sun;
  2114. #endif
  2115. };
  2116. #if defined(USE_X_DOM_SOCKET)
  2117. static unsigned short
  2118. USA_IN_PORT_UNSAFE(union usa *s)
  2119. {
  2120. if (s->sa.sa_family == AF_INET)
  2121. return s->sin.sin_port;
  2122. #if defined(USE_IPV6)
  2123. if (s->sa.sa_family == AF_INET6)
  2124. return s->sin6.sin6_port;
  2125. #endif
  2126. return 0;
  2127. }
  2128. #endif
  2129. #if defined(USE_IPV6)
  2130. #define USA_IN_PORT_UNSAFE(s) \
  2131. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  2132. #else
  2133. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  2134. #endif
  2135. /* Describes a string (chunk of memory). */
  2136. struct vec {
  2137. const char *ptr;
  2138. size_t len;
  2139. };
  2140. struct mg_file_stat {
  2141. /* File properties filled by mg_stat: */
  2142. uint64_t size;
  2143. time_t last_modified;
  2144. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  2145. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  2146. * case we need a "Content-Eencoding: gzip" header */
  2147. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  2148. };
  2149. struct mg_file_access {
  2150. /* File properties filled by mg_fopen: */
  2151. FILE *fp;
  2152. };
  2153. struct mg_file {
  2154. struct mg_file_stat stat;
  2155. struct mg_file_access access;
  2156. };
  2157. #define STRUCT_FILE_INITIALIZER \
  2158. { \
  2159. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  2160. { \
  2161. (FILE *)NULL \
  2162. } \
  2163. }
  2164. /* Describes listening socket, or socket which was accept()-ed by the master
  2165. * thread and queued for future handling by the worker thread. */
  2166. struct socket {
  2167. SOCKET sock; /* Listening socket */
  2168. union usa lsa; /* Local socket address */
  2169. union usa rsa; /* Remote socket address */
  2170. unsigned char is_ssl; /* Is port SSL-ed */
  2171. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  2172. * port */
  2173. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  2174. };
  2175. /* Enum const for all options must be in sync with
  2176. * static struct mg_option config_options[]
  2177. * This is tested in the unit test (test/private.c)
  2178. * "Private Config Options"
  2179. */
  2180. enum {
  2181. /* Once for each server */
  2182. LISTENING_PORTS,
  2183. NUM_THREADS,
  2184. RUN_AS_USER,
  2185. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2186. * socket option typedef TCP_NODELAY. */
  2187. MAX_REQUEST_SIZE,
  2188. LINGER_TIMEOUT,
  2189. CONNECTION_QUEUE_SIZE,
  2190. LISTEN_BACKLOG_SIZE,
  2191. #if defined(__linux__)
  2192. ALLOW_SENDFILE_CALL,
  2193. #endif
  2194. #if defined(_WIN32)
  2195. CASE_SENSITIVE_FILES,
  2196. #endif
  2197. THROTTLE,
  2198. ACCESS_LOG_FILE,
  2199. ERROR_LOG_FILE,
  2200. ENABLE_KEEP_ALIVE,
  2201. REQUEST_TIMEOUT,
  2202. KEEP_ALIVE_TIMEOUT,
  2203. #if defined(USE_WEBSOCKET)
  2204. WEBSOCKET_TIMEOUT,
  2205. ENABLE_WEBSOCKET_PING_PONG,
  2206. #endif
  2207. DECODE_URL,
  2208. #if defined(USE_LUA)
  2209. LUA_BACKGROUND_SCRIPT,
  2210. LUA_BACKGROUND_SCRIPT_PARAMS,
  2211. #endif
  2212. #if defined(USE_HTTP2)
  2213. ENABLE_HTTP2,
  2214. #endif
  2215. /* Once for each domain */
  2216. DOCUMENT_ROOT,
  2217. CGI_EXTENSIONS,
  2218. CGI2_EXTENSIONS,
  2219. CGI_ENVIRONMENT,
  2220. CGI2_ENVIRONMENT,
  2221. CGI_INTERPRETER,
  2222. CGI2_INTERPRETER,
  2223. CGI_INTERPRETER_ARGS,
  2224. CGI2_INTERPRETER_ARGS,
  2225. #if defined(USE_TIMERS)
  2226. CGI_TIMEOUT,
  2227. CGI2_TIMEOUT,
  2228. #endif
  2229. PUT_DELETE_PASSWORDS_FILE,
  2230. PROTECT_URI,
  2231. AUTHENTICATION_DOMAIN,
  2232. ENABLE_AUTH_DOMAIN_CHECK,
  2233. SSI_EXTENSIONS,
  2234. ENABLE_DIRECTORY_LISTING,
  2235. GLOBAL_PASSWORDS_FILE,
  2236. INDEX_FILES,
  2237. ACCESS_CONTROL_LIST,
  2238. EXTRA_MIME_TYPES,
  2239. SSL_CERTIFICATE,
  2240. SSL_CERTIFICATE_CHAIN,
  2241. URL_REWRITE_PATTERN,
  2242. HIDE_FILES,
  2243. SSL_DO_VERIFY_PEER,
  2244. SSL_CACHE_TIMEOUT,
  2245. SSL_CA_PATH,
  2246. SSL_CA_FILE,
  2247. SSL_VERIFY_DEPTH,
  2248. SSL_DEFAULT_VERIFY_PATHS,
  2249. SSL_CIPHER_LIST,
  2250. SSL_PROTOCOL_VERSION,
  2251. SSL_SHORT_TRUST,
  2252. #if defined(USE_LUA)
  2253. LUA_PRELOAD_FILE,
  2254. LUA_SCRIPT_EXTENSIONS,
  2255. LUA_SERVER_PAGE_EXTENSIONS,
  2256. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2257. LUA_DEBUG_PARAMS,
  2258. #endif
  2259. #endif
  2260. #if defined(USE_DUKTAPE)
  2261. DUKTAPE_SCRIPT_EXTENSIONS,
  2262. #endif
  2263. #if defined(USE_WEBSOCKET)
  2264. WEBSOCKET_ROOT,
  2265. #endif
  2266. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2267. LUA_WEBSOCKET_EXTENSIONS,
  2268. #endif
  2269. ACCESS_CONTROL_ALLOW_ORIGIN,
  2270. ACCESS_CONTROL_ALLOW_METHODS,
  2271. ACCESS_CONTROL_ALLOW_HEADERS,
  2272. ERROR_PAGES,
  2273. #if !defined(NO_CACHING)
  2274. STATIC_FILE_MAX_AGE,
  2275. STATIC_FILE_CACHE_CONTROL,
  2276. #endif
  2277. #if !defined(NO_SSL)
  2278. STRICT_HTTPS_MAX_AGE,
  2279. #endif
  2280. ADDITIONAL_HEADER,
  2281. ALLOW_INDEX_SCRIPT_SUB_RES,
  2282. #if defined(DAEMONIZE)
  2283. ENABLE_DAEMONIZE,
  2284. #endif
  2285. NUM_OPTIONS
  2286. };
  2287. /* Config option name, config types, default value.
  2288. * Must be in the same order as the enum const above.
  2289. */
  2290. static const struct mg_option config_options[] = {
  2291. /* Once for each server */
  2292. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2293. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2294. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2295. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2296. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2297. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2298. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  2299. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  2300. #if defined(__linux__)
  2301. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2302. #endif
  2303. #if defined(_WIN32)
  2304. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2305. #endif
  2306. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2307. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2308. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2309. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2310. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2311. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2312. #if defined(USE_WEBSOCKET)
  2313. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2314. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2315. #endif
  2316. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2317. #if defined(USE_LUA)
  2318. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2319. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2320. #endif
  2321. #if defined(USE_HTTP2)
  2322. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2323. #endif
  2324. /* Once for each domain */
  2325. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2326. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2327. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2328. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2329. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2330. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2331. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2332. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2333. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  2334. #if defined(USE_TIMERS)
  2335. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2336. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2337. #endif
  2338. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2339. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2340. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2341. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2342. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2343. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2344. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2345. {"index_files",
  2346. MG_CONFIG_TYPE_STRING_LIST,
  2347. #if defined(USE_LUA)
  2348. "index.xhtml,index.html,index.htm,"
  2349. "index.lp,index.lsp,index.lua,index.cgi,"
  2350. "index.shtml,index.php"},
  2351. #else
  2352. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2353. #endif
  2354. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2355. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2356. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2357. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2358. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2359. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2360. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2361. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  2362. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2363. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2364. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2365. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2366. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2367. #if defined(USE_HTTP2)
  2368. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  2369. * as a minimum in 2020 */
  2370. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  2371. #else
  2372. /* Keep the default (compatibility) */
  2373. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2374. #endif /* defined(USE_HTTP2) */
  2375. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2376. #if defined(USE_LUA)
  2377. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2378. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2379. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2380. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2381. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2382. #endif
  2383. #endif
  2384. #if defined(USE_DUKTAPE)
  2385. /* The support for duktape is still in alpha version state.
  2386. * The name of this config option might change. */
  2387. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2388. #endif
  2389. #if defined(USE_WEBSOCKET)
  2390. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2391. #endif
  2392. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2393. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2394. #endif
  2395. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2396. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2397. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2398. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2399. #if !defined(NO_CACHING)
  2400. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2401. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2402. #endif
  2403. #if !defined(NO_SSL)
  2404. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2405. #endif
  2406. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2407. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2408. #if defined(DAEMONIZE)
  2409. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2410. #endif
  2411. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2412. /* Check if the config_options and the corresponding enum have compatible
  2413. * sizes. */
  2414. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2415. == (NUM_OPTIONS + 1),
  2416. "config_options and enum not sync");
  2417. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2418. struct mg_handler_info {
  2419. /* Name/Pattern of the URI. */
  2420. char *uri;
  2421. size_t uri_len;
  2422. /* handler type */
  2423. int handler_type;
  2424. /* Handler for http/https or authorization requests. */
  2425. mg_request_handler handler;
  2426. unsigned int refcount;
  2427. int removing;
  2428. /* Handler for ws/wss (websocket) requests. */
  2429. mg_websocket_connect_handler connect_handler;
  2430. mg_websocket_ready_handler ready_handler;
  2431. mg_websocket_data_handler data_handler;
  2432. mg_websocket_close_handler close_handler;
  2433. /* accepted subprotocols for ws/wss requests. */
  2434. struct mg_websocket_subprotocols *subprotocols;
  2435. /* Handler for authorization requests */
  2436. mg_authorization_handler auth_handler;
  2437. /* User supplied argument for the handler function. */
  2438. void *cbdata;
  2439. /* next handler in a linked list */
  2440. struct mg_handler_info *next;
  2441. };
  2442. enum {
  2443. CONTEXT_INVALID,
  2444. CONTEXT_SERVER,
  2445. CONTEXT_HTTP_CLIENT,
  2446. CONTEXT_WS_CLIENT
  2447. };
  2448. struct mg_domain_context {
  2449. SSL_CTX *ssl_ctx; /* SSL context */
  2450. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2451. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2452. int64_t ssl_cert_last_mtime;
  2453. /* Server nonce */
  2454. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2455. unsigned long nonce_count; /* Used nonces, used for authentication */
  2456. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2457. /* linked list of shared lua websockets */
  2458. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2459. #endif
  2460. /* Linked list of domains */
  2461. struct mg_domain_context *next;
  2462. };
  2463. /* Stop flag can be "volatile" or require a lock.
  2464. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  2465. * states a read operation for int is always atomic. */
  2466. #if defined(STOP_FLAG_NEEDS_LOCK)
  2467. typedef ptrdiff_t volatile stop_flag_t;
  2468. static int
  2469. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  2470. {
  2471. stop_flag_t sf = mg_atomic_add(f, 0);
  2472. return (sf == 0);
  2473. }
  2474. static int
  2475. STOP_FLAG_IS_TWO(stop_flag_t *f)
  2476. {
  2477. stop_flag_t sf = mg_atomic_add(f, 0);
  2478. return (sf == 2);
  2479. }
  2480. static void
  2481. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2482. {
  2483. stop_flag_t sf;
  2484. do {
  2485. sf = mg_atomic_compare_and_swap(f, *f, v);
  2486. } while (sf != v);
  2487. }
  2488. #else /* STOP_FLAG_NEEDS_LOCK */
  2489. typedef int volatile stop_flag_t;
  2490. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2491. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2492. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2493. #endif /* STOP_FLAG_NEEDS_LOCK */
  2494. struct mg_context {
  2495. /* Part 1 - Physical context:
  2496. * This holds threads, ports, timeouts, ...
  2497. * set for the entire server, independent from the
  2498. * addressed hostname.
  2499. */
  2500. /* Connection related */
  2501. int context_type; /* See CONTEXT_* above */
  2502. struct socket *listening_sockets;
  2503. struct mg_pollfd *listening_socket_fds;
  2504. unsigned int num_listening_sockets;
  2505. struct mg_connection *worker_connections; /* The connection struct, pre-
  2506. * allocated for each worker */
  2507. #if defined(USE_SERVER_STATS)
  2508. volatile ptrdiff_t active_connections;
  2509. volatile ptrdiff_t max_active_connections;
  2510. volatile ptrdiff_t total_connections;
  2511. volatile ptrdiff_t total_requests;
  2512. volatile int64_t total_data_read;
  2513. volatile int64_t total_data_written;
  2514. #endif
  2515. /* Thread related */
  2516. stop_flag_t stop_flag; /* Should we stop event loop */
  2517. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2518. pthread_t masterthreadid; /* The master thread ID */
  2519. unsigned int
  2520. cfg_worker_threads; /* The number of configured worker threads. */
  2521. pthread_t *worker_threadids; /* The worker thread IDs */
  2522. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2523. /* Connection to thread dispatching */
  2524. #if defined(ALTERNATIVE_QUEUE)
  2525. struct socket *client_socks;
  2526. void **client_wait_events;
  2527. #else
  2528. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2529. worker thread */
  2530. volatile int sq_head; /* Head of the socket queue */
  2531. volatile int sq_tail; /* Tail of the socket queue */
  2532. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2533. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2534. volatile int sq_blocked; /* Status information: sq is full */
  2535. int sq_size; /* No of elements in socket queue */
  2536. #if defined(USE_SERVER_STATS)
  2537. int sq_max_fill;
  2538. #endif /* USE_SERVER_STATS */
  2539. #endif /* ALTERNATIVE_QUEUE */
  2540. /* Memory related */
  2541. unsigned int max_request_size; /* The max request size */
  2542. #if defined(USE_SERVER_STATS)
  2543. struct mg_memory_stat ctx_memory;
  2544. #endif
  2545. /* Operating system related */
  2546. char *systemName; /* What operating system is running */
  2547. time_t start_time; /* Server start time, used for authentication
  2548. * and for diagnstics. */
  2549. #if defined(USE_TIMERS)
  2550. struct ttimers *timers;
  2551. #endif
  2552. /* Lua specific: Background operations and shared websockets */
  2553. #if defined(USE_LUA)
  2554. void *lua_background_state;
  2555. #endif
  2556. /* Server nonce */
  2557. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2558. * ssl_cert_last_mtime, nonce_count, and
  2559. * next (linked list) */
  2560. /* Server callbacks */
  2561. struct mg_callbacks callbacks; /* User-defined callback function */
  2562. void *user_data; /* User-defined data */
  2563. /* Part 2 - Logical domain:
  2564. * This holds hostname, TLS certificate, document root, ...
  2565. * set for a domain hosted at the server.
  2566. * There may be multiple domains hosted at one physical server.
  2567. * The default domain "dd" is the first element of a list of
  2568. * domains.
  2569. */
  2570. struct mg_domain_context dd; /* default domain */
  2571. };
  2572. #if defined(USE_SERVER_STATS)
  2573. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2574. static struct mg_memory_stat *
  2575. get_memory_stat(struct mg_context *ctx)
  2576. {
  2577. if (ctx) {
  2578. return &(ctx->ctx_memory);
  2579. }
  2580. return &mg_common_memory;
  2581. }
  2582. #endif
  2583. enum {
  2584. CONNECTION_TYPE_INVALID = 0,
  2585. CONNECTION_TYPE_REQUEST = 1,
  2586. CONNECTION_TYPE_RESPONSE = 2
  2587. };
  2588. enum {
  2589. PROTOCOL_TYPE_HTTP1 = 0,
  2590. PROTOCOL_TYPE_WEBSOCKET = 1,
  2591. PROTOCOL_TYPE_HTTP2 = 2
  2592. };
  2593. #if defined(USE_HTTP2)
  2594. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2595. #define HTTP2_DYN_TABLE_SIZE (256)
  2596. #endif
  2597. struct mg_http2_connection {
  2598. uint32_t stream_id;
  2599. uint32_t dyn_table_size;
  2600. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2601. };
  2602. #endif
  2603. struct mg_connection {
  2604. int connection_type; /* see CONNECTION_TYPE_* above */
  2605. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2606. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2607. fully sent */
  2608. #if defined(USE_HTTP2)
  2609. struct mg_http2_connection http2;
  2610. #endif
  2611. struct mg_request_info request_info;
  2612. struct mg_response_info response_info;
  2613. struct mg_context *phys_ctx;
  2614. struct mg_domain_context *dom_ctx;
  2615. #if defined(USE_SERVER_STATS)
  2616. int conn_state; /* 0 = undef, numerical value may change in different
  2617. * versions. For the current definition, see
  2618. * mg_get_connection_info_impl */
  2619. #endif
  2620. SSL *ssl; /* SSL descriptor */
  2621. struct socket client; /* Connected client */
  2622. time_t conn_birth_time; /* Time (wall clock) when connection was
  2623. * established */
  2624. #if defined(USE_SERVER_STATS)
  2625. time_t conn_close_time; /* Time (wall clock) when connection was
  2626. * closed (or 0 if still open) */
  2627. #endif
  2628. struct timespec req_time; /* Time (since system start) when the request
  2629. * was received */
  2630. int64_t num_bytes_sent; /* Total bytes sent to client */
  2631. int64_t content_len; /* How many bytes of content can be read
  2632. * !is_chunked: Content-Length header value
  2633. * or -1 (until connection closed,
  2634. * not allowed for a request)
  2635. * is_chunked: >= 0, appended gradually
  2636. */
  2637. int64_t consumed_content; /* How many bytes of content have been read */
  2638. int is_chunked; /* Transfer-Encoding is chunked:
  2639. * 0 = not chunked,
  2640. * 1 = chunked, not yet, or some data read,
  2641. * 2 = chunked, has error,
  2642. * 3 = chunked, all data read except trailer,
  2643. * 4 = chunked, all data read
  2644. */
  2645. char *buf; /* Buffer for received data */
  2646. char *path_info; /* PATH_INFO part of the URL */
  2647. int must_close; /* 1 if connection must be closed */
  2648. int accept_gzip; /* 1 if gzip encoding is accepted */
  2649. int in_error_handler; /* 1 if in handler for user defined error
  2650. * pages */
  2651. #if defined(USE_WEBSOCKET)
  2652. int in_websocket_handling; /* 1 if in read_websocket */
  2653. #endif
  2654. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2655. && defined(MG_EXPERIMENTAL_INTERFACES)
  2656. /* Parameters for websocket data compression according to rfc7692 */
  2657. int websocket_deflate_server_max_windows_bits;
  2658. int websocket_deflate_client_max_windows_bits;
  2659. int websocket_deflate_server_no_context_takeover;
  2660. int websocket_deflate_client_no_context_takeover;
  2661. int websocket_deflate_initialized;
  2662. int websocket_deflate_flush;
  2663. z_stream websocket_deflate_state;
  2664. z_stream websocket_inflate_state;
  2665. #endif
  2666. int handled_requests; /* Number of requests handled by this connection
  2667. */
  2668. int buf_size; /* Buffer size */
  2669. int request_len; /* Size of the request + headers in a buffer */
  2670. int data_len; /* Total size of data in a buffer */
  2671. int status_code; /* HTTP reply status code, e.g. 200 */
  2672. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2673. * throttle */
  2674. time_t last_throttle_time; /* Last time throttled data was sent */
  2675. int last_throttle_bytes; /* Bytes sent this second */
  2676. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2677. * atomic transmissions for websockets */
  2678. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2679. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2680. #endif
  2681. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2682. * for quick access */
  2683. };
  2684. /* Directory entry */
  2685. struct de {
  2686. struct mg_connection *conn;
  2687. char *file_name;
  2688. struct mg_file_stat file;
  2689. };
  2690. #define mg_cry_internal(conn, fmt, ...) \
  2691. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2692. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2693. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2694. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2695. struct mg_context *ctx,
  2696. const char *func,
  2697. unsigned line,
  2698. const char *fmt,
  2699. ...) PRINTF_ARGS(5, 6);
  2700. #if !defined(NO_THREAD_NAME)
  2701. #if defined(_WIN32) && defined(_MSC_VER)
  2702. /* Set the thread name for debugging purposes in Visual Studio
  2703. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2704. */
  2705. #pragma pack(push, 8)
  2706. typedef struct tagTHREADNAME_INFO {
  2707. DWORD dwType; /* Must be 0x1000. */
  2708. LPCSTR szName; /* Pointer to name (in user addr space). */
  2709. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2710. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2711. } THREADNAME_INFO;
  2712. #pragma pack(pop)
  2713. #elif defined(__linux__)
  2714. #include <sys/prctl.h>
  2715. #include <sys/sendfile.h>
  2716. #if defined(ALTERNATIVE_QUEUE)
  2717. #include <sys/eventfd.h>
  2718. #endif /* ALTERNATIVE_QUEUE */
  2719. #if defined(ALTERNATIVE_QUEUE)
  2720. static void *
  2721. event_create(void)
  2722. {
  2723. int evhdl = eventfd(0, EFD_CLOEXEC);
  2724. int *ret;
  2725. if (evhdl == -1) {
  2726. /* Linux uses -1 on error, Windows NULL. */
  2727. /* However, Linux does not return 0 on success either. */
  2728. return 0;
  2729. }
  2730. ret = (int *)mg_malloc(sizeof(int));
  2731. if (ret) {
  2732. *ret = evhdl;
  2733. } else {
  2734. (void)close(evhdl);
  2735. }
  2736. return (void *)ret;
  2737. }
  2738. static int
  2739. event_wait(void *eventhdl)
  2740. {
  2741. uint64_t u;
  2742. int evhdl, s;
  2743. if (!eventhdl) {
  2744. /* error */
  2745. return 0;
  2746. }
  2747. evhdl = *(int *)eventhdl;
  2748. s = (int)read(evhdl, &u, sizeof(u));
  2749. if (s != sizeof(u)) {
  2750. /* error */
  2751. return 0;
  2752. }
  2753. (void)u; /* the value is not required */
  2754. return 1;
  2755. }
  2756. static int
  2757. event_signal(void *eventhdl)
  2758. {
  2759. uint64_t u = 1;
  2760. int evhdl, s;
  2761. if (!eventhdl) {
  2762. /* error */
  2763. return 0;
  2764. }
  2765. evhdl = *(int *)eventhdl;
  2766. s = (int)write(evhdl, &u, sizeof(u));
  2767. if (s != sizeof(u)) {
  2768. /* error */
  2769. return 0;
  2770. }
  2771. return 1;
  2772. }
  2773. static void
  2774. event_destroy(void *eventhdl)
  2775. {
  2776. int evhdl;
  2777. if (!eventhdl) {
  2778. /* error */
  2779. return;
  2780. }
  2781. evhdl = *(int *)eventhdl;
  2782. close(evhdl);
  2783. mg_free(eventhdl);
  2784. }
  2785. #endif
  2786. #endif
  2787. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2788. struct posix_event {
  2789. pthread_mutex_t mutex;
  2790. pthread_cond_t cond;
  2791. int signaled;
  2792. };
  2793. static void *
  2794. event_create(void)
  2795. {
  2796. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2797. if (ret == 0) {
  2798. /* out of memory */
  2799. return 0;
  2800. }
  2801. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2802. /* pthread mutex not available */
  2803. mg_free(ret);
  2804. return 0;
  2805. }
  2806. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2807. /* pthread cond not available */
  2808. pthread_mutex_destroy(&(ret->mutex));
  2809. mg_free(ret);
  2810. return 0;
  2811. }
  2812. ret->signaled = 0;
  2813. return (void *)ret;
  2814. }
  2815. static int
  2816. event_wait(void *eventhdl)
  2817. {
  2818. struct posix_event *ev = (struct posix_event *)eventhdl;
  2819. pthread_mutex_lock(&(ev->mutex));
  2820. while (!ev->signaled) {
  2821. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2822. }
  2823. ev->signaled = 0;
  2824. pthread_mutex_unlock(&(ev->mutex));
  2825. return 1;
  2826. }
  2827. static int
  2828. event_signal(void *eventhdl)
  2829. {
  2830. struct posix_event *ev = (struct posix_event *)eventhdl;
  2831. pthread_mutex_lock(&(ev->mutex));
  2832. pthread_cond_signal(&(ev->cond));
  2833. ev->signaled = 1;
  2834. pthread_mutex_unlock(&(ev->mutex));
  2835. return 1;
  2836. }
  2837. static void
  2838. event_destroy(void *eventhdl)
  2839. {
  2840. struct posix_event *ev = (struct posix_event *)eventhdl;
  2841. pthread_cond_destroy(&(ev->cond));
  2842. pthread_mutex_destroy(&(ev->mutex));
  2843. mg_free(ev);
  2844. }
  2845. #endif
  2846. static void
  2847. mg_set_thread_name(const char *name)
  2848. {
  2849. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2850. mg_snprintf(
  2851. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2852. #if defined(_WIN32)
  2853. #if defined(_MSC_VER)
  2854. /* Windows and Visual Studio Compiler */
  2855. __try {
  2856. THREADNAME_INFO info;
  2857. info.dwType = 0x1000;
  2858. info.szName = threadName;
  2859. info.dwThreadID = ~0U;
  2860. info.dwFlags = 0;
  2861. RaiseException(0x406D1388,
  2862. 0,
  2863. sizeof(info) / sizeof(ULONG_PTR),
  2864. (ULONG_PTR *)&info);
  2865. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2866. }
  2867. #elif defined(__MINGW32__)
  2868. /* No option known to set thread name for MinGW known */
  2869. #endif
  2870. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2871. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2872. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2873. #if defined(__MACH__)
  2874. /* OS X only current thread name can be changed */
  2875. (void)pthread_setname_np(threadName);
  2876. #else
  2877. (void)pthread_setname_np(pthread_self(), threadName);
  2878. #endif
  2879. #elif defined(__linux__)
  2880. /* On Linux we can use the prctl function.
  2881. * When building for Linux Standard Base (LSB) use
  2882. * NO_THREAD_NAME. However, thread names are a big
  2883. * help for debugging, so the stadard is to set them.
  2884. */
  2885. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2886. #endif
  2887. }
  2888. #else /* !defined(NO_THREAD_NAME) */
  2889. void
  2890. mg_set_thread_name(const char *threadName)
  2891. {
  2892. }
  2893. #endif
  2894. const struct mg_option *
  2895. mg_get_valid_options(void)
  2896. {
  2897. return config_options;
  2898. }
  2899. /* Do not open file (unused) */
  2900. #define MG_FOPEN_MODE_NONE (0)
  2901. /* Open file for read only access */
  2902. #define MG_FOPEN_MODE_READ (1)
  2903. /* Open file for writing, create and overwrite */
  2904. #define MG_FOPEN_MODE_WRITE (2)
  2905. /* Open file for writing, create and append */
  2906. #define MG_FOPEN_MODE_APPEND (4)
  2907. static int
  2908. is_file_opened(const struct mg_file_access *fileacc)
  2909. {
  2910. if (!fileacc) {
  2911. return 0;
  2912. }
  2913. return (fileacc->fp != NULL);
  2914. }
  2915. #if !defined(NO_FILESYSTEMS)
  2916. static int mg_stat(const struct mg_connection *conn,
  2917. const char *path,
  2918. struct mg_file_stat *filep);
  2919. /* Reject files with special characters */
  2920. static int
  2921. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2922. {
  2923. const uint8_t *c = (const uint8_t *)path;
  2924. (void)conn; /* not used */
  2925. if ((c == NULL) || (c[0] == 0)) {
  2926. /* Null pointer or empty path --> suspicious */
  2927. return 1;
  2928. }
  2929. while (*c) {
  2930. if (*c <= 32) {
  2931. /* Control character or space */
  2932. return 0;
  2933. }
  2934. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2935. /* stdin/stdout redirection character */
  2936. return 0;
  2937. }
  2938. #if defined(_WIN32)
  2939. if (*c == '\\') {
  2940. /* Windows backslash */
  2941. return 0;
  2942. }
  2943. #else
  2944. if (*c == '&') {
  2945. /* Linux ampersand */
  2946. return 0;
  2947. }
  2948. #endif
  2949. c++;
  2950. }
  2951. /* Nothing suspicious found */
  2952. return 0;
  2953. }
  2954. /* mg_fopen will open a file either in memory or on the disk.
  2955. * The input parameter path is a string in UTF-8 encoding.
  2956. * The input parameter mode is MG_FOPEN_MODE_*
  2957. * On success, fp will be set in the output struct mg_file.
  2958. * All status members will also be set.
  2959. * The function returns 1 on success, 0 on error. */
  2960. static int
  2961. mg_fopen(const struct mg_connection *conn,
  2962. const char *path,
  2963. int mode,
  2964. struct mg_file *filep)
  2965. {
  2966. int found;
  2967. if (!filep) {
  2968. return 0;
  2969. }
  2970. filep->access.fp = NULL;
  2971. if (mg_path_suspicious(conn, path)) {
  2972. return 0;
  2973. }
  2974. /* filep is initialized in mg_stat: all fields with memset to,
  2975. * some fields like size and modification date with values */
  2976. found = mg_stat(conn, path, &(filep->stat));
  2977. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2978. /* file does not exist and will not be created */
  2979. return 0;
  2980. }
  2981. #if defined(_WIN32)
  2982. {
  2983. wchar_t wbuf[W_PATH_MAX];
  2984. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2985. switch (mode) {
  2986. case MG_FOPEN_MODE_READ:
  2987. filep->access.fp = _wfopen(wbuf, L"rb");
  2988. break;
  2989. case MG_FOPEN_MODE_WRITE:
  2990. filep->access.fp = _wfopen(wbuf, L"wb");
  2991. break;
  2992. case MG_FOPEN_MODE_APPEND:
  2993. filep->access.fp = _wfopen(wbuf, L"ab");
  2994. break;
  2995. }
  2996. }
  2997. #else
  2998. /* Linux et al already use unicode. No need to convert. */
  2999. switch (mode) {
  3000. case MG_FOPEN_MODE_READ:
  3001. filep->access.fp = fopen(path, "r");
  3002. break;
  3003. case MG_FOPEN_MODE_WRITE:
  3004. filep->access.fp = fopen(path, "w");
  3005. break;
  3006. case MG_FOPEN_MODE_APPEND:
  3007. filep->access.fp = fopen(path, "a");
  3008. break;
  3009. }
  3010. #endif
  3011. if (!found) {
  3012. /* File did not exist before fopen was called.
  3013. * Maybe it has been created now. Get stat info
  3014. * like creation time now. */
  3015. found = mg_stat(conn, path, &(filep->stat));
  3016. (void)found;
  3017. }
  3018. /* return OK if file is opened */
  3019. return (filep->access.fp != NULL);
  3020. }
  3021. /* return 0 on success, just like fclose */
  3022. static int
  3023. mg_fclose(struct mg_file_access *fileacc)
  3024. {
  3025. int ret = -1;
  3026. if (fileacc != NULL) {
  3027. if (fileacc->fp != NULL) {
  3028. ret = fclose(fileacc->fp);
  3029. }
  3030. /* reset all members of fileacc */
  3031. memset(fileacc, 0, sizeof(*fileacc));
  3032. }
  3033. return ret;
  3034. }
  3035. #endif /* NO_FILESYSTEMS */
  3036. static void
  3037. mg_strlcpy(register char *dst, register const char *src, size_t n)
  3038. {
  3039. for (; *src != '\0' && n > 1; n--) {
  3040. *dst++ = *src++;
  3041. }
  3042. *dst = '\0';
  3043. }
  3044. static int
  3045. lowercase(const char *s)
  3046. {
  3047. return tolower((unsigned char)*s);
  3048. }
  3049. int
  3050. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  3051. {
  3052. int diff = 0;
  3053. if (len > 0) {
  3054. do {
  3055. diff = lowercase(s1++) - lowercase(s2++);
  3056. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  3057. }
  3058. return diff;
  3059. }
  3060. int
  3061. mg_strcasecmp(const char *s1, const char *s2)
  3062. {
  3063. int diff;
  3064. do {
  3065. diff = lowercase(s1++) - lowercase(s2++);
  3066. } while (diff == 0 && s1[-1] != '\0');
  3067. return diff;
  3068. }
  3069. static char *
  3070. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  3071. {
  3072. char *p;
  3073. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  3074. * defined */
  3075. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  3076. mg_strlcpy(p, ptr, len + 1);
  3077. }
  3078. return p;
  3079. }
  3080. static char *
  3081. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  3082. {
  3083. return mg_strndup_ctx(str, strlen(str), ctx);
  3084. }
  3085. static char *
  3086. mg_strdup(const char *str)
  3087. {
  3088. return mg_strndup_ctx(str, strlen(str), NULL);
  3089. }
  3090. static const char *
  3091. mg_strcasestr(const char *big_str, const char *small_str)
  3092. {
  3093. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  3094. if (big_len >= small_len) {
  3095. for (i = 0; i <= (big_len - small_len); i++) {
  3096. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  3097. return big_str + i;
  3098. }
  3099. }
  3100. }
  3101. return NULL;
  3102. }
  3103. /* Return null terminated string of given maximum length.
  3104. * Report errors if length is exceeded. */
  3105. static void
  3106. mg_vsnprintf(const struct mg_connection *conn,
  3107. int *truncated,
  3108. char *buf,
  3109. size_t buflen,
  3110. const char *fmt,
  3111. va_list ap)
  3112. {
  3113. int n, ok;
  3114. if (buflen == 0) {
  3115. if (truncated) {
  3116. *truncated = 1;
  3117. }
  3118. return;
  3119. }
  3120. #if defined(__clang__)
  3121. #pragma clang diagnostic push
  3122. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  3123. /* Using fmt as a non-literal is intended here, since it is mostly called
  3124. * indirectly by mg_snprintf */
  3125. #endif
  3126. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  3127. ok = (n >= 0) && ((size_t)n < buflen);
  3128. #if defined(__clang__)
  3129. #pragma clang diagnostic pop
  3130. #endif
  3131. if (ok) {
  3132. if (truncated) {
  3133. *truncated = 0;
  3134. }
  3135. } else {
  3136. if (truncated) {
  3137. *truncated = 1;
  3138. }
  3139. mg_cry_internal(conn,
  3140. "truncating vsnprintf buffer: [%.*s]",
  3141. (int)((buflen > 200) ? 200 : (buflen - 1)),
  3142. buf);
  3143. n = (int)buflen - 1;
  3144. }
  3145. buf[n] = '\0';
  3146. }
  3147. static void
  3148. mg_snprintf(const struct mg_connection *conn,
  3149. int *truncated,
  3150. char *buf,
  3151. size_t buflen,
  3152. const char *fmt,
  3153. ...)
  3154. {
  3155. va_list ap;
  3156. va_start(ap, fmt);
  3157. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  3158. va_end(ap);
  3159. }
  3160. static int
  3161. get_option_index(const char *name)
  3162. {
  3163. int i;
  3164. for (i = 0; config_options[i].name != NULL; i++) {
  3165. if (strcmp(config_options[i].name, name) == 0) {
  3166. return i;
  3167. }
  3168. }
  3169. return -1;
  3170. }
  3171. const char *
  3172. mg_get_option(const struct mg_context *ctx, const char *name)
  3173. {
  3174. int i;
  3175. if ((i = get_option_index(name)) == -1) {
  3176. return NULL;
  3177. } else if (!ctx || ctx->dd.config[i] == NULL) {
  3178. return "";
  3179. } else {
  3180. return ctx->dd.config[i];
  3181. }
  3182. }
  3183. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  3184. struct mg_context *
  3185. mg_get_context(const struct mg_connection *conn)
  3186. {
  3187. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  3188. }
  3189. void *
  3190. mg_get_user_data(const struct mg_context *ctx)
  3191. {
  3192. return (ctx == NULL) ? NULL : ctx->user_data;
  3193. }
  3194. void *
  3195. mg_get_user_context_data(const struct mg_connection *conn)
  3196. {
  3197. return mg_get_user_data(mg_get_context(conn));
  3198. }
  3199. void *
  3200. mg_get_thread_pointer(const struct mg_connection *conn)
  3201. {
  3202. /* both methods should return the same pointer */
  3203. if (conn) {
  3204. /* quick access, in case conn is known */
  3205. return conn->tls_user_ptr;
  3206. } else {
  3207. /* otherwise get pointer from thread local storage (TLS) */
  3208. struct mg_workerTLS *tls =
  3209. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3210. return tls->user_ptr;
  3211. }
  3212. }
  3213. void
  3214. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  3215. {
  3216. if (const_conn != NULL) {
  3217. /* Const cast, since "const struct mg_connection *" does not mean
  3218. * the connection object is not modified. Here "const" is used,
  3219. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  3220. struct mg_connection *conn = (struct mg_connection *)const_conn;
  3221. conn->request_info.conn_data = data;
  3222. }
  3223. }
  3224. void *
  3225. mg_get_user_connection_data(const struct mg_connection *conn)
  3226. {
  3227. if (conn != NULL) {
  3228. return conn->request_info.conn_data;
  3229. }
  3230. return NULL;
  3231. }
  3232. #if defined(MG_LEGACY_INTERFACE)
  3233. /* Deprecated: Use mg_get_server_ports instead. */
  3234. size_t
  3235. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3236. {
  3237. size_t i;
  3238. if (!ctx) {
  3239. return 0;
  3240. }
  3241. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3242. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3243. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3244. }
  3245. return i;
  3246. }
  3247. #endif
  3248. int
  3249. mg_get_server_ports(const struct mg_context *ctx,
  3250. int size,
  3251. struct mg_server_port *ports)
  3252. {
  3253. int i, cnt = 0;
  3254. if (size <= 0) {
  3255. return -1;
  3256. }
  3257. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3258. if (!ctx) {
  3259. return -1;
  3260. }
  3261. if (!ctx->listening_sockets) {
  3262. return -1;
  3263. }
  3264. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3265. ports[cnt].port =
  3266. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  3267. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3268. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3269. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3270. /* IPv4 */
  3271. ports[cnt].protocol = 1;
  3272. cnt++;
  3273. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3274. /* IPv6 */
  3275. ports[cnt].protocol = 3;
  3276. cnt++;
  3277. }
  3278. }
  3279. return cnt;
  3280. }
  3281. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  3282. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  3283. #endif
  3284. static void
  3285. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3286. {
  3287. buf[0] = '\0';
  3288. if (!usa) {
  3289. return;
  3290. }
  3291. if (usa->sa.sa_family == AF_INET) {
  3292. getnameinfo(&usa->sa,
  3293. sizeof(usa->sin),
  3294. buf,
  3295. (unsigned)len,
  3296. NULL,
  3297. 0,
  3298. NI_NUMERICHOST);
  3299. }
  3300. #if defined(USE_IPV6)
  3301. else if (usa->sa.sa_family == AF_INET6) {
  3302. getnameinfo(&usa->sa,
  3303. sizeof(usa->sin6),
  3304. buf,
  3305. (unsigned)len,
  3306. NULL,
  3307. 0,
  3308. NI_NUMERICHOST);
  3309. }
  3310. #endif
  3311. #if defined(USE_X_DOM_SOCKET)
  3312. else if (usa->sa.sa_family == AF_UNIX) {
  3313. /* TODO: Define a remote address for unix domain sockets.
  3314. * This code will always return "localhost", identical to http+tcp:
  3315. getnameinfo(&usa->sa,
  3316. sizeof(usa->sun),
  3317. buf,
  3318. (unsigned)len,
  3319. NULL,
  3320. 0,
  3321. NI_NUMERICHOST);
  3322. */
  3323. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  3324. buf[len] = 0;
  3325. }
  3326. #endif
  3327. }
  3328. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3329. * included in all responses other than 100, 101, 5xx. */
  3330. static void
  3331. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3332. {
  3333. #if !defined(REENTRANT_TIME)
  3334. struct tm *tm;
  3335. tm = ((t != NULL) ? gmtime(t) : NULL);
  3336. if (tm != NULL) {
  3337. #else
  3338. struct tm _tm;
  3339. struct tm *tm = &_tm;
  3340. if (t != NULL) {
  3341. gmtime_r(t, tm);
  3342. #endif
  3343. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3344. } else {
  3345. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3346. buf[buf_len - 1] = '\0';
  3347. }
  3348. }
  3349. /* difftime for struct timespec. Return value is in seconds. */
  3350. static double
  3351. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3352. {
  3353. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3354. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3355. }
  3356. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3357. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3358. const char *func,
  3359. unsigned line,
  3360. const char *fmt,
  3361. va_list ap);
  3362. #include "external_mg_cry_internal_impl.inl"
  3363. #elif !defined(NO_FILESYSTEMS)
  3364. /* Print error message to the opened error log stream. */
  3365. static void
  3366. mg_cry_internal_impl(const struct mg_connection *conn,
  3367. const char *func,
  3368. unsigned line,
  3369. const char *fmt,
  3370. va_list ap)
  3371. {
  3372. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3373. struct mg_file fi;
  3374. time_t timestamp;
  3375. /* Unused, in the RELEASE build */
  3376. (void)func;
  3377. (void)line;
  3378. #if defined(GCC_DIAGNOSTIC)
  3379. #pragma GCC diagnostic push
  3380. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3381. #endif
  3382. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3383. #if defined(GCC_DIAGNOSTIC)
  3384. #pragma GCC diagnostic pop
  3385. #endif
  3386. buf[sizeof(buf) - 1] = 0;
  3387. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3388. if (!conn) {
  3389. puts(buf);
  3390. return;
  3391. }
  3392. /* Do not lock when getting the callback value, here and below.
  3393. * I suppose this is fine, since function cannot disappear in the
  3394. * same way string option can. */
  3395. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3396. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3397. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3398. if (mg_fopen(conn,
  3399. conn->dom_ctx->config[ERROR_LOG_FILE],
  3400. MG_FOPEN_MODE_APPEND,
  3401. &fi)
  3402. == 0) {
  3403. fi.access.fp = NULL;
  3404. }
  3405. } else {
  3406. fi.access.fp = NULL;
  3407. }
  3408. if (fi.access.fp != NULL) {
  3409. flockfile(fi.access.fp);
  3410. timestamp = time(NULL);
  3411. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3412. fprintf(fi.access.fp,
  3413. "[%010lu] [error] [client %s] ",
  3414. (unsigned long)timestamp,
  3415. src_addr);
  3416. if (conn->request_info.request_method != NULL) {
  3417. fprintf(fi.access.fp,
  3418. "%s %s: ",
  3419. conn->request_info.request_method,
  3420. conn->request_info.request_uri
  3421. ? conn->request_info.request_uri
  3422. : "");
  3423. }
  3424. fprintf(fi.access.fp, "%s", buf);
  3425. fputc('\n', fi.access.fp);
  3426. fflush(fi.access.fp);
  3427. funlockfile(fi.access.fp);
  3428. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3429. * mg_cry here anyway ;-) */
  3430. }
  3431. }
  3432. }
  3433. #else
  3434. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3435. #endif /* Externally provided function */
  3436. /* Construct fake connection structure. Used for logging, if connection
  3437. * is not applicable at the moment of logging. */
  3438. static struct mg_connection *
  3439. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3440. {
  3441. static const struct mg_connection conn_zero = {0};
  3442. *fc = conn_zero;
  3443. fc->phys_ctx = ctx;
  3444. fc->dom_ctx = &(ctx->dd);
  3445. return fc;
  3446. }
  3447. static void
  3448. mg_cry_internal_wrap(const struct mg_connection *conn,
  3449. struct mg_context *ctx,
  3450. const char *func,
  3451. unsigned line,
  3452. const char *fmt,
  3453. ...)
  3454. {
  3455. va_list ap;
  3456. va_start(ap, fmt);
  3457. if (!conn && ctx) {
  3458. struct mg_connection fc;
  3459. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3460. } else {
  3461. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3462. }
  3463. va_end(ap);
  3464. }
  3465. void
  3466. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3467. {
  3468. va_list ap;
  3469. va_start(ap, fmt);
  3470. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3471. va_end(ap);
  3472. }
  3473. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3474. const char *
  3475. mg_version(void)
  3476. {
  3477. return CIVETWEB_VERSION;
  3478. }
  3479. const struct mg_request_info *
  3480. mg_get_request_info(const struct mg_connection *conn)
  3481. {
  3482. if (!conn) {
  3483. return NULL;
  3484. }
  3485. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3486. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3487. char txt[16];
  3488. struct mg_workerTLS *tls =
  3489. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3490. sprintf(txt, "%03i", conn->response_info.status_code);
  3491. if (strlen(txt) == 3) {
  3492. memcpy(tls->txtbuf, txt, 4);
  3493. } else {
  3494. strcpy(tls->txtbuf, "ERR");
  3495. }
  3496. ((struct mg_connection *)conn)->request_info.local_uri =
  3497. ((struct mg_connection *)conn)->request_info.request_uri =
  3498. tls->txtbuf; /* use thread safe buffer */
  3499. ((struct mg_connection *)conn)->request_info.num_headers =
  3500. conn->response_info.num_headers;
  3501. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3502. conn->response_info.http_headers,
  3503. sizeof(conn->response_info.http_headers));
  3504. } else
  3505. #endif
  3506. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3507. return NULL;
  3508. }
  3509. return &conn->request_info;
  3510. }
  3511. const struct mg_response_info *
  3512. mg_get_response_info(const struct mg_connection *conn)
  3513. {
  3514. if (!conn) {
  3515. return NULL;
  3516. }
  3517. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3518. return NULL;
  3519. }
  3520. return &conn->response_info;
  3521. }
  3522. static const char *
  3523. get_proto_name(const struct mg_connection *conn)
  3524. {
  3525. #if defined(__clang__)
  3526. #pragma clang diagnostic push
  3527. #pragma clang diagnostic ignored "-Wunreachable-code"
  3528. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3529. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3530. * unreachable, but splitting into four different #ifdef clauses here is more
  3531. * complicated.
  3532. */
  3533. #endif
  3534. const struct mg_request_info *ri = &conn->request_info;
  3535. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3536. ? (ri->is_ssl ? "wss" : "ws")
  3537. : (ri->is_ssl ? "https" : "http"));
  3538. return proto;
  3539. #if defined(__clang__)
  3540. #pragma clang diagnostic pop
  3541. #endif
  3542. }
  3543. static int
  3544. mg_construct_local_link(const struct mg_connection *conn,
  3545. char *buf,
  3546. size_t buflen,
  3547. const char *define_proto,
  3548. int define_port,
  3549. const char *define_uri)
  3550. {
  3551. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3552. return -1;
  3553. } else {
  3554. int truncated = 0;
  3555. const struct mg_request_info *ri = &conn->request_info;
  3556. const char *proto =
  3557. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3558. const char *uri =
  3559. (define_uri != NULL)
  3560. ? define_uri
  3561. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3562. int port = (define_port > 0) ? define_port : ri->server_port;
  3563. int default_port = 80;
  3564. if (uri == NULL) {
  3565. return -1;
  3566. }
  3567. #if defined(USE_X_DOM_SOCKET)
  3568. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3569. /* TODO: Define and document a link for UNIX domain sockets. */
  3570. /* There seems to be no official standard for this.
  3571. * Common uses seem to be "httpunix://", "http.unix://" or
  3572. * "http+unix://" as a protocol definition string, followed by
  3573. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3574. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3575. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3576. * "" (completely skipping the server name part). In any case, the
  3577. * last part is the server local path. */
  3578. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3579. mg_snprintf(conn,
  3580. &truncated,
  3581. buf,
  3582. buflen,
  3583. "%s.unix://%s%s",
  3584. proto,
  3585. server_name,
  3586. ri->local_uri);
  3587. default_port = 0;
  3588. return 0;
  3589. }
  3590. #endif
  3591. if (define_proto) {
  3592. /* If we got a protocol name, use the default port accordingly. */
  3593. if ((0 == strcmp(define_proto, "https"))
  3594. || (0 == strcmp(define_proto, "wss"))) {
  3595. default_port = 443;
  3596. }
  3597. } else if (ri->is_ssl) {
  3598. /* If we did not get a protocol name, use TLS as default if it is
  3599. * already used. */
  3600. default_port = 443;
  3601. }
  3602. {
  3603. #if defined(USE_IPV6)
  3604. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3605. #endif
  3606. int auth_domain_check_enabled =
  3607. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3608. && (!mg_strcasecmp(
  3609. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3610. const char *server_domain =
  3611. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3612. char portstr[16];
  3613. char server_ip[48];
  3614. if (port != default_port) {
  3615. sprintf(portstr, ":%u", (unsigned)port);
  3616. } else {
  3617. portstr[0] = 0;
  3618. }
  3619. if (!auth_domain_check_enabled || !server_domain) {
  3620. sockaddr_to_string(server_ip,
  3621. sizeof(server_ip),
  3622. &conn->client.lsa);
  3623. server_domain = server_ip;
  3624. }
  3625. mg_snprintf(conn,
  3626. &truncated,
  3627. buf,
  3628. buflen,
  3629. #if defined(USE_IPV6)
  3630. "%s://%s%s%s%s%s",
  3631. proto,
  3632. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3633. server_domain,
  3634. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3635. #else
  3636. "%s://%s%s%s",
  3637. proto,
  3638. server_domain,
  3639. #endif
  3640. portstr,
  3641. ri->local_uri);
  3642. if (truncated) {
  3643. return -1;
  3644. }
  3645. return 0;
  3646. }
  3647. }
  3648. }
  3649. int
  3650. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3651. {
  3652. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3653. }
  3654. /* Skip the characters until one of the delimiters characters found.
  3655. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3656. * Advance pointer to buffer to the next word. Return found 0-terminated
  3657. * word.
  3658. * Delimiters can be quoted with quotechar. */
  3659. static char *
  3660. skip_quoted(char **buf,
  3661. const char *delimiters,
  3662. const char *whitespace,
  3663. char quotechar)
  3664. {
  3665. char *p, *begin_word, *end_word, *end_whitespace;
  3666. begin_word = *buf;
  3667. end_word = begin_word + strcspn(begin_word, delimiters);
  3668. /* Check for quotechar */
  3669. if (end_word > begin_word) {
  3670. p = end_word - 1;
  3671. while (*p == quotechar) {
  3672. /* While the delimiter is quoted, look for the next delimiter.
  3673. */
  3674. /* This happens, e.g., in calls from parse_auth_header,
  3675. * if the user name contains a " character. */
  3676. /* If there is anything beyond end_word, copy it. */
  3677. if (*end_word != '\0') {
  3678. size_t end_off = strcspn(end_word + 1, delimiters);
  3679. memmove(p, end_word, end_off + 1);
  3680. p += end_off; /* p must correspond to end_word - 1 */
  3681. end_word += end_off + 1;
  3682. } else {
  3683. *p = '\0';
  3684. break;
  3685. }
  3686. }
  3687. for (p++; p < end_word; p++) {
  3688. *p = '\0';
  3689. }
  3690. }
  3691. if (*end_word == '\0') {
  3692. *buf = end_word;
  3693. } else {
  3694. #if defined(GCC_DIAGNOSTIC)
  3695. /* Disable spurious conversion warning for GCC */
  3696. #pragma GCC diagnostic push
  3697. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3698. #endif /* defined(GCC_DIAGNOSTIC) */
  3699. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3700. #if defined(GCC_DIAGNOSTIC)
  3701. #pragma GCC diagnostic pop
  3702. #endif /* defined(GCC_DIAGNOSTIC) */
  3703. for (p = end_word; p < end_whitespace; p++) {
  3704. *p = '\0';
  3705. }
  3706. *buf = end_whitespace;
  3707. }
  3708. return begin_word;
  3709. }
  3710. /* Return HTTP header value, or NULL if not found. */
  3711. static const char *
  3712. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3713. {
  3714. int i;
  3715. for (i = 0; i < num_hdr; i++) {
  3716. if (!mg_strcasecmp(name, hdr[i].name)) {
  3717. return hdr[i].value;
  3718. }
  3719. }
  3720. return NULL;
  3721. }
  3722. #if defined(USE_WEBSOCKET)
  3723. /* Retrieve requested HTTP header multiple values, and return the number of
  3724. * found occurrences */
  3725. static int
  3726. get_req_headers(const struct mg_request_info *ri,
  3727. const char *name,
  3728. const char **output,
  3729. int output_max_size)
  3730. {
  3731. int i;
  3732. int cnt = 0;
  3733. if (ri) {
  3734. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3735. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3736. output[cnt++] = ri->http_headers[i].value;
  3737. }
  3738. }
  3739. }
  3740. return cnt;
  3741. }
  3742. #endif
  3743. const char *
  3744. mg_get_header(const struct mg_connection *conn, const char *name)
  3745. {
  3746. if (!conn) {
  3747. return NULL;
  3748. }
  3749. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3750. return get_header(conn->request_info.http_headers,
  3751. conn->request_info.num_headers,
  3752. name);
  3753. }
  3754. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3755. return get_header(conn->response_info.http_headers,
  3756. conn->response_info.num_headers,
  3757. name);
  3758. }
  3759. return NULL;
  3760. }
  3761. static const char *
  3762. get_http_version(const struct mg_connection *conn)
  3763. {
  3764. if (!conn) {
  3765. return NULL;
  3766. }
  3767. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3768. return conn->request_info.http_version;
  3769. }
  3770. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3771. return conn->response_info.http_version;
  3772. }
  3773. return NULL;
  3774. }
  3775. /* A helper function for traversing a comma separated list of values.
  3776. * It returns a list pointer shifted to the next value, or NULL if the end
  3777. * of the list found.
  3778. * Value is stored in val vector. If value has form "x=y", then eq_val
  3779. * vector is initialized to point to the "y" part, and val vector length
  3780. * is adjusted to point only to "x". */
  3781. static const char *
  3782. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3783. {
  3784. int end;
  3785. reparse:
  3786. if (val == NULL || list == NULL || *list == '\0') {
  3787. /* End of the list */
  3788. return NULL;
  3789. }
  3790. /* Skip over leading LWS */
  3791. while (*list == ' ' || *list == '\t')
  3792. list++;
  3793. val->ptr = list;
  3794. if ((list = strchr(val->ptr, ',')) != NULL) {
  3795. /* Comma found. Store length and shift the list ptr */
  3796. val->len = ((size_t)(list - val->ptr));
  3797. list++;
  3798. } else {
  3799. /* This value is the last one */
  3800. list = val->ptr + strlen(val->ptr);
  3801. val->len = ((size_t)(list - val->ptr));
  3802. }
  3803. /* Adjust length for trailing LWS */
  3804. end = (int)val->len - 1;
  3805. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3806. end--;
  3807. val->len = (size_t)(end) + (size_t)(1);
  3808. if (val->len == 0) {
  3809. /* Ignore any empty entries. */
  3810. goto reparse;
  3811. }
  3812. if (eq_val != NULL) {
  3813. /* Value has form "x=y", adjust pointers and lengths
  3814. * so that val points to "x", and eq_val points to "y". */
  3815. eq_val->len = 0;
  3816. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3817. if (eq_val->ptr != NULL) {
  3818. eq_val->ptr++; /* Skip over '=' character */
  3819. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3820. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3821. }
  3822. }
  3823. return list;
  3824. }
  3825. /* A helper function for checking if a comma separated list of values
  3826. * contains
  3827. * the given option (case insensitvely).
  3828. * 'header' can be NULL, in which case false is returned. */
  3829. static int
  3830. header_has_option(const char *header, const char *option)
  3831. {
  3832. struct vec opt_vec;
  3833. struct vec eq_vec;
  3834. DEBUG_ASSERT(option != NULL);
  3835. DEBUG_ASSERT(option[0] != '\0');
  3836. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3837. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3838. return 1;
  3839. }
  3840. return 0;
  3841. }
  3842. /* Perform case-insensitive match of string against pattern */
  3843. static ptrdiff_t
  3844. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3845. {
  3846. const char *or_str;
  3847. ptrdiff_t i, j, len, res;
  3848. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3849. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3850. return (res > 0) ? res
  3851. : match_prefix(or_str + 1,
  3852. (size_t)((pattern + pattern_len)
  3853. - (or_str + 1)),
  3854. str);
  3855. }
  3856. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3857. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3858. continue;
  3859. } else if (pattern[i] == '$') {
  3860. return (str[j] == '\0') ? j : -1;
  3861. } else if (pattern[i] == '*') {
  3862. i++;
  3863. if (pattern[i] == '*') {
  3864. i++;
  3865. len = (ptrdiff_t)strlen(str + j);
  3866. } else {
  3867. len = (ptrdiff_t)strcspn(str + j, "/");
  3868. }
  3869. if (i == (ptrdiff_t)pattern_len) {
  3870. return j + len;
  3871. }
  3872. do {
  3873. res = match_prefix(pattern + i,
  3874. (pattern_len - (size_t)i),
  3875. str + j + len);
  3876. } while (res == -1 && len-- > 0);
  3877. return (res == -1) ? -1 : j + res + len;
  3878. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3879. return -1;
  3880. }
  3881. }
  3882. return (ptrdiff_t)j;
  3883. }
  3884. static ptrdiff_t
  3885. match_prefix_strlen(const char *pattern, const char *str)
  3886. {
  3887. if (pattern == NULL) {
  3888. return -1;
  3889. }
  3890. return match_prefix(pattern, strlen(pattern), str);
  3891. }
  3892. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3893. * This function must tolerate situations when connection info is not
  3894. * set up, for example if request parsing failed. */
  3895. static int
  3896. should_keep_alive(const struct mg_connection *conn)
  3897. {
  3898. const char *http_version;
  3899. const char *header;
  3900. /* First satisfy needs of the server */
  3901. if ((conn == NULL) || conn->must_close) {
  3902. /* Close, if civetweb framework needs to close */
  3903. return 0;
  3904. }
  3905. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3906. /* Close, if keep alive is not enabled */
  3907. return 0;
  3908. }
  3909. /* Check explicit wish of the client */
  3910. header = mg_get_header(conn, "Connection");
  3911. if (header) {
  3912. /* If there is a connection header from the client, obey */
  3913. if (header_has_option(header, "keep-alive")) {
  3914. return 1;
  3915. }
  3916. return 0;
  3917. }
  3918. /* Use default of the standard */
  3919. http_version = get_http_version(conn);
  3920. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3921. /* HTTP 1.1 default is keep alive */
  3922. return 1;
  3923. }
  3924. /* HTTP 1.0 (and earlier) default is to close the connection */
  3925. return 0;
  3926. }
  3927. static int
  3928. should_decode_url(const struct mg_connection *conn)
  3929. {
  3930. if (!conn || !conn->dom_ctx) {
  3931. return 0;
  3932. }
  3933. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3934. }
  3935. static const char *
  3936. suggest_connection_header(const struct mg_connection *conn)
  3937. {
  3938. return should_keep_alive(conn) ? "keep-alive" : "close";
  3939. }
  3940. #include "response.inl"
  3941. static void
  3942. send_no_cache_header(struct mg_connection *conn)
  3943. {
  3944. /* Send all current and obsolete cache opt-out directives. */
  3945. mg_response_header_add(conn,
  3946. "Cache-Control",
  3947. "no-cache, no-store, "
  3948. "must-revalidate, private, max-age=0",
  3949. -1);
  3950. mg_response_header_add(conn, "Expires", "0", -1);
  3951. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3952. /* Obsolete, but still send it for HTTP/1.0 */
  3953. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3954. }
  3955. }
  3956. static void
  3957. send_static_cache_header(struct mg_connection *conn)
  3958. {
  3959. #if !defined(NO_CACHING)
  3960. int max_age;
  3961. char val[64];
  3962. const char *cache_control =
  3963. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3964. /* If there is a full cache-control option configured,0 use it */
  3965. if (cache_control != NULL) {
  3966. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3967. return;
  3968. }
  3969. /* Read the server config to check how long a file may be cached.
  3970. * The configuration is in seconds. */
  3971. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3972. if (max_age <= 0) {
  3973. /* 0 means "do not cache". All values <0 are reserved
  3974. * and may be used differently in the future. */
  3975. /* If a file should not be cached, do not only send
  3976. * max-age=0, but also pragmas and Expires headers. */
  3977. send_no_cache_header(conn);
  3978. return;
  3979. }
  3980. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3981. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3982. /* See also https://www.mnot.net/cache_docs/ */
  3983. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3984. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3985. * leap
  3986. * year to 31622400 seconds. For the moment, we just send whatever has
  3987. * been configured, still the behavior for >1 year should be considered
  3988. * as undefined. */
  3989. mg_snprintf(
  3990. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3991. mg_response_header_add(conn, "Cache-Control", val, -1);
  3992. #else /* NO_CACHING */
  3993. send_no_cache_header(conn);
  3994. #endif /* !NO_CACHING */
  3995. }
  3996. static void
  3997. send_additional_header(struct mg_connection *conn)
  3998. {
  3999. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  4000. #if !defined(NO_SSL)
  4001. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  4002. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  4003. if (max_age >= 0) {
  4004. char val[64];
  4005. mg_snprintf(conn,
  4006. NULL,
  4007. val,
  4008. sizeof(val),
  4009. "max-age=%lu",
  4010. (unsigned long)max_age);
  4011. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  4012. }
  4013. }
  4014. #endif
  4015. if (header && header[0]) {
  4016. mg_response_header_add_lines(conn, header);
  4017. }
  4018. }
  4019. #if !defined(NO_FILESYSTEMS)
  4020. static void handle_file_based_request(struct mg_connection *conn,
  4021. const char *path,
  4022. struct mg_file *filep);
  4023. #endif /* NO_FILESYSTEMS */
  4024. const char *
  4025. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  4026. {
  4027. /* See IANA HTTP status code assignment:
  4028. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  4029. */
  4030. switch (response_code) {
  4031. /* RFC2616 Section 10.1 - Informational 1xx */
  4032. case 100:
  4033. return "Continue"; /* RFC2616 Section 10.1.1 */
  4034. case 101:
  4035. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  4036. case 102:
  4037. return "Processing"; /* RFC2518 Section 10.1 */
  4038. /* RFC2616 Section 10.2 - Successful 2xx */
  4039. case 200:
  4040. return "OK"; /* RFC2616 Section 10.2.1 */
  4041. case 201:
  4042. return "Created"; /* RFC2616 Section 10.2.2 */
  4043. case 202:
  4044. return "Accepted"; /* RFC2616 Section 10.2.3 */
  4045. case 203:
  4046. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  4047. case 204:
  4048. return "No Content"; /* RFC2616 Section 10.2.5 */
  4049. case 205:
  4050. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  4051. case 206:
  4052. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  4053. case 207:
  4054. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  4055. */
  4056. case 208:
  4057. return "Already Reported"; /* RFC5842 Section 7.1 */
  4058. case 226:
  4059. return "IM used"; /* RFC3229 Section 10.4.1 */
  4060. /* RFC2616 Section 10.3 - Redirection 3xx */
  4061. case 300:
  4062. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  4063. case 301:
  4064. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  4065. case 302:
  4066. return "Found"; /* RFC2616 Section 10.3.3 */
  4067. case 303:
  4068. return "See Other"; /* RFC2616 Section 10.3.4 */
  4069. case 304:
  4070. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  4071. case 305:
  4072. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  4073. case 307:
  4074. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  4075. case 308:
  4076. return "Permanent Redirect"; /* RFC7238 Section 3 */
  4077. /* RFC2616 Section 10.4 - Client Error 4xx */
  4078. case 400:
  4079. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  4080. case 401:
  4081. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  4082. case 402:
  4083. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  4084. case 403:
  4085. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  4086. case 404:
  4087. return "Not Found"; /* RFC2616 Section 10.4.5 */
  4088. case 405:
  4089. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  4090. case 406:
  4091. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  4092. case 407:
  4093. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  4094. case 408:
  4095. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  4096. case 409:
  4097. return "Conflict"; /* RFC2616 Section 10.4.10 */
  4098. case 410:
  4099. return "Gone"; /* RFC2616 Section 10.4.11 */
  4100. case 411:
  4101. return "Length Required"; /* RFC2616 Section 10.4.12 */
  4102. case 412:
  4103. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  4104. case 413:
  4105. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  4106. case 414:
  4107. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  4108. case 415:
  4109. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  4110. case 416:
  4111. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  4112. */
  4113. case 417:
  4114. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  4115. case 421:
  4116. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  4117. case 422:
  4118. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  4119. * Section 11.2 */
  4120. case 423:
  4121. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  4122. case 424:
  4123. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  4124. * Section 11.4 */
  4125. case 426:
  4126. return "Upgrade Required"; /* RFC 2817 Section 4 */
  4127. case 428:
  4128. return "Precondition Required"; /* RFC 6585, Section 3 */
  4129. case 429:
  4130. return "Too Many Requests"; /* RFC 6585, Section 4 */
  4131. case 431:
  4132. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  4133. case 451:
  4134. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  4135. * Section 3 */
  4136. /* RFC2616 Section 10.5 - Server Error 5xx */
  4137. case 500:
  4138. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  4139. case 501:
  4140. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  4141. case 502:
  4142. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  4143. case 503:
  4144. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  4145. case 504:
  4146. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  4147. case 505:
  4148. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  4149. case 506:
  4150. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  4151. case 507:
  4152. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  4153. * Section 11.5 */
  4154. case 508:
  4155. return "Loop Detected"; /* RFC5842 Section 7.1 */
  4156. case 510:
  4157. return "Not Extended"; /* RFC 2774, Section 7 */
  4158. case 511:
  4159. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  4160. /* Other status codes, not shown in the IANA HTTP status code
  4161. * assignment.
  4162. * E.g., "de facto" standards due to common use, ... */
  4163. case 418:
  4164. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  4165. case 419:
  4166. return "Authentication Timeout"; /* common use */
  4167. case 420:
  4168. return "Enhance Your Calm"; /* common use */
  4169. case 440:
  4170. return "Login Timeout"; /* common use */
  4171. case 509:
  4172. return "Bandwidth Limit Exceeded"; /* common use */
  4173. default:
  4174. /* This error code is unknown. This should not happen. */
  4175. if (conn) {
  4176. mg_cry_internal(conn,
  4177. "Unknown HTTP response code: %u",
  4178. response_code);
  4179. }
  4180. /* Return at least a category according to RFC 2616 Section 10. */
  4181. if (response_code >= 100 && response_code < 200) {
  4182. /* Unknown informational status code */
  4183. return "Information";
  4184. }
  4185. if (response_code >= 200 && response_code < 300) {
  4186. /* Unknown success code */
  4187. return "Success";
  4188. }
  4189. if (response_code >= 300 && response_code < 400) {
  4190. /* Unknown redirection code */
  4191. return "Redirection";
  4192. }
  4193. if (response_code >= 400 && response_code < 500) {
  4194. /* Unknown request error code */
  4195. return "Client Error";
  4196. }
  4197. if (response_code >= 500 && response_code < 600) {
  4198. /* Unknown server error code */
  4199. return "Server Error";
  4200. }
  4201. /* Response code not even within reasonable range */
  4202. return "";
  4203. }
  4204. }
  4205. static int
  4206. mg_send_http_error_impl(struct mg_connection *conn,
  4207. int status,
  4208. const char *fmt,
  4209. va_list args)
  4210. {
  4211. char errmsg_buf[MG_BUF_LEN];
  4212. va_list ap;
  4213. int has_body;
  4214. #if !defined(NO_FILESYSTEMS)
  4215. char path_buf[PATH_MAX];
  4216. int len, i, page_handler_found, scope, truncated;
  4217. const char *error_handler = NULL;
  4218. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  4219. const char *error_page_file_ext, *tstr;
  4220. #endif /* NO_FILESYSTEMS */
  4221. int handled_by_callback = 0;
  4222. if ((conn == NULL) || (fmt == NULL)) {
  4223. return -2;
  4224. }
  4225. /* Set status (for log) */
  4226. conn->status_code = status;
  4227. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  4228. has_body = ((status > 199) && (status != 204) && (status != 304));
  4229. /* Prepare message in buf, if required */
  4230. if (has_body
  4231. || (!conn->in_error_handler
  4232. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  4233. /* Store error message in errmsg_buf */
  4234. va_copy(ap, args);
  4235. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  4236. va_end(ap);
  4237. /* In a debug build, print all html errors */
  4238. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  4239. }
  4240. /* If there is a http_error callback, call it.
  4241. * But don't do it recursively, if callback calls mg_send_http_error again.
  4242. */
  4243. if (!conn->in_error_handler
  4244. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  4245. /* Mark in_error_handler to avoid recursion and call user callback. */
  4246. conn->in_error_handler = 1;
  4247. handled_by_callback =
  4248. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  4249. == 0);
  4250. conn->in_error_handler = 0;
  4251. }
  4252. if (!handled_by_callback) {
  4253. /* Check for recursion */
  4254. if (conn->in_error_handler) {
  4255. DEBUG_TRACE(
  4256. "Recursion when handling error %u - fall back to default",
  4257. status);
  4258. #if !defined(NO_FILESYSTEMS)
  4259. } else {
  4260. /* Send user defined error pages, if defined */
  4261. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  4262. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  4263. page_handler_found = 0;
  4264. if (error_handler != NULL) {
  4265. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  4266. switch (scope) {
  4267. case 1: /* Handler for specific error, e.g. 404 error */
  4268. mg_snprintf(conn,
  4269. &truncated,
  4270. path_buf,
  4271. sizeof(path_buf) - 32,
  4272. "%serror%03u.",
  4273. error_handler,
  4274. status);
  4275. break;
  4276. case 2: /* Handler for error group, e.g., 5xx error
  4277. * handler
  4278. * for all server errors (500-599) */
  4279. mg_snprintf(conn,
  4280. &truncated,
  4281. path_buf,
  4282. sizeof(path_buf) - 32,
  4283. "%serror%01uxx.",
  4284. error_handler,
  4285. status / 100);
  4286. break;
  4287. default: /* Handler for all errors */
  4288. mg_snprintf(conn,
  4289. &truncated,
  4290. path_buf,
  4291. sizeof(path_buf) - 32,
  4292. "%serror.",
  4293. error_handler);
  4294. break;
  4295. }
  4296. /* String truncation in buf may only occur if
  4297. * error_handler is too long. This string is
  4298. * from the config, not from a client. */
  4299. (void)truncated;
  4300. /* The following code is redundant, but it should avoid
  4301. * false positives in static source code analyzers and
  4302. * vulnerability scanners.
  4303. */
  4304. path_buf[sizeof(path_buf) - 32] = 0;
  4305. len = (int)strlen(path_buf);
  4306. if (len > (int)sizeof(path_buf) - 32) {
  4307. len = (int)sizeof(path_buf) - 32;
  4308. }
  4309. /* Start with the file extenstion from the configuration. */
  4310. tstr = strchr(error_page_file_ext, '.');
  4311. while (tstr) {
  4312. for (i = 1;
  4313. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4314. i++) {
  4315. /* buffer overrun is not possible here, since
  4316. * (i < 32) && (len < sizeof(path_buf) - 32)
  4317. * ==> (i + len) < sizeof(path_buf) */
  4318. path_buf[len + i - 1] = tstr[i];
  4319. }
  4320. /* buffer overrun is not possible here, since
  4321. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4322. * ==> (i + len) <= sizeof(path_buf) */
  4323. path_buf[len + i - 1] = 0;
  4324. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4325. DEBUG_TRACE("Check error page %s - found",
  4326. path_buf);
  4327. page_handler_found = 1;
  4328. break;
  4329. }
  4330. DEBUG_TRACE("Check error page %s - not found",
  4331. path_buf);
  4332. /* Continue with the next file extenstion from the
  4333. * configuration (if there is a next one). */
  4334. tstr = strchr(tstr + i, '.');
  4335. }
  4336. }
  4337. }
  4338. if (page_handler_found) {
  4339. conn->in_error_handler = 1;
  4340. handle_file_based_request(conn, path_buf, &error_page_file);
  4341. conn->in_error_handler = 0;
  4342. return 0;
  4343. }
  4344. #endif /* NO_FILESYSTEMS */
  4345. }
  4346. /* No custom error page. Send default error page. */
  4347. conn->must_close = 1;
  4348. mg_response_header_start(conn, status);
  4349. send_no_cache_header(conn);
  4350. send_additional_header(conn);
  4351. if (has_body) {
  4352. mg_response_header_add(conn,
  4353. "Content-Type",
  4354. "text/plain; charset=utf-8",
  4355. -1);
  4356. }
  4357. mg_response_header_send(conn);
  4358. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4359. if (has_body) {
  4360. /* For other errors, send a generic error message. */
  4361. const char *status_text = mg_get_response_code_text(conn, status);
  4362. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4363. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4364. } else {
  4365. /* No body allowed. Close the connection. */
  4366. DEBUG_TRACE("Error %i", status);
  4367. }
  4368. }
  4369. return 0;
  4370. }
  4371. int
  4372. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4373. {
  4374. va_list ap;
  4375. int ret;
  4376. va_start(ap, fmt);
  4377. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4378. va_end(ap);
  4379. return ret;
  4380. }
  4381. int
  4382. mg_send_http_ok(struct mg_connection *conn,
  4383. const char *mime_type,
  4384. long long content_length)
  4385. {
  4386. if ((mime_type == NULL) || (*mime_type == 0)) {
  4387. /* No content type defined: default to text/html */
  4388. mime_type = "text/html";
  4389. }
  4390. mg_response_header_start(conn, 200);
  4391. send_no_cache_header(conn);
  4392. send_additional_header(conn);
  4393. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  4394. if (content_length < 0) {
  4395. /* Size not known. Use chunked encoding (HTTP/1.x) */
  4396. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  4397. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  4398. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  4399. }
  4400. } else {
  4401. char len[32];
  4402. int trunc = 0;
  4403. mg_snprintf(conn,
  4404. &trunc,
  4405. len,
  4406. sizeof(len),
  4407. "%" UINT64_FMT,
  4408. (uint64_t)content_length);
  4409. if (!trunc) {
  4410. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  4411. * !trunc is always true */
  4412. mg_response_header_add(conn, "Content-Length", len, -1);
  4413. }
  4414. }
  4415. mg_response_header_send(conn);
  4416. return 0;
  4417. }
  4418. int
  4419. mg_send_http_redirect(struct mg_connection *conn,
  4420. const char *target_url,
  4421. int redirect_code)
  4422. {
  4423. /* Send a 30x redirect response.
  4424. *
  4425. * Redirect types (status codes):
  4426. *
  4427. * Status | Perm/Temp | Method | Version
  4428. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4429. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4430. * 303 | temporary | always use GET | HTTP/1.1
  4431. * 307 | temporary | always keep method | HTTP/1.1
  4432. * 308 | permanent | always keep method | HTTP/1.1
  4433. */
  4434. const char *redirect_text;
  4435. int ret;
  4436. size_t content_len = 0;
  4437. #if defined(MG_SEND_REDIRECT_BODY)
  4438. char reply[MG_BUF_LEN];
  4439. #endif
  4440. /* In case redirect_code=0, use 307. */
  4441. if (redirect_code == 0) {
  4442. redirect_code = 307;
  4443. }
  4444. /* In case redirect_code is none of the above, return error. */
  4445. if ((redirect_code != 301) && (redirect_code != 302)
  4446. && (redirect_code != 303) && (redirect_code != 307)
  4447. && (redirect_code != 308)) {
  4448. /* Parameter error */
  4449. return -2;
  4450. }
  4451. /* Get proper text for response code */
  4452. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4453. /* If target_url is not defined, redirect to "/". */
  4454. if ((target_url == NULL) || (*target_url == 0)) {
  4455. target_url = "/";
  4456. }
  4457. #if defined(MG_SEND_REDIRECT_BODY)
  4458. /* TODO: condition name? */
  4459. /* Prepare a response body with a hyperlink.
  4460. *
  4461. * According to RFC2616 (and RFC1945 before):
  4462. * Unless the request method was HEAD, the entity of the
  4463. * response SHOULD contain a short hypertext note with a hyperlink to
  4464. * the new URI(s).
  4465. *
  4466. * However, this response body is not useful in M2M communication.
  4467. * Probably the original reason in the RFC was, clients not supporting
  4468. * a 30x HTTP redirect could still show the HTML page and let the user
  4469. * press the link. Since current browsers support 30x HTTP, the additional
  4470. * HTML body does not seem to make sense anymore.
  4471. *
  4472. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4473. * but it only notes:
  4474. * The server's response payload usually contains a short
  4475. * hypertext note with a hyperlink to the new URI(s).
  4476. *
  4477. * Deactivated by default. If you need the 30x body, set the define.
  4478. */
  4479. mg_snprintf(
  4480. conn,
  4481. NULL /* ignore truncation */,
  4482. reply,
  4483. sizeof(reply),
  4484. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4485. redirect_text,
  4486. target_url,
  4487. target_url);
  4488. content_len = strlen(reply);
  4489. #endif
  4490. /* Do not send any additional header. For all other options,
  4491. * including caching, there are suitable defaults. */
  4492. ret = mg_printf(conn,
  4493. "HTTP/1.1 %i %s\r\n"
  4494. "Location: %s\r\n"
  4495. "Content-Length: %u\r\n"
  4496. "Connection: %s\r\n\r\n",
  4497. redirect_code,
  4498. redirect_text,
  4499. target_url,
  4500. (unsigned int)content_len,
  4501. suggest_connection_header(conn));
  4502. #if defined(MG_SEND_REDIRECT_BODY)
  4503. /* Send response body */
  4504. if (ret > 0) {
  4505. /* ... unless it is a HEAD request */
  4506. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4507. ret = mg_write(conn, reply, content_len);
  4508. }
  4509. }
  4510. #endif
  4511. return (ret > 0) ? ret : -1;
  4512. }
  4513. #if defined(_WIN32)
  4514. /* Create substitutes for POSIX functions in Win32. */
  4515. #if defined(GCC_DIAGNOSTIC)
  4516. /* Show no warning in case system functions are not used. */
  4517. #pragma GCC diagnostic push
  4518. #pragma GCC diagnostic ignored "-Wunused-function"
  4519. #endif
  4520. static int
  4521. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4522. {
  4523. (void)unused;
  4524. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4525. InitializeCriticalSection(&mutex->sec);
  4526. return 0;
  4527. }
  4528. static int
  4529. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4530. {
  4531. DeleteCriticalSection(&mutex->sec);
  4532. return 0;
  4533. }
  4534. static int
  4535. pthread_mutex_lock(pthread_mutex_t *mutex)
  4536. {
  4537. EnterCriticalSection(&mutex->sec);
  4538. return 0;
  4539. }
  4540. static int
  4541. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4542. {
  4543. LeaveCriticalSection(&mutex->sec);
  4544. return 0;
  4545. }
  4546. FUNCTION_MAY_BE_UNUSED
  4547. static int
  4548. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4549. {
  4550. (void)unused;
  4551. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4552. cv->waiting_thread = NULL;
  4553. return 0;
  4554. }
  4555. FUNCTION_MAY_BE_UNUSED
  4556. static int
  4557. pthread_cond_timedwait(pthread_cond_t *cv,
  4558. pthread_mutex_t *mutex,
  4559. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4560. {
  4561. struct mg_workerTLS **ptls,
  4562. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4563. int ok;
  4564. uint64_t nsnow, nswaitabs;
  4565. int64_t nswaitrel;
  4566. DWORD mswaitrel;
  4567. pthread_mutex_lock(&cv->threadIdSec);
  4568. /* Add this thread to cv's waiting list */
  4569. ptls = &cv->waiting_thread;
  4570. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4571. ;
  4572. tls->next_waiting_thread = NULL;
  4573. *ptls = tls;
  4574. pthread_mutex_unlock(&cv->threadIdSec);
  4575. if (abstime) {
  4576. nsnow = mg_get_current_time_ns();
  4577. nswaitabs =
  4578. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4579. nswaitrel = nswaitabs - nsnow;
  4580. if (nswaitrel < 0) {
  4581. nswaitrel = 0;
  4582. }
  4583. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4584. } else {
  4585. mswaitrel = (DWORD)INFINITE;
  4586. }
  4587. pthread_mutex_unlock(mutex);
  4588. ok = (WAIT_OBJECT_0
  4589. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4590. if (!ok) {
  4591. ok = 1;
  4592. pthread_mutex_lock(&cv->threadIdSec);
  4593. ptls = &cv->waiting_thread;
  4594. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4595. if (*ptls == tls) {
  4596. *ptls = tls->next_waiting_thread;
  4597. ok = 0;
  4598. break;
  4599. }
  4600. }
  4601. pthread_mutex_unlock(&cv->threadIdSec);
  4602. if (ok) {
  4603. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4604. (DWORD)INFINITE);
  4605. }
  4606. }
  4607. /* This thread has been removed from cv's waiting list */
  4608. pthread_mutex_lock(mutex);
  4609. return ok ? 0 : -1;
  4610. }
  4611. FUNCTION_MAY_BE_UNUSED
  4612. static int
  4613. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4614. {
  4615. return pthread_cond_timedwait(cv, mutex, NULL);
  4616. }
  4617. FUNCTION_MAY_BE_UNUSED
  4618. static int
  4619. pthread_cond_signal(pthread_cond_t *cv)
  4620. {
  4621. HANDLE wkup = NULL;
  4622. BOOL ok = FALSE;
  4623. pthread_mutex_lock(&cv->threadIdSec);
  4624. if (cv->waiting_thread) {
  4625. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4626. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4627. ok = SetEvent(wkup);
  4628. DEBUG_ASSERT(ok);
  4629. }
  4630. pthread_mutex_unlock(&cv->threadIdSec);
  4631. return ok ? 0 : 1;
  4632. }
  4633. FUNCTION_MAY_BE_UNUSED
  4634. static int
  4635. pthread_cond_broadcast(pthread_cond_t *cv)
  4636. {
  4637. pthread_mutex_lock(&cv->threadIdSec);
  4638. while (cv->waiting_thread) {
  4639. pthread_cond_signal(cv);
  4640. }
  4641. pthread_mutex_unlock(&cv->threadIdSec);
  4642. return 0;
  4643. }
  4644. FUNCTION_MAY_BE_UNUSED
  4645. static int
  4646. pthread_cond_destroy(pthread_cond_t *cv)
  4647. {
  4648. pthread_mutex_lock(&cv->threadIdSec);
  4649. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4650. pthread_mutex_unlock(&cv->threadIdSec);
  4651. pthread_mutex_destroy(&cv->threadIdSec);
  4652. return 0;
  4653. }
  4654. #if defined(ALTERNATIVE_QUEUE)
  4655. FUNCTION_MAY_BE_UNUSED
  4656. static void *
  4657. event_create(void)
  4658. {
  4659. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4660. }
  4661. FUNCTION_MAY_BE_UNUSED
  4662. static int
  4663. event_wait(void *eventhdl)
  4664. {
  4665. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4666. return (res == WAIT_OBJECT_0);
  4667. }
  4668. FUNCTION_MAY_BE_UNUSED
  4669. static int
  4670. event_signal(void *eventhdl)
  4671. {
  4672. return (int)SetEvent((HANDLE)eventhdl);
  4673. }
  4674. FUNCTION_MAY_BE_UNUSED
  4675. static void
  4676. event_destroy(void *eventhdl)
  4677. {
  4678. CloseHandle((HANDLE)eventhdl);
  4679. }
  4680. #endif
  4681. #if defined(GCC_DIAGNOSTIC)
  4682. /* Enable unused function warning again */
  4683. #pragma GCC diagnostic pop
  4684. #endif
  4685. /* For Windows, change all slashes to backslashes in path names. */
  4686. static void
  4687. change_slashes_to_backslashes(char *path)
  4688. {
  4689. int i;
  4690. for (i = 0; path[i] != '\0'; i++) {
  4691. if (path[i] == '/') {
  4692. path[i] = '\\';
  4693. }
  4694. /* remove double backslash (check i > 0 to preserve UNC paths,
  4695. * like \\server\file.txt) */
  4696. if ((i > 0) && (path[i] == '\\')) {
  4697. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4698. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4699. }
  4700. }
  4701. }
  4702. }
  4703. static int
  4704. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4705. {
  4706. int diff;
  4707. do {
  4708. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4709. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4710. s1++;
  4711. s2++;
  4712. } while ((diff == 0) && (s1[-1] != L'\0'));
  4713. return diff;
  4714. }
  4715. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4716. * wbuf and wbuf_len is a target buffer and its length. */
  4717. static void
  4718. path_to_unicode(const struct mg_connection *conn,
  4719. const char *path,
  4720. wchar_t *wbuf,
  4721. size_t wbuf_len)
  4722. {
  4723. char buf[PATH_MAX], buf2[PATH_MAX];
  4724. wchar_t wbuf2[W_PATH_MAX + 1];
  4725. DWORD long_len, err;
  4726. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4727. mg_strlcpy(buf, path, sizeof(buf));
  4728. change_slashes_to_backslashes(buf);
  4729. /* Convert to Unicode and back. If doubly-converted string does not
  4730. * match the original, something is fishy, reject. */
  4731. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4732. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4733. WideCharToMultiByte(
  4734. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4735. if (strcmp(buf, buf2) != 0) {
  4736. wbuf[0] = L'\0';
  4737. }
  4738. /* Windows file systems are not case sensitive, but you can still use
  4739. * uppercase and lowercase letters (on all modern file systems).
  4740. * The server can check if the URI uses the same upper/lowercase
  4741. * letters an the file system, effectively making Windows servers
  4742. * case sensitive (like Linux servers are). It is still not possible
  4743. * to use two files with the same name in different cases on Windows
  4744. * (like /a and /A) - this would be possible in Linux.
  4745. * As a default, Windows is not case sensitive, but the case sensitive
  4746. * file name check can be activated by an additional configuration. */
  4747. if (conn) {
  4748. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4749. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4750. "yes")) {
  4751. /* Use case sensitive compare function */
  4752. fcompare = wcscmp;
  4753. }
  4754. }
  4755. (void)conn; /* conn is currently unused */
  4756. #if !defined(_WIN32_WCE)
  4757. /* Only accept a full file path, not a Windows short (8.3) path. */
  4758. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4759. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4760. if (long_len == 0) {
  4761. err = GetLastError();
  4762. if (err == ERROR_FILE_NOT_FOUND) {
  4763. /* File does not exist. This is not always a problem here. */
  4764. return;
  4765. }
  4766. }
  4767. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4768. /* Short name is used. */
  4769. wbuf[0] = L'\0';
  4770. }
  4771. #else
  4772. (void)long_len;
  4773. (void)wbuf2;
  4774. (void)err;
  4775. if (strchr(path, '~')) {
  4776. wbuf[0] = L'\0';
  4777. }
  4778. #endif
  4779. }
  4780. #if !defined(NO_FILESYSTEMS)
  4781. /* Get file information, return 1 if file exists, 0 if not */
  4782. static int
  4783. mg_stat(const struct mg_connection *conn,
  4784. const char *path,
  4785. struct mg_file_stat *filep)
  4786. {
  4787. wchar_t wbuf[W_PATH_MAX];
  4788. WIN32_FILE_ATTRIBUTE_DATA info;
  4789. time_t creation_time;
  4790. size_t len;
  4791. if (!filep) {
  4792. return 0;
  4793. }
  4794. memset(filep, 0, sizeof(*filep));
  4795. if (mg_path_suspicious(conn, path)) {
  4796. return 0;
  4797. }
  4798. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4799. /* Windows happily opens files with some garbage at the end of file name.
  4800. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4801. * "a.cgi", despite one would expect an error back. */
  4802. len = strlen(path);
  4803. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4804. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4805. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4806. filep->last_modified =
  4807. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4808. info.ftLastWriteTime.dwHighDateTime);
  4809. /* On Windows, the file creation time can be higher than the
  4810. * modification time, e.g. when a file is copied.
  4811. * Since the Last-Modified timestamp is used for caching
  4812. * it should be based on the most recent timestamp. */
  4813. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4814. info.ftCreationTime.dwHighDateTime);
  4815. if (creation_time > filep->last_modified) {
  4816. filep->last_modified = creation_time;
  4817. }
  4818. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4819. return 1;
  4820. }
  4821. return 0;
  4822. }
  4823. #endif
  4824. static int
  4825. mg_remove(const struct mg_connection *conn, const char *path)
  4826. {
  4827. wchar_t wbuf[W_PATH_MAX];
  4828. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4829. return DeleteFileW(wbuf) ? 0 : -1;
  4830. }
  4831. static int
  4832. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4833. {
  4834. wchar_t wbuf[W_PATH_MAX];
  4835. (void)mode;
  4836. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4837. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4838. }
  4839. /* Create substitutes for POSIX functions in Win32. */
  4840. #if defined(GCC_DIAGNOSTIC)
  4841. /* Show no warning in case system functions are not used. */
  4842. #pragma GCC diagnostic push
  4843. #pragma GCC diagnostic ignored "-Wunused-function"
  4844. #endif
  4845. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4846. FUNCTION_MAY_BE_UNUSED
  4847. static DIR *
  4848. mg_opendir(const struct mg_connection *conn, const char *name)
  4849. {
  4850. DIR *dir = NULL;
  4851. wchar_t wpath[W_PATH_MAX];
  4852. DWORD attrs;
  4853. if (name == NULL) {
  4854. SetLastError(ERROR_BAD_ARGUMENTS);
  4855. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4856. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4857. } else {
  4858. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4859. attrs = GetFileAttributesW(wpath);
  4860. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4861. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4862. (void)wcscat(wpath, L"\\*");
  4863. dir->handle = FindFirstFileW(wpath, &dir->info);
  4864. dir->result.d_name[0] = '\0';
  4865. } else {
  4866. mg_free(dir);
  4867. dir = NULL;
  4868. }
  4869. }
  4870. return dir;
  4871. }
  4872. FUNCTION_MAY_BE_UNUSED
  4873. static int
  4874. mg_closedir(DIR *dir)
  4875. {
  4876. int result = 0;
  4877. if (dir != NULL) {
  4878. if (dir->handle != INVALID_HANDLE_VALUE)
  4879. result = FindClose(dir->handle) ? 0 : -1;
  4880. mg_free(dir);
  4881. } else {
  4882. result = -1;
  4883. SetLastError(ERROR_BAD_ARGUMENTS);
  4884. }
  4885. return result;
  4886. }
  4887. FUNCTION_MAY_BE_UNUSED
  4888. static struct dirent *
  4889. mg_readdir(DIR *dir)
  4890. {
  4891. struct dirent *result = 0;
  4892. if (dir) {
  4893. if (dir->handle != INVALID_HANDLE_VALUE) {
  4894. result = &dir->result;
  4895. (void)WideCharToMultiByte(CP_UTF8,
  4896. 0,
  4897. dir->info.cFileName,
  4898. -1,
  4899. result->d_name,
  4900. sizeof(result->d_name),
  4901. NULL,
  4902. NULL);
  4903. if (!FindNextFileW(dir->handle, &dir->info)) {
  4904. (void)FindClose(dir->handle);
  4905. dir->handle = INVALID_HANDLE_VALUE;
  4906. }
  4907. } else {
  4908. SetLastError(ERROR_FILE_NOT_FOUND);
  4909. }
  4910. } else {
  4911. SetLastError(ERROR_BAD_ARGUMENTS);
  4912. }
  4913. return result;
  4914. }
  4915. #if !defined(HAVE_POLL)
  4916. #undef POLLIN
  4917. #undef POLLPRI
  4918. #undef POLLOUT
  4919. #define POLLIN (1) /* Data ready - read will not block. */
  4920. #define POLLPRI (2) /* Priority data ready. */
  4921. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4922. FUNCTION_MAY_BE_UNUSED
  4923. static int
  4924. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4925. {
  4926. struct timeval tv;
  4927. fd_set rset;
  4928. fd_set wset;
  4929. unsigned int i;
  4930. int result;
  4931. SOCKET maxfd = 0;
  4932. memset(&tv, 0, sizeof(tv));
  4933. tv.tv_sec = milliseconds / 1000;
  4934. tv.tv_usec = (milliseconds % 1000) * 1000;
  4935. FD_ZERO(&rset);
  4936. FD_ZERO(&wset);
  4937. for (i = 0; i < n; i++) {
  4938. if (pfd[i].events & POLLIN) {
  4939. FD_SET(pfd[i].fd, &rset);
  4940. }
  4941. if (pfd[i].events & POLLOUT) {
  4942. FD_SET(pfd[i].fd, &wset);
  4943. }
  4944. pfd[i].revents = 0;
  4945. if (pfd[i].fd > maxfd) {
  4946. maxfd = pfd[i].fd;
  4947. }
  4948. }
  4949. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4950. for (i = 0; i < n; i++) {
  4951. if (FD_ISSET(pfd[i].fd, &rset)) {
  4952. pfd[i].revents |= POLLIN;
  4953. }
  4954. if (FD_ISSET(pfd[i].fd, &wset)) {
  4955. pfd[i].revents |= POLLOUT;
  4956. }
  4957. }
  4958. }
  4959. /* We should subtract the time used in select from remaining
  4960. * "milliseconds", in particular if called from mg_poll with a
  4961. * timeout quantum.
  4962. * Unfortunately, the remaining time is not stored in "tv" in all
  4963. * implementations, so the result in "tv" must be considered undefined.
  4964. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4965. return result;
  4966. }
  4967. #endif /* HAVE_POLL */
  4968. #if defined(GCC_DIAGNOSTIC)
  4969. /* Enable unused function warning again */
  4970. #pragma GCC diagnostic pop
  4971. #endif
  4972. static void
  4973. set_close_on_exec(SOCKET sock,
  4974. const struct mg_connection *conn /* may be null */,
  4975. struct mg_context *ctx /* may be null */)
  4976. {
  4977. (void)conn; /* Unused. */
  4978. (void)ctx;
  4979. #if defined(_WIN32_WCE)
  4980. (void)sock;
  4981. #else
  4982. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4983. #endif
  4984. }
  4985. int
  4986. mg_start_thread(mg_thread_func_t f, void *p)
  4987. {
  4988. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4989. /* Compile-time option to control stack size, e.g.
  4990. * -DUSE_STACK_SIZE=16384
  4991. */
  4992. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4993. == ((uintptr_t)(-1L)))
  4994. ? -1
  4995. : 0);
  4996. #else
  4997. return (
  4998. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4999. ? -1
  5000. : 0);
  5001. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5002. }
  5003. /* Start a thread storing the thread context. */
  5004. static int
  5005. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  5006. void *p,
  5007. pthread_t *threadidptr)
  5008. {
  5009. uintptr_t uip;
  5010. HANDLE threadhandle;
  5011. int result = -1;
  5012. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  5013. threadhandle = (HANDLE)uip;
  5014. if ((uip != 0) && (threadidptr != NULL)) {
  5015. *threadidptr = threadhandle;
  5016. result = 0;
  5017. }
  5018. return result;
  5019. }
  5020. /* Wait for a thread to finish. */
  5021. static int
  5022. mg_join_thread(pthread_t threadid)
  5023. {
  5024. int result;
  5025. DWORD dwevent;
  5026. result = -1;
  5027. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  5028. if (dwevent == WAIT_FAILED) {
  5029. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  5030. } else {
  5031. if (dwevent == WAIT_OBJECT_0) {
  5032. CloseHandle(threadid);
  5033. result = 0;
  5034. }
  5035. }
  5036. return result;
  5037. }
  5038. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  5039. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  5040. /* Create substitutes for POSIX functions in Win32. */
  5041. #if defined(GCC_DIAGNOSTIC)
  5042. /* Show no warning in case system functions are not used. */
  5043. #pragma GCC diagnostic push
  5044. #pragma GCC diagnostic ignored "-Wunused-function"
  5045. #endif
  5046. FUNCTION_MAY_BE_UNUSED
  5047. static HANDLE
  5048. dlopen(const char *dll_name, int flags)
  5049. {
  5050. wchar_t wbuf[W_PATH_MAX];
  5051. (void)flags;
  5052. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  5053. return LoadLibraryW(wbuf);
  5054. }
  5055. FUNCTION_MAY_BE_UNUSED
  5056. static int
  5057. dlclose(void *handle)
  5058. {
  5059. int result;
  5060. if (FreeLibrary((HMODULE)handle) != 0) {
  5061. result = 0;
  5062. } else {
  5063. result = -1;
  5064. }
  5065. return result;
  5066. }
  5067. #if defined(GCC_DIAGNOSTIC)
  5068. /* Enable unused function warning again */
  5069. #pragma GCC diagnostic pop
  5070. #endif
  5071. #endif
  5072. #if !defined(NO_CGI)
  5073. #define SIGKILL (0)
  5074. static int
  5075. kill(pid_t pid, int sig_num)
  5076. {
  5077. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  5078. (void)CloseHandle((HANDLE)pid);
  5079. return 0;
  5080. }
  5081. #if !defined(WNOHANG)
  5082. #define WNOHANG (1)
  5083. #endif
  5084. static pid_t
  5085. waitpid(pid_t pid, int *status, int flags)
  5086. {
  5087. DWORD timeout = INFINITE;
  5088. DWORD waitres;
  5089. (void)status; /* Currently not used by any client here */
  5090. if ((flags | WNOHANG) == WNOHANG) {
  5091. timeout = 0;
  5092. }
  5093. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  5094. if (waitres == WAIT_OBJECT_0) {
  5095. return pid;
  5096. }
  5097. if (waitres == WAIT_TIMEOUT) {
  5098. return 0;
  5099. }
  5100. return (pid_t)-1;
  5101. }
  5102. static void
  5103. trim_trailing_whitespaces(char *s)
  5104. {
  5105. char *e = s + strlen(s);
  5106. while ((e > s) && isspace((unsigned char)e[-1])) {
  5107. *(--e) = '\0';
  5108. }
  5109. }
  5110. static pid_t
  5111. spawn_process(struct mg_connection *conn,
  5112. const char *prog,
  5113. char *envblk,
  5114. char *envp[],
  5115. int fdin[2],
  5116. int fdout[2],
  5117. int fderr[2],
  5118. const char *dir)
  5119. {
  5120. HANDLE me;
  5121. char *interp;
  5122. char *interp_arg = 0;
  5123. char full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  5124. int truncated;
  5125. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5126. STARTUPINFOA si;
  5127. PROCESS_INFORMATION pi = {0};
  5128. (void)envp;
  5129. memset(&si, 0, sizeof(si));
  5130. si.cb = sizeof(si);
  5131. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  5132. si.wShowWindow = SW_HIDE;
  5133. me = GetCurrentProcess();
  5134. DuplicateHandle(me,
  5135. (HANDLE)_get_osfhandle(fdin[0]),
  5136. me,
  5137. &si.hStdInput,
  5138. 0,
  5139. TRUE,
  5140. DUPLICATE_SAME_ACCESS);
  5141. DuplicateHandle(me,
  5142. (HANDLE)_get_osfhandle(fdout[1]),
  5143. me,
  5144. &si.hStdOutput,
  5145. 0,
  5146. TRUE,
  5147. DUPLICATE_SAME_ACCESS);
  5148. DuplicateHandle(me,
  5149. (HANDLE)_get_osfhandle(fderr[1]),
  5150. me,
  5151. &si.hStdError,
  5152. 0,
  5153. TRUE,
  5154. DUPLICATE_SAME_ACCESS);
  5155. /* Mark handles that should not be inherited. See
  5156. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  5157. */
  5158. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  5159. HANDLE_FLAG_INHERIT,
  5160. 0);
  5161. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  5162. HANDLE_FLAG_INHERIT,
  5163. 0);
  5164. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  5165. HANDLE_FLAG_INHERIT,
  5166. 0);
  5167. /* First check, if there is a CGI interpreter configured for all CGI
  5168. * scripts. */
  5169. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5170. if (interp != NULL) {
  5171. /* If there is a configured interpreter, check for additional arguments
  5172. */
  5173. interp_arg = conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5174. } else {
  5175. /* Otherwise, the interpreter must be stated in the first line of the
  5176. * CGI script file, after a #! (shebang) mark. */
  5177. buf[0] = buf[1] = '\0';
  5178. /* Get the full script path */
  5179. mg_snprintf(
  5180. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  5181. if (truncated) {
  5182. pi.hProcess = (pid_t)-1;
  5183. goto spawn_cleanup;
  5184. }
  5185. /* Open the script file, to read the first line */
  5186. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  5187. /* Read the first line of the script into the buffer */
  5188. mg_fgets(buf, sizeof(buf), &file);
  5189. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5190. buf[sizeof(buf) - 1] = '\0';
  5191. }
  5192. if ((buf[0] == '#') && (buf[1] == '!')) {
  5193. trim_trailing_whitespaces(buf + 2);
  5194. } else {
  5195. buf[2] = '\0';
  5196. }
  5197. interp = buf + 2;
  5198. }
  5199. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  5200. if (interp[0] != '\0') {
  5201. /* This is an interpreted script file. We must call the interpreter. */
  5202. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  5203. mg_snprintf(conn,
  5204. &truncated,
  5205. cmdline,
  5206. sizeof(cmdline),
  5207. "\"%s\" %s \"%s\\%s\"",
  5208. interp,
  5209. interp_arg,
  5210. full_dir,
  5211. prog);
  5212. } else {
  5213. mg_snprintf(conn,
  5214. &truncated,
  5215. cmdline,
  5216. sizeof(cmdline),
  5217. "\"%s\" \"%s\\%s\"",
  5218. interp,
  5219. full_dir,
  5220. prog);
  5221. }
  5222. } else {
  5223. /* This is (probably) a compiled program. We call it directly. */
  5224. mg_snprintf(conn,
  5225. &truncated,
  5226. cmdline,
  5227. sizeof(cmdline),
  5228. "\"%s\\%s\"",
  5229. full_dir,
  5230. prog);
  5231. }
  5232. if (truncated) {
  5233. pi.hProcess = (pid_t)-1;
  5234. goto spawn_cleanup;
  5235. }
  5236. DEBUG_TRACE("Running [%s]", cmdline);
  5237. if (CreateProcessA(NULL,
  5238. cmdline,
  5239. NULL,
  5240. NULL,
  5241. TRUE,
  5242. CREATE_NEW_PROCESS_GROUP,
  5243. envblk,
  5244. NULL,
  5245. &si,
  5246. &pi)
  5247. == 0) {
  5248. mg_cry_internal(
  5249. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  5250. pi.hProcess = (pid_t)-1;
  5251. /* goto spawn_cleanup; */
  5252. }
  5253. spawn_cleanup:
  5254. (void)CloseHandle(si.hStdOutput);
  5255. (void)CloseHandle(si.hStdError);
  5256. (void)CloseHandle(si.hStdInput);
  5257. if (pi.hThread != NULL) {
  5258. (void)CloseHandle(pi.hThread);
  5259. }
  5260. return (pid_t)pi.hProcess;
  5261. }
  5262. #endif /* !NO_CGI */
  5263. static int
  5264. set_blocking_mode(SOCKET sock)
  5265. {
  5266. unsigned long non_blocking = 0;
  5267. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5268. }
  5269. static int
  5270. set_non_blocking_mode(SOCKET sock)
  5271. {
  5272. unsigned long non_blocking = 1;
  5273. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  5274. }
  5275. #else
  5276. #if !defined(NO_FILESYSTEMS)
  5277. static int
  5278. mg_stat(const struct mg_connection *conn,
  5279. const char *path,
  5280. struct mg_file_stat *filep)
  5281. {
  5282. struct stat st;
  5283. if (!filep) {
  5284. return 0;
  5285. }
  5286. memset(filep, 0, sizeof(*filep));
  5287. if (mg_path_suspicious(conn, path)) {
  5288. return 0;
  5289. }
  5290. if (0 == stat(path, &st)) {
  5291. filep->size = (uint64_t)(st.st_size);
  5292. filep->last_modified = st.st_mtime;
  5293. filep->is_directory = S_ISDIR(st.st_mode);
  5294. return 1;
  5295. }
  5296. return 0;
  5297. }
  5298. #endif /* NO_FILESYSTEMS */
  5299. static void
  5300. set_close_on_exec(int fd,
  5301. const struct mg_connection *conn /* may be null */,
  5302. struct mg_context *ctx /* may be null */)
  5303. {
  5304. #if defined(__ZEPHYR__)
  5305. (void)fd;
  5306. (void)conn;
  5307. (void)ctx;
  5308. #else
  5309. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5310. if (conn || ctx) {
  5311. struct mg_connection fc;
  5312. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5313. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5314. __func__,
  5315. strerror(ERRNO));
  5316. }
  5317. }
  5318. #endif
  5319. }
  5320. int
  5321. mg_start_thread(mg_thread_func_t func, void *param)
  5322. {
  5323. pthread_t thread_id;
  5324. pthread_attr_t attr;
  5325. int result;
  5326. (void)pthread_attr_init(&attr);
  5327. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5328. #if defined(__ZEPHYR__)
  5329. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5330. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5331. /* Compile-time option to control stack size,
  5332. * e.g. -DUSE_STACK_SIZE=16384 */
  5333. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5334. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5335. result = pthread_create(&thread_id, &attr, func, param);
  5336. pthread_attr_destroy(&attr);
  5337. return result;
  5338. }
  5339. /* Start a thread storing the thread context. */
  5340. static int
  5341. mg_start_thread_with_id(mg_thread_func_t func,
  5342. void *param,
  5343. pthread_t *threadidptr)
  5344. {
  5345. pthread_t thread_id;
  5346. pthread_attr_t attr;
  5347. int result;
  5348. (void)pthread_attr_init(&attr);
  5349. #if defined(__ZEPHYR__)
  5350. pthread_attr_setstack(&attr,
  5351. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5352. ZEPHYR_STACK_SIZE);
  5353. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5354. /* Compile-time option to control stack size,
  5355. * e.g. -DUSE_STACK_SIZE=16384 */
  5356. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5357. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5358. result = pthread_create(&thread_id, &attr, func, param);
  5359. pthread_attr_destroy(&attr);
  5360. if ((result == 0) && (threadidptr != NULL)) {
  5361. *threadidptr = thread_id;
  5362. }
  5363. return result;
  5364. }
  5365. /* Wait for a thread to finish. */
  5366. static int
  5367. mg_join_thread(pthread_t threadid)
  5368. {
  5369. int result;
  5370. result = pthread_join(threadid, NULL);
  5371. return result;
  5372. }
  5373. #if !defined(NO_CGI)
  5374. static pid_t
  5375. spawn_process(struct mg_connection *conn,
  5376. const char *prog,
  5377. char *envblk,
  5378. char *envp[],
  5379. int fdin[2],
  5380. int fdout[2],
  5381. int fderr[2],
  5382. const char *dir)
  5383. {
  5384. pid_t pid;
  5385. const char *interp;
  5386. (void)envblk;
  5387. if ((pid = fork()) == -1) {
  5388. /* Parent */
  5389. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5390. } else if (pid != 0) {
  5391. /* Make sure children close parent-side descriptors.
  5392. * The caller will close the child-side immediately. */
  5393. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5394. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5395. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5396. } else {
  5397. /* Child */
  5398. if (chdir(dir) != 0) {
  5399. mg_cry_internal(
  5400. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5401. } else if (dup2(fdin[0], 0) == -1) {
  5402. mg_cry_internal(conn,
  5403. "%s: dup2(%d, 0): %s",
  5404. __func__,
  5405. fdin[0],
  5406. strerror(ERRNO));
  5407. } else if (dup2(fdout[1], 1) == -1) {
  5408. mg_cry_internal(conn,
  5409. "%s: dup2(%d, 1): %s",
  5410. __func__,
  5411. fdout[1],
  5412. strerror(ERRNO));
  5413. } else if (dup2(fderr[1], 2) == -1) {
  5414. mg_cry_internal(conn,
  5415. "%s: dup2(%d, 2): %s",
  5416. __func__,
  5417. fderr[1],
  5418. strerror(ERRNO));
  5419. } else {
  5420. struct sigaction sa;
  5421. /* Keep stderr and stdout in two different pipes.
  5422. * Stdout will be sent back to the client,
  5423. * stderr should go into a server error log. */
  5424. (void)close(fdin[0]);
  5425. (void)close(fdout[1]);
  5426. (void)close(fderr[1]);
  5427. /* Close write end fdin and read end fdout and fderr */
  5428. (void)close(fdin[1]);
  5429. (void)close(fdout[0]);
  5430. (void)close(fderr[0]);
  5431. /* After exec, all signal handlers are restored to their default
  5432. * values, with one exception of SIGCHLD. According to
  5433. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5434. * will leave unchanged after exec if it was set to be ignored.
  5435. * Restore it to default action. */
  5436. memset(&sa, 0, sizeof(sa));
  5437. sa.sa_handler = SIG_DFL;
  5438. sigaction(SIGCHLD, &sa, NULL);
  5439. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5440. if (interp == NULL) {
  5441. /* no interpreter configured, call the programm directly */
  5442. (void)execle(prog, prog, NULL, envp);
  5443. mg_cry_internal(conn,
  5444. "%s: execle(%s): %s",
  5445. __func__,
  5446. prog,
  5447. strerror(ERRNO));
  5448. } else {
  5449. /* call the configured interpreter */
  5450. const char *interp_args =
  5451. conn->dom_ctx->config[CGI_INTERPRETER_ARGS];
  5452. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5453. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5454. } else {
  5455. (void)execle(interp, interp, prog, NULL, envp);
  5456. }
  5457. mg_cry_internal(conn,
  5458. "%s: execle(%s %s): %s",
  5459. __func__,
  5460. interp,
  5461. prog,
  5462. strerror(ERRNO));
  5463. }
  5464. }
  5465. exit(EXIT_FAILURE);
  5466. }
  5467. return pid;
  5468. }
  5469. #endif /* !NO_CGI */
  5470. static int
  5471. set_non_blocking_mode(SOCKET sock)
  5472. {
  5473. int flags = fcntl(sock, F_GETFL, 0);
  5474. if (flags < 0) {
  5475. return -1;
  5476. }
  5477. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5478. return -1;
  5479. }
  5480. return 0;
  5481. }
  5482. static int
  5483. set_blocking_mode(SOCKET sock)
  5484. {
  5485. int flags = fcntl(sock, F_GETFL, 0);
  5486. if (flags < 0) {
  5487. return -1;
  5488. }
  5489. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5490. return -1;
  5491. }
  5492. return 0;
  5493. }
  5494. #endif /* _WIN32 / else */
  5495. /* End of initial operating system specific define block. */
  5496. /* Get a random number (independent of C rand function) */
  5497. static uint64_t
  5498. get_random(void)
  5499. {
  5500. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5501. static uint64_t lcg = 0; /* Linear congruential generator */
  5502. uint64_t now = mg_get_current_time_ns();
  5503. if (lfsr == 0) {
  5504. /* lfsr will be only 0 if has not been initialized,
  5505. * so this code is called only once. */
  5506. lfsr = mg_get_current_time_ns();
  5507. lcg = mg_get_current_time_ns();
  5508. } else {
  5509. /* Get the next step of both random number generators. */
  5510. lfsr = (lfsr >> 1)
  5511. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5512. << 63);
  5513. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5514. }
  5515. /* Combining two pseudo-random number generators and a high resolution
  5516. * part
  5517. * of the current server time will make it hard (impossible?) to guess
  5518. * the
  5519. * next number. */
  5520. return (lfsr ^ lcg ^ now);
  5521. }
  5522. static int
  5523. mg_poll(struct mg_pollfd *pfd,
  5524. unsigned int n,
  5525. int milliseconds,
  5526. stop_flag_t *stop_flag)
  5527. {
  5528. /* Call poll, but only for a maximum time of a few seconds.
  5529. * This will allow to stop the server after some seconds, instead
  5530. * of having to wait for a long socket timeout. */
  5531. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5532. do {
  5533. int result;
  5534. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5535. /* Shut down signal */
  5536. return -2;
  5537. }
  5538. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5539. ms_now = milliseconds;
  5540. }
  5541. result = poll(pfd, n, ms_now);
  5542. if (result != 0) {
  5543. /* Poll returned either success (1) or error (-1).
  5544. * Forward both to the caller. */
  5545. return result;
  5546. }
  5547. /* Poll returned timeout (0). */
  5548. if (milliseconds > 0) {
  5549. milliseconds -= ms_now;
  5550. }
  5551. } while (milliseconds > 0);
  5552. /* timeout: return 0 */
  5553. return 0;
  5554. }
  5555. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5556. * descriptor.
  5557. * Return value:
  5558. * >=0 .. number of bytes successfully written
  5559. * -1 .. timeout
  5560. * -2 .. error
  5561. */
  5562. static int
  5563. push_inner(struct mg_context *ctx,
  5564. FILE *fp,
  5565. SOCKET sock,
  5566. SSL *ssl,
  5567. const char *buf,
  5568. int len,
  5569. double timeout)
  5570. {
  5571. uint64_t start = 0, now = 0, timeout_ns = 0;
  5572. int n, err;
  5573. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5574. #if defined(_WIN32)
  5575. typedef int len_t;
  5576. #else
  5577. typedef size_t len_t;
  5578. #endif
  5579. if (timeout > 0) {
  5580. now = mg_get_current_time_ns();
  5581. start = now;
  5582. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5583. }
  5584. if (ctx == NULL) {
  5585. return -2;
  5586. }
  5587. #if defined(NO_SSL)
  5588. if (ssl) {
  5589. return -2;
  5590. }
  5591. #endif
  5592. /* Try to read until it succeeds, fails, times out, or the server
  5593. * shuts down. */
  5594. for (;;) {
  5595. #if !defined(NO_SSL)
  5596. if (ssl != NULL) {
  5597. ERR_clear_error();
  5598. n = SSL_write(ssl, buf, len);
  5599. if (n <= 0) {
  5600. err = SSL_get_error(ssl, n);
  5601. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5602. err = ERRNO;
  5603. } else if ((err == SSL_ERROR_WANT_READ)
  5604. || (err == SSL_ERROR_WANT_WRITE)) {
  5605. n = 0;
  5606. } else {
  5607. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5608. ERR_clear_error();
  5609. return -2;
  5610. }
  5611. ERR_clear_error();
  5612. } else {
  5613. err = 0;
  5614. }
  5615. } else
  5616. #endif
  5617. if (fp != NULL) {
  5618. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5619. if (ferror(fp)) {
  5620. n = -1;
  5621. err = ERRNO;
  5622. } else {
  5623. err = 0;
  5624. }
  5625. } else {
  5626. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5627. err = (n < 0) ? ERRNO : 0;
  5628. #if defined(_WIN32)
  5629. if (err == WSAEWOULDBLOCK) {
  5630. err = 0;
  5631. n = 0;
  5632. }
  5633. #else
  5634. if (ERROR_TRY_AGAIN(err)) {
  5635. err = 0;
  5636. n = 0;
  5637. }
  5638. #endif
  5639. if (n < 0) {
  5640. /* shutdown of the socket at client side */
  5641. return -2;
  5642. }
  5643. }
  5644. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5645. return -2;
  5646. }
  5647. if ((n > 0) || ((n == 0) && (len == 0))) {
  5648. /* some data has been read, or no data was requested */
  5649. return n;
  5650. }
  5651. if (n < 0) {
  5652. /* socket error - check errno */
  5653. DEBUG_TRACE("send() failed, error %d", err);
  5654. /* TODO (mid): error handling depending on the error code.
  5655. * These codes are different between Windows and Linux.
  5656. * Currently there is no problem with failing send calls,
  5657. * if there is a reproducible situation, it should be
  5658. * investigated in detail.
  5659. */
  5660. return -2;
  5661. }
  5662. /* Only in case n=0 (timeout), repeat calling the write function */
  5663. /* If send failed, wait before retry */
  5664. if (fp != NULL) {
  5665. /* For files, just wait a fixed time.
  5666. * Maybe it helps, maybe not. */
  5667. mg_sleep(5);
  5668. } else {
  5669. /* For sockets, wait for the socket using poll */
  5670. struct mg_pollfd pfd[1];
  5671. int pollres;
  5672. pfd[0].fd = sock;
  5673. pfd[0].events = POLLOUT;
  5674. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5675. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5676. return -2;
  5677. }
  5678. if (pollres > 0) {
  5679. continue;
  5680. }
  5681. }
  5682. if (timeout > 0) {
  5683. now = mg_get_current_time_ns();
  5684. if ((now - start) > timeout_ns) {
  5685. /* Timeout */
  5686. break;
  5687. }
  5688. }
  5689. }
  5690. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5691. used */
  5692. return -1;
  5693. }
  5694. static int
  5695. push_all(struct mg_context *ctx,
  5696. FILE *fp,
  5697. SOCKET sock,
  5698. SSL *ssl,
  5699. const char *buf,
  5700. int len)
  5701. {
  5702. double timeout = -1.0;
  5703. int n, nwritten = 0;
  5704. if (ctx == NULL) {
  5705. return -1;
  5706. }
  5707. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5708. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5709. }
  5710. if (timeout <= 0.0) {
  5711. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5712. }
  5713. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5714. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5715. if (n < 0) {
  5716. if (nwritten == 0) {
  5717. nwritten = -1; /* Propagate the error */
  5718. }
  5719. break;
  5720. } else if (n == 0) {
  5721. break; /* No more data to write */
  5722. } else {
  5723. nwritten += n;
  5724. len -= n;
  5725. }
  5726. }
  5727. return nwritten;
  5728. }
  5729. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5730. * Return value:
  5731. * >=0 .. number of bytes successfully read
  5732. * -1 .. timeout
  5733. * -2 .. error
  5734. */
  5735. static int
  5736. pull_inner(FILE *fp,
  5737. struct mg_connection *conn,
  5738. char *buf,
  5739. int len,
  5740. double timeout)
  5741. {
  5742. int nread, err = 0;
  5743. #if defined(_WIN32)
  5744. typedef int len_t;
  5745. #else
  5746. typedef size_t len_t;
  5747. #endif
  5748. /* We need an additional wait loop around this, because in some cases
  5749. * with TLSwe may get data from the socket but not from SSL_read.
  5750. * In this case we need to repeat at least once.
  5751. */
  5752. if (fp != NULL) {
  5753. #if !defined(_WIN32_WCE)
  5754. /* Use read() instead of fread(), because if we're reading from the
  5755. * CGI pipe, fread() may block until IO buffer is filled up. We
  5756. * cannot afford to block and must pass all read bytes immediately
  5757. * to the client. */
  5758. nread = (int)read(fileno(fp), buf, (size_t)len);
  5759. #else
  5760. /* WinCE does not support CGI pipes */
  5761. nread = (int)fread(buf, 1, (size_t)len, fp);
  5762. #endif
  5763. err = (nread < 0) ? ERRNO : 0;
  5764. if ((nread == 0) && (len > 0)) {
  5765. /* Should get data, but got EOL */
  5766. return -2;
  5767. }
  5768. #if !defined(NO_SSL)
  5769. } else if (conn->ssl != NULL) {
  5770. int ssl_pending;
  5771. struct mg_pollfd pfd[1];
  5772. int pollres;
  5773. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5774. /* We already know there is no more data buffered in conn->buf
  5775. * but there is more available in the SSL layer. So don't poll
  5776. * conn->client.sock yet. */
  5777. if (ssl_pending > len) {
  5778. ssl_pending = len;
  5779. }
  5780. pollres = 1;
  5781. } else {
  5782. pfd[0].fd = conn->client.sock;
  5783. pfd[0].events = POLLIN;
  5784. pollres = mg_poll(pfd,
  5785. 1,
  5786. (int)(timeout * 1000.0),
  5787. &(conn->phys_ctx->stop_flag));
  5788. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5789. return -2;
  5790. }
  5791. }
  5792. if (pollres > 0) {
  5793. ERR_clear_error();
  5794. nread =
  5795. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5796. if (nread <= 0) {
  5797. err = SSL_get_error(conn->ssl, nread);
  5798. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5799. err = ERRNO;
  5800. } else if ((err == SSL_ERROR_WANT_READ)
  5801. || (err == SSL_ERROR_WANT_WRITE)) {
  5802. nread = 0;
  5803. } else {
  5804. /* All errors should return -2 */
  5805. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5806. ERR_clear_error();
  5807. return -2;
  5808. }
  5809. ERR_clear_error();
  5810. } else {
  5811. err = 0;
  5812. }
  5813. } else if (pollres < 0) {
  5814. /* Error */
  5815. return -2;
  5816. } else {
  5817. /* pollres = 0 means timeout */
  5818. nread = 0;
  5819. }
  5820. #endif
  5821. } else {
  5822. struct mg_pollfd pfd[1];
  5823. int pollres;
  5824. pfd[0].fd = conn->client.sock;
  5825. pfd[0].events = POLLIN;
  5826. pollres = mg_poll(pfd,
  5827. 1,
  5828. (int)(timeout * 1000.0),
  5829. &(conn->phys_ctx->stop_flag));
  5830. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5831. return -2;
  5832. }
  5833. if (pollres > 0) {
  5834. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5835. err = (nread < 0) ? ERRNO : 0;
  5836. if (nread <= 0) {
  5837. /* shutdown of the socket at client side */
  5838. return -2;
  5839. }
  5840. } else if (pollres < 0) {
  5841. /* error callint poll */
  5842. return -2;
  5843. } else {
  5844. /* pollres = 0 means timeout */
  5845. nread = 0;
  5846. }
  5847. }
  5848. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5849. return -2;
  5850. }
  5851. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5852. /* some data has been read, or no data was requested */
  5853. return nread;
  5854. }
  5855. if (nread < 0) {
  5856. /* socket error - check errno */
  5857. #if defined(_WIN32)
  5858. if (err == WSAEWOULDBLOCK) {
  5859. /* TODO (low): check if this is still required */
  5860. /* standard case if called from close_socket_gracefully */
  5861. return -2;
  5862. } else if (err == WSAETIMEDOUT) {
  5863. /* TODO (low): check if this is still required */
  5864. /* timeout is handled by the while loop */
  5865. return 0;
  5866. } else if (err == WSAECONNABORTED) {
  5867. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5868. return -2;
  5869. } else {
  5870. DEBUG_TRACE("recv() failed, error %d", err);
  5871. return -2;
  5872. }
  5873. #else
  5874. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5875. * if the timeout is reached and if the socket was set to non-
  5876. * blocking in close_socket_gracefully, so we can not distinguish
  5877. * here. We have to wait for the timeout in both cases for now.
  5878. */
  5879. if (ERROR_TRY_AGAIN(err)) {
  5880. /* TODO (low): check if this is still required */
  5881. /* EAGAIN/EWOULDBLOCK:
  5882. * standard case if called from close_socket_gracefully
  5883. * => should return -1 */
  5884. /* or timeout occurred
  5885. * => the code must stay in the while loop */
  5886. /* EINTR can be generated on a socket with a timeout set even
  5887. * when SA_RESTART is effective for all relevant signals
  5888. * (see signal(7)).
  5889. * => stay in the while loop */
  5890. } else {
  5891. DEBUG_TRACE("recv() failed, error %d", err);
  5892. return -2;
  5893. }
  5894. #endif
  5895. }
  5896. /* Timeout occurred, but no data available. */
  5897. return -1;
  5898. }
  5899. static int
  5900. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5901. {
  5902. int n, nread = 0;
  5903. double timeout = -1.0;
  5904. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5905. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5906. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5907. }
  5908. if (timeout <= 0.0) {
  5909. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5910. }
  5911. start_time = mg_get_current_time_ns();
  5912. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5913. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5914. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5915. if (n == -2) {
  5916. if (nread == 0) {
  5917. nread = -1; /* Propagate the error */
  5918. }
  5919. break;
  5920. } else if (n == -1) {
  5921. /* timeout */
  5922. if (timeout >= 0.0) {
  5923. now = mg_get_current_time_ns();
  5924. if ((now - start_time) <= timeout_ns) {
  5925. continue;
  5926. }
  5927. }
  5928. break;
  5929. } else if (n == 0) {
  5930. break; /* No more data to read */
  5931. } else {
  5932. nread += n;
  5933. len -= n;
  5934. }
  5935. }
  5936. return nread;
  5937. }
  5938. static void
  5939. discard_unread_request_data(struct mg_connection *conn)
  5940. {
  5941. char buf[MG_BUF_LEN];
  5942. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5943. ;
  5944. }
  5945. static int
  5946. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5947. {
  5948. int64_t content_len, n, buffered_len, nread;
  5949. int64_t len64 =
  5950. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5951. * int, we may not read more
  5952. * bytes */
  5953. const char *body;
  5954. if (conn == NULL) {
  5955. return 0;
  5956. }
  5957. /* If Content-Length is not set for a response with body data,
  5958. * we do not know in advance how much data should be read. */
  5959. content_len = conn->content_len;
  5960. if (content_len < 0) {
  5961. /* The body data is completed when the connection is closed. */
  5962. content_len = INT64_MAX;
  5963. }
  5964. nread = 0;
  5965. if (conn->consumed_content < content_len) {
  5966. /* Adjust number of bytes to read. */
  5967. int64_t left_to_read = content_len - conn->consumed_content;
  5968. if (left_to_read < len64) {
  5969. /* Do not read more than the total content length of the
  5970. * request.
  5971. */
  5972. len64 = left_to_read;
  5973. }
  5974. /* Return buffered data */
  5975. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5976. - conn->consumed_content;
  5977. if (buffered_len > 0) {
  5978. if (len64 < buffered_len) {
  5979. buffered_len = len64;
  5980. }
  5981. body = conn->buf + conn->request_len + conn->consumed_content;
  5982. memcpy(buf, body, (size_t)buffered_len);
  5983. len64 -= buffered_len;
  5984. conn->consumed_content += buffered_len;
  5985. nread += buffered_len;
  5986. buf = (char *)buf + buffered_len;
  5987. }
  5988. /* We have returned all buffered data. Read new data from the remote
  5989. * socket.
  5990. */
  5991. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5992. conn->consumed_content += n;
  5993. nread += n;
  5994. } else {
  5995. nread = ((nread > 0) ? nread : n);
  5996. }
  5997. }
  5998. return (int)nread;
  5999. }
  6000. /* Forward declarations */
  6001. static void handle_request(struct mg_connection *);
  6002. #if defined(USE_HTTP2)
  6003. #if defined(NO_SSL)
  6004. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  6005. #endif
  6006. #define USE_ALPN
  6007. #include "mod_http2.inl"
  6008. /* Not supported with HTTP/2 */
  6009. #define HTTP1_only \
  6010. { \
  6011. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  6012. http2_must_use_http1(conn); \
  6013. return; \
  6014. } \
  6015. }
  6016. #else
  6017. #define HTTP1_only
  6018. #endif
  6019. int
  6020. mg_read(struct mg_connection *conn, void *buf, size_t len)
  6021. {
  6022. if (len > INT_MAX) {
  6023. len = INT_MAX;
  6024. }
  6025. if (conn == NULL) {
  6026. return 0;
  6027. }
  6028. if (conn->is_chunked) {
  6029. size_t all_read = 0;
  6030. while (len > 0) {
  6031. if (conn->is_chunked >= 3) {
  6032. /* No more data left to read */
  6033. return 0;
  6034. }
  6035. if (conn->is_chunked != 1) {
  6036. /* Has error */
  6037. return -1;
  6038. }
  6039. if (conn->consumed_content != conn->content_len) {
  6040. /* copy from the current chunk */
  6041. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  6042. if (read_ret < 1) {
  6043. /* read error */
  6044. conn->is_chunked = 2;
  6045. return -1;
  6046. }
  6047. all_read += (size_t)read_ret;
  6048. len -= (size_t)read_ret;
  6049. if (conn->consumed_content == conn->content_len) {
  6050. /* Add data bytes in the current chunk have been read,
  6051. * so we are expecting \r\n now. */
  6052. char x[2];
  6053. conn->content_len += 2;
  6054. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  6055. || (x[1] != '\n')) {
  6056. /* Protocol violation */
  6057. conn->is_chunked = 2;
  6058. return -1;
  6059. }
  6060. }
  6061. } else {
  6062. /* fetch a new chunk */
  6063. size_t i;
  6064. char lenbuf[64];
  6065. char *end = NULL;
  6066. unsigned long chunkSize = 0;
  6067. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  6068. conn->content_len++;
  6069. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  6070. lenbuf[i] = 0;
  6071. }
  6072. if ((i > 0) && (lenbuf[i] == '\r')
  6073. && (lenbuf[i - 1] != '\r')) {
  6074. continue;
  6075. }
  6076. if ((i > 1) && (lenbuf[i] == '\n')
  6077. && (lenbuf[i - 1] == '\r')) {
  6078. lenbuf[i + 1] = 0;
  6079. chunkSize = strtoul(lenbuf, &end, 16);
  6080. if (chunkSize == 0) {
  6081. /* regular end of content */
  6082. conn->is_chunked = 3;
  6083. }
  6084. break;
  6085. }
  6086. if (!isxdigit((unsigned char)lenbuf[i])) {
  6087. /* illegal character for chunk length */
  6088. conn->is_chunked = 2;
  6089. return -1;
  6090. }
  6091. }
  6092. if ((end == NULL) || (*end != '\r')) {
  6093. /* chunksize not set correctly */
  6094. conn->is_chunked = 2;
  6095. return -1;
  6096. }
  6097. if (chunkSize == 0) {
  6098. /* try discarding trailer for keep-alive */
  6099. conn->content_len += 2;
  6100. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  6101. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  6102. conn->is_chunked = 4;
  6103. }
  6104. break;
  6105. }
  6106. /* append a new chunk */
  6107. conn->content_len += (int64_t)chunkSize;
  6108. }
  6109. }
  6110. return (int)all_read;
  6111. }
  6112. return mg_read_inner(conn, buf, len);
  6113. }
  6114. int
  6115. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  6116. {
  6117. time_t now;
  6118. int n, total, allowed;
  6119. if (conn == NULL) {
  6120. return 0;
  6121. }
  6122. if (len > INT_MAX) {
  6123. return -1;
  6124. }
  6125. /* Mark connection as "data sent" */
  6126. conn->request_state = 10;
  6127. #if defined(USE_HTTP2)
  6128. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  6129. http2_data_frame_head(conn, len, 0);
  6130. }
  6131. #endif
  6132. if (conn->throttle > 0) {
  6133. if ((now = time(NULL)) != conn->last_throttle_time) {
  6134. conn->last_throttle_time = now;
  6135. conn->last_throttle_bytes = 0;
  6136. }
  6137. allowed = conn->throttle - conn->last_throttle_bytes;
  6138. if (allowed > (int)len) {
  6139. allowed = (int)len;
  6140. }
  6141. total = push_all(conn->phys_ctx,
  6142. NULL,
  6143. conn->client.sock,
  6144. conn->ssl,
  6145. (const char *)buf,
  6146. allowed);
  6147. if (total == allowed) {
  6148. buf = (const char *)buf + total;
  6149. conn->last_throttle_bytes += total;
  6150. while ((total < (int)len)
  6151. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  6152. allowed = (conn->throttle > ((int)len - total))
  6153. ? (int)len - total
  6154. : conn->throttle;
  6155. n = push_all(conn->phys_ctx,
  6156. NULL,
  6157. conn->client.sock,
  6158. conn->ssl,
  6159. (const char *)buf,
  6160. allowed);
  6161. if (n != allowed) {
  6162. break;
  6163. }
  6164. sleep(1);
  6165. conn->last_throttle_bytes = allowed;
  6166. conn->last_throttle_time = time(NULL);
  6167. buf = (const char *)buf + n;
  6168. total += n;
  6169. }
  6170. }
  6171. } else {
  6172. total = push_all(conn->phys_ctx,
  6173. NULL,
  6174. conn->client.sock,
  6175. conn->ssl,
  6176. (const char *)buf,
  6177. (int)len);
  6178. }
  6179. if (total > 0) {
  6180. conn->num_bytes_sent += total;
  6181. }
  6182. return total;
  6183. }
  6184. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6185. int
  6186. mg_send_chunk(struct mg_connection *conn,
  6187. const char *chunk,
  6188. unsigned int chunk_len)
  6189. {
  6190. char lenbuf[16];
  6191. size_t lenbuf_len;
  6192. int ret;
  6193. int t;
  6194. /* First store the length information in a text buffer. */
  6195. sprintf(lenbuf, "%x\r\n", chunk_len);
  6196. lenbuf_len = strlen(lenbuf);
  6197. /* Then send length information, chunk and terminating \r\n. */
  6198. ret = mg_write(conn, lenbuf, lenbuf_len);
  6199. if (ret != (int)lenbuf_len) {
  6200. return -1;
  6201. }
  6202. t = ret;
  6203. ret = mg_write(conn, chunk, chunk_len);
  6204. if (ret != (int)chunk_len) {
  6205. return -1;
  6206. }
  6207. t += ret;
  6208. ret = mg_write(conn, "\r\n", 2);
  6209. if (ret != 2) {
  6210. return -1;
  6211. }
  6212. t += ret;
  6213. return t;
  6214. }
  6215. #if defined(GCC_DIAGNOSTIC)
  6216. /* This block forwards format strings to printf implementations,
  6217. * so we need to disable the format-nonliteral warning. */
  6218. #pragma GCC diagnostic push
  6219. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6220. #endif
  6221. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6222. static int
  6223. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6224. {
  6225. va_list ap_copy;
  6226. size_t size = MG_BUF_LEN / 4;
  6227. int len = -1;
  6228. *buf = NULL;
  6229. while (len < 0) {
  6230. if (*buf) {
  6231. mg_free(*buf);
  6232. }
  6233. size *= 4;
  6234. *buf = (char *)mg_malloc(size);
  6235. if (!*buf) {
  6236. break;
  6237. }
  6238. va_copy(ap_copy, ap);
  6239. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6240. va_end(ap_copy);
  6241. (*buf)[size - 1] = 0;
  6242. }
  6243. return len;
  6244. }
  6245. /* Print message to buffer. If buffer is large enough to hold the message,
  6246. * return buffer. If buffer is to small, allocate large enough buffer on
  6247. * heap,
  6248. * and return allocated buffer. */
  6249. static int
  6250. alloc_vprintf(char **out_buf,
  6251. char *prealloc_buf,
  6252. size_t prealloc_size,
  6253. const char *fmt,
  6254. va_list ap)
  6255. {
  6256. va_list ap_copy;
  6257. int len;
  6258. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6259. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6260. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6261. * Therefore, we make two passes: on first pass, get required message
  6262. * length.
  6263. * On second pass, actually print the message. */
  6264. va_copy(ap_copy, ap);
  6265. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6266. va_end(ap_copy);
  6267. if (len < 0) {
  6268. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6269. * Switch to alternative code path that uses incremental
  6270. * allocations.
  6271. */
  6272. va_copy(ap_copy, ap);
  6273. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6274. va_end(ap_copy);
  6275. } else if ((size_t)(len) >= prealloc_size) {
  6276. /* The pre-allocated buffer not large enough. */
  6277. /* Allocate a new buffer. */
  6278. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6279. if (!*out_buf) {
  6280. /* Allocation failed. Return -1 as "out of memory" error. */
  6281. return -1;
  6282. }
  6283. /* Buffer allocation successful. Store the string there. */
  6284. va_copy(ap_copy, ap);
  6285. IGNORE_UNUSED_RESULT(
  6286. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6287. va_end(ap_copy);
  6288. } else {
  6289. /* The pre-allocated buffer is large enough.
  6290. * Use it to store the string and return the address. */
  6291. va_copy(ap_copy, ap);
  6292. IGNORE_UNUSED_RESULT(
  6293. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6294. va_end(ap_copy);
  6295. *out_buf = prealloc_buf;
  6296. }
  6297. return len;
  6298. }
  6299. #if defined(GCC_DIAGNOSTIC)
  6300. /* Enable format-nonliteral warning again. */
  6301. #pragma GCC diagnostic pop
  6302. #endif
  6303. static int
  6304. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6305. {
  6306. char mem[MG_BUF_LEN];
  6307. char *buf = NULL;
  6308. int len;
  6309. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6310. len = mg_write(conn, buf, (size_t)len);
  6311. }
  6312. if (buf != mem) {
  6313. mg_free(buf);
  6314. }
  6315. return len;
  6316. }
  6317. int
  6318. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6319. {
  6320. va_list ap;
  6321. int result;
  6322. va_start(ap, fmt);
  6323. result = mg_vprintf(conn, fmt, ap);
  6324. va_end(ap);
  6325. return result;
  6326. }
  6327. int
  6328. mg_url_decode(const char *src,
  6329. int src_len,
  6330. char *dst,
  6331. int dst_len,
  6332. int is_form_url_encoded)
  6333. {
  6334. int i, j, a, b;
  6335. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6336. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6337. if ((i < src_len - 2) && (src[i] == '%')
  6338. && isxdigit((unsigned char)src[i + 1])
  6339. && isxdigit((unsigned char)src[i + 2])) {
  6340. a = tolower((unsigned char)src[i + 1]);
  6341. b = tolower((unsigned char)src[i + 2]);
  6342. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6343. i += 2;
  6344. } else if (is_form_url_encoded && (src[i] == '+')) {
  6345. dst[j] = ' ';
  6346. } else {
  6347. dst[j] = src[i];
  6348. }
  6349. }
  6350. dst[j] = '\0'; /* Null-terminate the destination */
  6351. return (i >= src_len) ? j : -1;
  6352. }
  6353. /* form url decoding of an entire string */
  6354. static void
  6355. url_decode_in_place(char *buf)
  6356. {
  6357. int len = (int)strlen(buf);
  6358. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6359. }
  6360. int
  6361. mg_get_var(const char *data,
  6362. size_t data_len,
  6363. const char *name,
  6364. char *dst,
  6365. size_t dst_len)
  6366. {
  6367. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6368. }
  6369. int
  6370. mg_get_var2(const char *data,
  6371. size_t data_len,
  6372. const char *name,
  6373. char *dst,
  6374. size_t dst_len,
  6375. size_t occurrence)
  6376. {
  6377. const char *p, *e, *s;
  6378. size_t name_len;
  6379. int len;
  6380. if ((dst == NULL) || (dst_len == 0)) {
  6381. len = -2;
  6382. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6383. len = -1;
  6384. dst[0] = '\0';
  6385. } else {
  6386. name_len = strlen(name);
  6387. e = data + data_len;
  6388. len = -1;
  6389. dst[0] = '\0';
  6390. /* data is "var1=val1&var2=val2...". Find variable first */
  6391. for (p = data; p + name_len < e; p++) {
  6392. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6393. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6394. /* Point p to variable value */
  6395. p += name_len + 1;
  6396. /* Point s to the end of the value */
  6397. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6398. if (s == NULL) {
  6399. s = e;
  6400. }
  6401. DEBUG_ASSERT(s >= p);
  6402. if (s < p) {
  6403. return -3;
  6404. }
  6405. /* Decode variable into destination buffer */
  6406. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6407. /* Redirect error code from -1 to -2 (destination buffer too
  6408. * small). */
  6409. if (len == -1) {
  6410. len = -2;
  6411. }
  6412. break;
  6413. }
  6414. }
  6415. }
  6416. return len;
  6417. }
  6418. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6419. int
  6420. mg_split_form_urlencoded(char *data,
  6421. struct mg_header *form_fields,
  6422. unsigned num_form_fields)
  6423. {
  6424. char *b;
  6425. int i;
  6426. int num = 0;
  6427. if (data == NULL) {
  6428. /* parameter error */
  6429. return -1;
  6430. }
  6431. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6432. /* determine the number of expected fields */
  6433. if (data[0] == 0) {
  6434. return 0;
  6435. }
  6436. /* count number of & to return the number of key-value-pairs */
  6437. num = 1;
  6438. while (*data) {
  6439. if (*data == '&') {
  6440. num++;
  6441. }
  6442. data++;
  6443. }
  6444. return num;
  6445. }
  6446. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6447. /* parameter error */
  6448. return -1;
  6449. }
  6450. for (i = 0; i < (int)num_form_fields; i++) {
  6451. /* extract key-value pairs from input data */
  6452. while ((*data == ' ') || (*data == '\t')) {
  6453. /* skip initial spaces */
  6454. data++;
  6455. }
  6456. if (*data == 0) {
  6457. /* end of string reached */
  6458. break;
  6459. }
  6460. form_fields[num].name = data;
  6461. /* find & or = */
  6462. b = data;
  6463. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6464. b++;
  6465. }
  6466. if (*b == 0) {
  6467. /* last key without value */
  6468. form_fields[num].value = NULL;
  6469. } else if (*b == '&') {
  6470. /* mid key without value */
  6471. form_fields[num].value = NULL;
  6472. } else {
  6473. /* terminate string */
  6474. *b = 0;
  6475. /* value starts after '=' */
  6476. data = b + 1;
  6477. form_fields[num].value = data;
  6478. }
  6479. /* new field is stored */
  6480. num++;
  6481. /* find a next key */
  6482. b = strchr(data, '&');
  6483. if (b == 0) {
  6484. /* no more data */
  6485. break;
  6486. } else {
  6487. /* terminate value of last field at '&' */
  6488. *b = 0;
  6489. /* next key-value-pairs starts after '&' */
  6490. data = b + 1;
  6491. }
  6492. }
  6493. /* Decode all values */
  6494. for (i = 0; i < num; i++) {
  6495. if (form_fields[i].name) {
  6496. url_decode_in_place((char *)form_fields[i].name);
  6497. }
  6498. if (form_fields[i].value) {
  6499. url_decode_in_place((char *)form_fields[i].value);
  6500. }
  6501. }
  6502. /* return number of fields found */
  6503. return num;
  6504. }
  6505. /* HCP24: some changes to compare hole var_name */
  6506. int
  6507. mg_get_cookie(const char *cookie_header,
  6508. const char *var_name,
  6509. char *dst,
  6510. size_t dst_size)
  6511. {
  6512. const char *s, *p, *end;
  6513. int name_len, len = -1;
  6514. if ((dst == NULL) || (dst_size == 0)) {
  6515. return -2;
  6516. }
  6517. dst[0] = '\0';
  6518. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6519. return -1;
  6520. }
  6521. name_len = (int)strlen(var_name);
  6522. end = s + strlen(s);
  6523. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6524. if (s[name_len] == '=') {
  6525. /* HCP24: now check is it a substring or a full cookie name */
  6526. if ((s == cookie_header) || (s[-1] == ' ')) {
  6527. s += name_len + 1;
  6528. if ((p = strchr(s, ' ')) == NULL) {
  6529. p = end;
  6530. }
  6531. if (p[-1] == ';') {
  6532. p--;
  6533. }
  6534. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6535. s++;
  6536. p--;
  6537. }
  6538. if ((size_t)(p - s) < dst_size) {
  6539. len = (int)(p - s);
  6540. mg_strlcpy(dst, s, (size_t)len + 1);
  6541. } else {
  6542. len = -3;
  6543. }
  6544. break;
  6545. }
  6546. }
  6547. }
  6548. return len;
  6549. }
  6550. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6551. static void
  6552. base64_encode(const unsigned char *src, int src_len, char *dst)
  6553. {
  6554. static const char *b64 =
  6555. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6556. int i, j, a, b, c;
  6557. for (i = j = 0; i < src_len; i += 3) {
  6558. a = src[i];
  6559. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6560. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6561. dst[j++] = b64[a >> 2];
  6562. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6563. if (i + 1 < src_len) {
  6564. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6565. }
  6566. if (i + 2 < src_len) {
  6567. dst[j++] = b64[c & 63];
  6568. }
  6569. }
  6570. while (j % 4 != 0) {
  6571. dst[j++] = '=';
  6572. }
  6573. dst[j++] = '\0';
  6574. }
  6575. #endif
  6576. #if defined(USE_LUA)
  6577. static unsigned char
  6578. b64reverse(char letter)
  6579. {
  6580. if ((letter >= 'A') && (letter <= 'Z')) {
  6581. return letter - 'A';
  6582. }
  6583. if ((letter >= 'a') && (letter <= 'z')) {
  6584. return letter - 'a' + 26;
  6585. }
  6586. if ((letter >= '0') && (letter <= '9')) {
  6587. return letter - '0' + 52;
  6588. }
  6589. if (letter == '+') {
  6590. return 62;
  6591. }
  6592. if (letter == '/') {
  6593. return 63;
  6594. }
  6595. if (letter == '=') {
  6596. return 255; /* normal end */
  6597. }
  6598. return 254; /* error */
  6599. }
  6600. static int
  6601. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6602. {
  6603. int i;
  6604. unsigned char a, b, c, d;
  6605. *dst_len = 0;
  6606. for (i = 0; i < src_len; i += 4) {
  6607. a = b64reverse(src[i]);
  6608. if (a >= 254) {
  6609. return i;
  6610. }
  6611. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6612. if (b >= 254) {
  6613. return i + 1;
  6614. }
  6615. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6616. if (c == 254) {
  6617. return i + 2;
  6618. }
  6619. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6620. if (d == 254) {
  6621. return i + 3;
  6622. }
  6623. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6624. if (c != 255) {
  6625. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6626. if (d != 255) {
  6627. dst[(*dst_len)++] = (c << 6) + d;
  6628. }
  6629. }
  6630. }
  6631. return -1;
  6632. }
  6633. #endif
  6634. static int
  6635. is_put_or_delete_method(const struct mg_connection *conn)
  6636. {
  6637. if (conn) {
  6638. const char *s = conn->request_info.request_method;
  6639. return (s != NULL)
  6640. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6641. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6642. }
  6643. return 0;
  6644. }
  6645. #if !defined(NO_FILES)
  6646. static int
  6647. extention_matches_script(
  6648. struct mg_connection *conn, /* in: request (must be valid) */
  6649. const char *filename /* in: filename (must be valid) */
  6650. )
  6651. {
  6652. #if !defined(NO_CGI)
  6653. if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], filename)
  6654. > 0) {
  6655. return 1;
  6656. }
  6657. if (match_prefix_strlen(conn->dom_ctx->config[CGI2_EXTENSIONS], filename)
  6658. > 0) {
  6659. return 1;
  6660. }
  6661. #endif
  6662. #if defined(USE_LUA)
  6663. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6664. filename)
  6665. > 0) {
  6666. return 1;
  6667. }
  6668. #endif
  6669. #if defined(USE_DUKTAPE)
  6670. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6671. filename)
  6672. > 0) {
  6673. return 1;
  6674. }
  6675. #endif
  6676. /* filename and conn could be unused, if all preocessor conditions
  6677. * are false (no script language supported). */
  6678. (void)filename;
  6679. (void)conn;
  6680. return 0;
  6681. }
  6682. static int
  6683. extention_matches_template_text(
  6684. struct mg_connection *conn, /* in: request (must be valid) */
  6685. const char *filename /* in: filename (must be valid) */
  6686. )
  6687. {
  6688. #if defined(USE_LUA)
  6689. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6690. filename)
  6691. > 0) {
  6692. return 1;
  6693. }
  6694. #endif
  6695. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6696. > 0) {
  6697. return 1;
  6698. }
  6699. return 0;
  6700. }
  6701. /* For given directory path, substitute it to valid index file.
  6702. * Return 1 if index file has been found, 0 if not found.
  6703. * If the file is found, it's stats is returned in stp. */
  6704. static int
  6705. substitute_index_file(struct mg_connection *conn,
  6706. char *path,
  6707. size_t path_len,
  6708. struct mg_file_stat *filestat)
  6709. {
  6710. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6711. struct vec filename_vec;
  6712. size_t n = strlen(path);
  6713. int found = 0;
  6714. /* The 'path' given to us points to the directory. Remove all trailing
  6715. * directory separator characters from the end of the path, and
  6716. * then append single directory separator character. */
  6717. while ((n > 0) && (path[n - 1] == '/')) {
  6718. n--;
  6719. }
  6720. path[n] = '/';
  6721. /* Traverse index files list. For each entry, append it to the given
  6722. * path and see if the file exists. If it exists, break the loop */
  6723. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6724. /* Ignore too long entries that may overflow path buffer */
  6725. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6726. continue;
  6727. }
  6728. /* Prepare full path to the index file */
  6729. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6730. /* Does it exist? */
  6731. if (mg_stat(conn, path, filestat)) {
  6732. /* Yes it does, break the loop */
  6733. found = 1;
  6734. break;
  6735. }
  6736. }
  6737. /* If no index file exists, restore directory path */
  6738. if (!found) {
  6739. path[n] = '\0';
  6740. }
  6741. return found;
  6742. }
  6743. #endif
  6744. static void
  6745. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6746. char *filename, /* out: filename */
  6747. size_t filename_buf_len, /* in: size of filename buffer */
  6748. struct mg_file_stat *filestat, /* out: file status structure */
  6749. int *is_found, /* out: file found (directly) */
  6750. int *is_script_resource, /* out: handled by a script? */
  6751. int *is_websocket_request, /* out: websocket connetion? */
  6752. int *is_put_or_delete_request, /* out: put/delete a file? */
  6753. int *is_template_text /* out: SSI file or LSP file? */
  6754. )
  6755. {
  6756. char const *accept_encoding;
  6757. #if !defined(NO_FILES)
  6758. const char *uri = conn->request_info.local_uri;
  6759. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6760. const char *rewrite;
  6761. struct vec a, b;
  6762. ptrdiff_t match_len;
  6763. char gz_path[PATH_MAX];
  6764. int truncated;
  6765. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6766. char *tmp_str;
  6767. size_t tmp_str_len, sep_pos;
  6768. int allow_substitute_script_subresources;
  6769. #endif
  6770. #else
  6771. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6772. #endif
  6773. /* Step 1: Set all initially unknown outputs to zero */
  6774. memset(filestat, 0, sizeof(*filestat));
  6775. *filename = 0;
  6776. *is_found = 0;
  6777. *is_script_resource = 0;
  6778. *is_template_text = 0;
  6779. /* Step 2: Check if the request attempts to modify the file system */
  6780. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6781. /* Step 3: Check if it is a websocket request, and modify the document
  6782. * root if required */
  6783. #if defined(USE_WEBSOCKET)
  6784. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6785. #if !defined(NO_FILES)
  6786. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6787. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6788. }
  6789. #endif /* !NO_FILES */
  6790. #else /* USE_WEBSOCKET */
  6791. *is_websocket_request = 0;
  6792. #endif /* USE_WEBSOCKET */
  6793. /* Step 4: Check if gzip encoded response is allowed */
  6794. conn->accept_gzip = 0;
  6795. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6796. if (strstr(accept_encoding, "gzip") != NULL) {
  6797. conn->accept_gzip = 1;
  6798. }
  6799. }
  6800. #if !defined(NO_FILES)
  6801. /* Step 5: If there is no root directory, don't look for files. */
  6802. /* Note that root == NULL is a regular use case here. This occurs,
  6803. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6804. * config is not required. */
  6805. if (root == NULL) {
  6806. /* all file related outputs have already been set to 0, just return
  6807. */
  6808. return;
  6809. }
  6810. /* Step 6: Determine the local file path from the root path and the
  6811. * request uri. */
  6812. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6813. * part of the path one byte on the right. */
  6814. truncated = 0;
  6815. mg_snprintf(
  6816. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6817. if (truncated) {
  6818. goto interpret_cleanup;
  6819. }
  6820. /* Step 7: URI rewriting */
  6821. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6822. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6823. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6824. mg_snprintf(conn,
  6825. &truncated,
  6826. filename,
  6827. filename_buf_len - 1,
  6828. "%.*s%s",
  6829. (int)b.len,
  6830. b.ptr,
  6831. uri + match_len);
  6832. break;
  6833. }
  6834. }
  6835. if (truncated) {
  6836. goto interpret_cleanup;
  6837. }
  6838. /* Step 8: Check if the file exists at the server */
  6839. /* Local file path and name, corresponding to requested URI
  6840. * is now stored in "filename" variable. */
  6841. if (mg_stat(conn, filename, filestat)) {
  6842. int uri_len = (int)strlen(uri);
  6843. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6844. /* 8.1: File exists. */
  6845. *is_found = 1;
  6846. /* 8.2: Check if it is a script type. */
  6847. if (extention_matches_script(conn, filename)) {
  6848. /* The request addresses a CGI resource, Lua script or
  6849. * server-side javascript.
  6850. * The URI corresponds to the script itself (like
  6851. * /path/script.cgi), and there is no additional resource
  6852. * path (like /path/script.cgi/something).
  6853. * Requests that modify (replace or delete) a resource, like
  6854. * PUT and DELETE requests, should replace/delete the script
  6855. * file.
  6856. * Requests that read or write from/to a resource, like GET and
  6857. * POST requests, should call the script and return the
  6858. * generated response. */
  6859. *is_script_resource = (!*is_put_or_delete_request);
  6860. }
  6861. /* 8.3: Check for SSI and LSP files */
  6862. if (extention_matches_template_text(conn, filename)) {
  6863. /* Same as above, but for *.lsp and *.shtml files. */
  6864. /* A "template text" is a file delivered directly to the client,
  6865. * but with some text tags replaced by dynamic content.
  6866. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6867. * (LP, LSP) file. */
  6868. *is_template_text = (!*is_put_or_delete_request);
  6869. }
  6870. /* 8.4: If the request target is a directory, there could be
  6871. * a substitute file (index.html, index.cgi, ...). */
  6872. if (filestat->is_directory && is_uri_end_slash) {
  6873. /* Use a local copy here, since substitute_index_file will
  6874. * change the content of the file status */
  6875. struct mg_file_stat tmp_filestat;
  6876. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6877. if (substitute_index_file(
  6878. conn, filename, filename_buf_len, &tmp_filestat)) {
  6879. /* Substitute file found. Copy stat to the output, then
  6880. * check if the file is a script file */
  6881. *filestat = tmp_filestat;
  6882. if (extention_matches_script(conn, filename)) {
  6883. /* Substitute file is a script file */
  6884. *is_script_resource = 1;
  6885. } else if (extention_matches_template_text(conn, filename)) {
  6886. /* Substitute file is a LSP or SSI file */
  6887. *is_template_text = 1;
  6888. } else {
  6889. /* Substitute file is a regular file */
  6890. *is_script_resource = 0;
  6891. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6892. }
  6893. }
  6894. /* If there is no substitute file, the server could return
  6895. * a directory listing in a later step */
  6896. }
  6897. return;
  6898. }
  6899. /* Step 9: Check for zipped files: */
  6900. /* If we can't find the actual file, look for the file
  6901. * with the same name but a .gz extension. If we find it,
  6902. * use that and set the gzipped flag in the file struct
  6903. * to indicate that the response need to have the content-
  6904. * encoding: gzip header.
  6905. * We can only do this if the browser declares support. */
  6906. if (conn->accept_gzip) {
  6907. mg_snprintf(
  6908. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6909. if (truncated) {
  6910. goto interpret_cleanup;
  6911. }
  6912. if (mg_stat(conn, gz_path, filestat)) {
  6913. if (filestat) {
  6914. filestat->is_gzipped = 1;
  6915. *is_found = 1;
  6916. }
  6917. /* Currently gz files can not be scripts. */
  6918. return;
  6919. }
  6920. }
  6921. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6922. /* Step 10: Script resources may handle sub-resources */
  6923. /* Support PATH_INFO for CGI scripts. */
  6924. tmp_str_len = strlen(filename);
  6925. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6926. if (!tmp_str) {
  6927. /* Out of memory */
  6928. goto interpret_cleanup;
  6929. }
  6930. memcpy(tmp_str, filename, tmp_str_len + 1);
  6931. /* Check config, if index scripts may have sub-resources */
  6932. allow_substitute_script_subresources =
  6933. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6934. "yes");
  6935. sep_pos = tmp_str_len;
  6936. while (sep_pos > 0) {
  6937. sep_pos--;
  6938. if (tmp_str[sep_pos] == '/') {
  6939. int is_script = 0, does_exist = 0;
  6940. tmp_str[sep_pos] = 0;
  6941. if (tmp_str[0]) {
  6942. is_script = extention_matches_script(conn, tmp_str);
  6943. does_exist = mg_stat(conn, tmp_str, filestat);
  6944. }
  6945. if (does_exist && is_script) {
  6946. filename[sep_pos] = 0;
  6947. memmove(filename + sep_pos + 2,
  6948. filename + sep_pos + 1,
  6949. strlen(filename + sep_pos + 1) + 1);
  6950. conn->path_info = filename + sep_pos + 1;
  6951. filename[sep_pos + 1] = '/';
  6952. *is_script_resource = 1;
  6953. *is_found = 1;
  6954. break;
  6955. }
  6956. if (allow_substitute_script_subresources) {
  6957. if (substitute_index_file(
  6958. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6959. /* some intermediate directory has an index file */
  6960. if (extention_matches_script(conn, tmp_str)) {
  6961. size_t script_name_len = strlen(tmp_str);
  6962. /* subres_name read before this memory locatio will be
  6963. overwritten */
  6964. char *subres_name = filename + sep_pos;
  6965. size_t subres_name_len = strlen(subres_name);
  6966. DEBUG_TRACE("Substitute script %s serving path %s",
  6967. tmp_str,
  6968. filename);
  6969. /* this index file is a script */
  6970. if ((script_name_len + subres_name_len + 2)
  6971. >= filename_buf_len) {
  6972. mg_free(tmp_str);
  6973. goto interpret_cleanup;
  6974. }
  6975. conn->path_info =
  6976. filename + script_name_len + 1; /* new target */
  6977. memmove(conn->path_info, subres_name, subres_name_len);
  6978. conn->path_info[subres_name_len] = 0;
  6979. memcpy(filename, tmp_str, script_name_len + 1);
  6980. *is_script_resource = 1;
  6981. *is_found = 1;
  6982. break;
  6983. } else {
  6984. DEBUG_TRACE("Substitute file %s serving path %s",
  6985. tmp_str,
  6986. filename);
  6987. /* non-script files will not have sub-resources */
  6988. filename[sep_pos] = 0;
  6989. conn->path_info = 0;
  6990. *is_script_resource = 0;
  6991. *is_found = 0;
  6992. break;
  6993. }
  6994. }
  6995. }
  6996. tmp_str[sep_pos] = '/';
  6997. }
  6998. }
  6999. mg_free(tmp_str);
  7000. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  7001. #endif /* !defined(NO_FILES) */
  7002. return;
  7003. #if !defined(NO_FILES)
  7004. /* Reset all outputs */
  7005. interpret_cleanup:
  7006. memset(filestat, 0, sizeof(*filestat));
  7007. *filename = 0;
  7008. *is_found = 0;
  7009. *is_script_resource = 0;
  7010. *is_websocket_request = 0;
  7011. *is_put_or_delete_request = 0;
  7012. #endif /* !defined(NO_FILES) */
  7013. }
  7014. /* Check whether full request is buffered. Return:
  7015. * -1 if request or response is malformed
  7016. * 0 if request or response is not yet fully buffered
  7017. * >0 actual request length, including last \r\n\r\n */
  7018. static int
  7019. get_http_header_len(const char *buf, int buflen)
  7020. {
  7021. int i;
  7022. for (i = 0; i < buflen; i++) {
  7023. /* Do an unsigned comparison in some conditions below */
  7024. const unsigned char c = (unsigned char)buf[i];
  7025. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7026. && !isprint(c)) {
  7027. /* abort scan as soon as one malformed character is found */
  7028. return -1;
  7029. }
  7030. if (i < buflen - 1) {
  7031. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7032. /* Two newline, no carriage return - not standard compliant,
  7033. * but it should be accepted */
  7034. return i + 2;
  7035. }
  7036. }
  7037. if (i < buflen - 3) {
  7038. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7039. && (buf[i + 3] == '\n')) {
  7040. /* Two \r\n - standard compliant */
  7041. return i + 4;
  7042. }
  7043. }
  7044. }
  7045. return 0;
  7046. }
  7047. #if !defined(NO_CACHING)
  7048. /* Convert month to the month number. Return -1 on error, or month number */
  7049. static int
  7050. get_month_index(const char *s)
  7051. {
  7052. size_t i;
  7053. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7054. if (!strcmp(s, month_names[i])) {
  7055. return (int)i;
  7056. }
  7057. }
  7058. return -1;
  7059. }
  7060. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7061. static time_t
  7062. parse_date_string(const char *datetime)
  7063. {
  7064. char month_str[32] = {0};
  7065. int second, minute, hour, day, month, year;
  7066. time_t result = (time_t)0;
  7067. struct tm tm;
  7068. if ((sscanf(datetime,
  7069. "%d/%3s/%d %d:%d:%d",
  7070. &day,
  7071. month_str,
  7072. &year,
  7073. &hour,
  7074. &minute,
  7075. &second)
  7076. == 6)
  7077. || (sscanf(datetime,
  7078. "%d %3s %d %d:%d:%d",
  7079. &day,
  7080. month_str,
  7081. &year,
  7082. &hour,
  7083. &minute,
  7084. &second)
  7085. == 6)
  7086. || (sscanf(datetime,
  7087. "%*3s, %d %3s %d %d:%d:%d",
  7088. &day,
  7089. month_str,
  7090. &year,
  7091. &hour,
  7092. &minute,
  7093. &second)
  7094. == 6)
  7095. || (sscanf(datetime,
  7096. "%d-%3s-%d %d:%d:%d",
  7097. &day,
  7098. month_str,
  7099. &year,
  7100. &hour,
  7101. &minute,
  7102. &second)
  7103. == 6)) {
  7104. month = get_month_index(month_str);
  7105. if ((month >= 0) && (year >= 1970)) {
  7106. memset(&tm, 0, sizeof(tm));
  7107. tm.tm_year = year - 1900;
  7108. tm.tm_mon = month;
  7109. tm.tm_mday = day;
  7110. tm.tm_hour = hour;
  7111. tm.tm_min = minute;
  7112. tm.tm_sec = second;
  7113. result = timegm(&tm);
  7114. }
  7115. }
  7116. return result;
  7117. }
  7118. #endif /* !NO_CACHING */
  7119. /* Pre-process URIs according to RFC + protect against directory disclosure
  7120. * attacks by removing '..', excessive '/' and '\' characters */
  7121. static void
  7122. remove_dot_segments(char *inout)
  7123. {
  7124. /* Windows backend protection
  7125. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7126. * in URI by slash */
  7127. char *out_end = inout;
  7128. char *in = inout;
  7129. if (!in) {
  7130. /* Param error. */
  7131. return;
  7132. }
  7133. while (*in) {
  7134. if (*in == '\\') {
  7135. *in = '/';
  7136. }
  7137. in++;
  7138. }
  7139. /* Algorithm "remove_dot_segments" from
  7140. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7141. /* Step 1:
  7142. * The input buffer is initialized.
  7143. * The output buffer is initialized to the empty string.
  7144. */
  7145. in = inout;
  7146. /* Step 2:
  7147. * While the input buffer is not empty, loop as follows:
  7148. */
  7149. /* Less than out_end of the inout buffer is used as output, so keep
  7150. * condition: out_end <= in */
  7151. while (*in) {
  7152. /* Step 2a:
  7153. * If the input buffer begins with a prefix of "../" or "./",
  7154. * then remove that prefix from the input buffer;
  7155. */
  7156. if (!strncmp(in, "../", 3)) {
  7157. in += 3;
  7158. } else if (!strncmp(in, "./", 2)) {
  7159. in += 2;
  7160. }
  7161. /* otherwise */
  7162. /* Step 2b:
  7163. * if the input buffer begins with a prefix of "/./" or "/.",
  7164. * where "." is a complete path segment, then replace that
  7165. * prefix with "/" in the input buffer;
  7166. */
  7167. else if (!strncmp(in, "/./", 3)) {
  7168. in += 2;
  7169. } else if (!strcmp(in, "/.")) {
  7170. in[1] = 0;
  7171. }
  7172. /* otherwise */
  7173. /* Step 2c:
  7174. * if the input buffer begins with a prefix of "/../" or "/..",
  7175. * where ".." is a complete path segment, then replace that
  7176. * prefix with "/" in the input buffer and remove the last
  7177. * segment and its preceding "/" (if any) from the output
  7178. * buffer;
  7179. */
  7180. else if (!strncmp(in, "/../", 4)) {
  7181. in += 3;
  7182. if (inout != out_end) {
  7183. /* remove last segment */
  7184. do {
  7185. out_end--;
  7186. } while ((inout != out_end) && (*out_end != '/'));
  7187. }
  7188. } else if (!strcmp(in, "/..")) {
  7189. in[1] = 0;
  7190. if (inout != out_end) {
  7191. /* remove last segment */
  7192. do {
  7193. out_end--;
  7194. } while ((inout != out_end) && (*out_end != '/'));
  7195. }
  7196. }
  7197. /* otherwise */
  7198. /* Step 2d:
  7199. * if the input buffer consists only of "." or "..", then remove
  7200. * that from the input buffer;
  7201. */
  7202. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7203. *in = 0;
  7204. }
  7205. /* otherwise */
  7206. /* Step 2e:
  7207. * move the first path segment in the input buffer to the end of
  7208. * the output buffer, including the initial "/" character (if
  7209. * any) and any subsequent characters up to, but not including,
  7210. * the next "/" character or the end of the input buffer.
  7211. */
  7212. else {
  7213. do {
  7214. *out_end = *in;
  7215. out_end++;
  7216. in++;
  7217. } while ((*in != 0) && (*in != '/'));
  7218. }
  7219. }
  7220. /* Step 3:
  7221. * Finally, the output buffer is returned as the result of
  7222. * remove_dot_segments.
  7223. */
  7224. /* Terminate output */
  7225. *out_end = 0;
  7226. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7227. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7228. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7229. * or "//" anymore.
  7230. */
  7231. out_end = in = inout;
  7232. while (*in) {
  7233. if (*in == '.') {
  7234. /* remove . at the end or preceding of / */
  7235. char *in_ahead = in;
  7236. do {
  7237. in_ahead++;
  7238. } while (*in_ahead == '.');
  7239. if (*in_ahead == '/') {
  7240. in = in_ahead;
  7241. if ((out_end != inout) && (out_end[-1] == '/')) {
  7242. /* remove generated // */
  7243. out_end--;
  7244. }
  7245. } else if (*in_ahead == 0) {
  7246. in = in_ahead;
  7247. } else {
  7248. do {
  7249. *out_end++ = '.';
  7250. in++;
  7251. } while (in != in_ahead);
  7252. }
  7253. } else if (*in == '/') {
  7254. /* replace // by / */
  7255. *out_end++ = '/';
  7256. do {
  7257. in++;
  7258. } while (*in == '/');
  7259. } else {
  7260. *out_end++ = *in;
  7261. in++;
  7262. }
  7263. }
  7264. *out_end = 0;
  7265. }
  7266. static const struct {
  7267. const char *extension;
  7268. size_t ext_len;
  7269. const char *mime_type;
  7270. } builtin_mime_types[] = {
  7271. /* IANA registered MIME types
  7272. * (http://www.iana.org/assignments/media-types)
  7273. * application types */
  7274. {".doc", 4, "application/msword"},
  7275. {".eps", 4, "application/postscript"},
  7276. {".exe", 4, "application/octet-stream"},
  7277. {".js", 3, "application/javascript"},
  7278. {".json", 5, "application/json"},
  7279. {".pdf", 4, "application/pdf"},
  7280. {".ps", 3, "application/postscript"},
  7281. {".rtf", 4, "application/rtf"},
  7282. {".xhtml", 6, "application/xhtml+xml"},
  7283. {".xsl", 4, "application/xml"},
  7284. {".xslt", 5, "application/xml"},
  7285. /* fonts */
  7286. {".ttf", 4, "application/font-sfnt"},
  7287. {".cff", 4, "application/font-sfnt"},
  7288. {".otf", 4, "application/font-sfnt"},
  7289. {".aat", 4, "application/font-sfnt"},
  7290. {".sil", 4, "application/font-sfnt"},
  7291. {".pfr", 4, "application/font-tdpfr"},
  7292. {".woff", 5, "application/font-woff"},
  7293. /* audio */
  7294. {".mp3", 4, "audio/mpeg"},
  7295. {".oga", 4, "audio/ogg"},
  7296. {".ogg", 4, "audio/ogg"},
  7297. /* image */
  7298. {".gif", 4, "image/gif"},
  7299. {".ief", 4, "image/ief"},
  7300. {".jpeg", 5, "image/jpeg"},
  7301. {".jpg", 4, "image/jpeg"},
  7302. {".jpm", 4, "image/jpm"},
  7303. {".jpx", 4, "image/jpx"},
  7304. {".png", 4, "image/png"},
  7305. {".svg", 4, "image/svg+xml"},
  7306. {".tif", 4, "image/tiff"},
  7307. {".tiff", 5, "image/tiff"},
  7308. /* model */
  7309. {".wrl", 4, "model/vrml"},
  7310. /* text */
  7311. {".css", 4, "text/css"},
  7312. {".csv", 4, "text/csv"},
  7313. {".htm", 4, "text/html"},
  7314. {".html", 5, "text/html"},
  7315. {".sgm", 4, "text/sgml"},
  7316. {".shtm", 5, "text/html"},
  7317. {".shtml", 6, "text/html"},
  7318. {".txt", 4, "text/plain"},
  7319. {".xml", 4, "text/xml"},
  7320. /* video */
  7321. {".mov", 4, "video/quicktime"},
  7322. {".mp4", 4, "video/mp4"},
  7323. {".mpeg", 5, "video/mpeg"},
  7324. {".mpg", 4, "video/mpeg"},
  7325. {".ogv", 4, "video/ogg"},
  7326. {".qt", 3, "video/quicktime"},
  7327. /* not registered types
  7328. * (http://reference.sitepoint.com/html/mime-types-full,
  7329. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7330. {".arj", 4, "application/x-arj-compressed"},
  7331. {".gz", 3, "application/x-gunzip"},
  7332. {".rar", 4, "application/x-arj-compressed"},
  7333. {".swf", 4, "application/x-shockwave-flash"},
  7334. {".tar", 4, "application/x-tar"},
  7335. {".tgz", 4, "application/x-tar-gz"},
  7336. {".torrent", 8, "application/x-bittorrent"},
  7337. {".ppt", 4, "application/x-mspowerpoint"},
  7338. {".xls", 4, "application/x-msexcel"},
  7339. {".zip", 4, "application/x-zip-compressed"},
  7340. {".aac",
  7341. 4,
  7342. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7343. {".aif", 4, "audio/x-aif"},
  7344. {".m3u", 4, "audio/x-mpegurl"},
  7345. {".mid", 4, "audio/x-midi"},
  7346. {".ra", 3, "audio/x-pn-realaudio"},
  7347. {".ram", 4, "audio/x-pn-realaudio"},
  7348. {".wav", 4, "audio/x-wav"},
  7349. {".bmp", 4, "image/bmp"},
  7350. {".ico", 4, "image/x-icon"},
  7351. {".pct", 4, "image/x-pct"},
  7352. {".pict", 5, "image/pict"},
  7353. {".rgb", 4, "image/x-rgb"},
  7354. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7355. {".asf", 4, "video/x-ms-asf"},
  7356. {".avi", 4, "video/x-msvideo"},
  7357. {".m4v", 4, "video/x-m4v"},
  7358. {NULL, 0, NULL}};
  7359. const char *
  7360. mg_get_builtin_mime_type(const char *path)
  7361. {
  7362. const char *ext;
  7363. size_t i, path_len;
  7364. path_len = strlen(path);
  7365. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7366. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7367. if ((path_len > builtin_mime_types[i].ext_len)
  7368. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7369. return builtin_mime_types[i].mime_type;
  7370. }
  7371. }
  7372. return "text/plain";
  7373. }
  7374. /* Look at the "path" extension and figure what mime type it has.
  7375. * Store mime type in the vector. */
  7376. static void
  7377. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7378. {
  7379. struct vec ext_vec, mime_vec;
  7380. const char *list, *ext;
  7381. size_t path_len;
  7382. path_len = strlen(path);
  7383. if ((conn == NULL) || (vec == NULL)) {
  7384. if (vec != NULL) {
  7385. memset(vec, '\0', sizeof(struct vec));
  7386. }
  7387. return;
  7388. }
  7389. /* Scan user-defined mime types first, in case user wants to
  7390. * override default mime types. */
  7391. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7392. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7393. /* ext now points to the path suffix */
  7394. ext = path + path_len - ext_vec.len;
  7395. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7396. *vec = mime_vec;
  7397. return;
  7398. }
  7399. }
  7400. vec->ptr = mg_get_builtin_mime_type(path);
  7401. vec->len = strlen(vec->ptr);
  7402. }
  7403. /* Stringify binary data. Output buffer must be twice as big as input,
  7404. * because each byte takes 2 bytes in string representation */
  7405. static void
  7406. bin2str(char *to, const unsigned char *p, size_t len)
  7407. {
  7408. static const char *hex = "0123456789abcdef";
  7409. for (; len--; p++) {
  7410. *to++ = hex[p[0] >> 4];
  7411. *to++ = hex[p[0] & 0x0f];
  7412. }
  7413. *to = '\0';
  7414. }
  7415. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7416. */
  7417. char *
  7418. mg_md5(char buf[33], ...)
  7419. {
  7420. md5_byte_t hash[16];
  7421. const char *p;
  7422. va_list ap;
  7423. md5_state_t ctx;
  7424. md5_init(&ctx);
  7425. va_start(ap, buf);
  7426. while ((p = va_arg(ap, const char *)) != NULL) {
  7427. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7428. }
  7429. va_end(ap);
  7430. md5_finish(&ctx, hash);
  7431. bin2str(buf, hash, sizeof(hash));
  7432. return buf;
  7433. }
  7434. /* Check the user's password, return 1 if OK */
  7435. static int
  7436. check_password(const char *method,
  7437. const char *ha1,
  7438. const char *uri,
  7439. const char *nonce,
  7440. const char *nc,
  7441. const char *cnonce,
  7442. const char *qop,
  7443. const char *response)
  7444. {
  7445. char ha2[32 + 1], expected_response[32 + 1];
  7446. /* Some of the parameters may be NULL */
  7447. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7448. || (qop == NULL) || (response == NULL)) {
  7449. return 0;
  7450. }
  7451. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7452. if (strlen(response) != 32) {
  7453. return 0;
  7454. }
  7455. mg_md5(ha2, method, ":", uri, NULL);
  7456. mg_md5(expected_response,
  7457. ha1,
  7458. ":",
  7459. nonce,
  7460. ":",
  7461. nc,
  7462. ":",
  7463. cnonce,
  7464. ":",
  7465. qop,
  7466. ":",
  7467. ha2,
  7468. NULL);
  7469. return mg_strcasecmp(response, expected_response) == 0;
  7470. }
  7471. #if !defined(NO_FILESYSTEMS)
  7472. /* Use the global passwords file, if specified by auth_gpass option,
  7473. * or search for .htpasswd in the requested directory. */
  7474. static void
  7475. open_auth_file(struct mg_connection *conn,
  7476. const char *path,
  7477. struct mg_file *filep)
  7478. {
  7479. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7480. char name[PATH_MAX];
  7481. const char *p, *e,
  7482. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7483. int truncated;
  7484. if (gpass != NULL) {
  7485. /* Use global passwords file */
  7486. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7487. #if defined(DEBUG)
  7488. /* Use mg_cry_internal here, since gpass has been
  7489. * configured. */
  7490. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7491. #endif
  7492. }
  7493. /* Important: using local struct mg_file to test path for
  7494. * is_directory flag. If filep is used, mg_stat() makes it
  7495. * appear as if auth file was opened.
  7496. * TODO(mid): Check if this is still required after rewriting
  7497. * mg_stat */
  7498. } else if (mg_stat(conn, path, &filep->stat)
  7499. && filep->stat.is_directory) {
  7500. mg_snprintf(conn,
  7501. &truncated,
  7502. name,
  7503. sizeof(name),
  7504. "%s/%s",
  7505. path,
  7506. PASSWORDS_FILE_NAME);
  7507. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7508. #if defined(DEBUG)
  7509. /* Don't use mg_cry_internal here, but only a trace, since
  7510. * this is a typical case. It will occur for every directory
  7511. * without a password file. */
  7512. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7513. #endif
  7514. }
  7515. } else {
  7516. /* Try to find .htpasswd in requested directory. */
  7517. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7518. if (e[0] == '/') {
  7519. break;
  7520. }
  7521. }
  7522. mg_snprintf(conn,
  7523. &truncated,
  7524. name,
  7525. sizeof(name),
  7526. "%.*s/%s",
  7527. (int)(e - p),
  7528. p,
  7529. PASSWORDS_FILE_NAME);
  7530. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7531. #if defined(DEBUG)
  7532. /* Don't use mg_cry_internal here, but only a trace, since
  7533. * this is a typical case. It will occur for every directory
  7534. * without a password file. */
  7535. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7536. #endif
  7537. }
  7538. }
  7539. }
  7540. }
  7541. #endif /* NO_FILESYSTEMS */
  7542. /* Parsed Authorization header */
  7543. struct ah {
  7544. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7545. };
  7546. /* Return 1 on success. Always initializes the ah structure. */
  7547. static int
  7548. parse_auth_header(struct mg_connection *conn,
  7549. char *buf,
  7550. size_t buf_size,
  7551. struct ah *ah)
  7552. {
  7553. char *name, *value, *s;
  7554. const char *auth_header;
  7555. uint64_t nonce;
  7556. if (!ah || !conn) {
  7557. return 0;
  7558. }
  7559. (void)memset(ah, 0, sizeof(*ah));
  7560. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7561. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7562. return 0;
  7563. }
  7564. /* Make modifiable copy of the auth header */
  7565. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7566. s = buf;
  7567. /* Parse authorization header */
  7568. for (;;) {
  7569. /* Gobble initial spaces */
  7570. while (isspace((unsigned char)*s)) {
  7571. s++;
  7572. }
  7573. name = skip_quoted(&s, "=", " ", 0);
  7574. /* Value is either quote-delimited, or ends at first comma or space.
  7575. */
  7576. if (s[0] == '\"') {
  7577. s++;
  7578. value = skip_quoted(&s, "\"", " ", '\\');
  7579. if (s[0] == ',') {
  7580. s++;
  7581. }
  7582. } else {
  7583. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7584. * uses spaces */
  7585. }
  7586. if (*name == '\0') {
  7587. break;
  7588. }
  7589. if (!strcmp(name, "username")) {
  7590. ah->user = value;
  7591. } else if (!strcmp(name, "cnonce")) {
  7592. ah->cnonce = value;
  7593. } else if (!strcmp(name, "response")) {
  7594. ah->response = value;
  7595. } else if (!strcmp(name, "uri")) {
  7596. ah->uri = value;
  7597. } else if (!strcmp(name, "qop")) {
  7598. ah->qop = value;
  7599. } else if (!strcmp(name, "nc")) {
  7600. ah->nc = value;
  7601. } else if (!strcmp(name, "nonce")) {
  7602. ah->nonce = value;
  7603. }
  7604. }
  7605. #if !defined(NO_NONCE_CHECK)
  7606. /* Read the nonce from the response. */
  7607. if (ah->nonce == NULL) {
  7608. return 0;
  7609. }
  7610. s = NULL;
  7611. nonce = strtoull(ah->nonce, &s, 10);
  7612. if ((s == NULL) || (*s != 0)) {
  7613. return 0;
  7614. }
  7615. /* Convert the nonce from the client to a number. */
  7616. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7617. /* The converted number corresponds to the time the nounce has been
  7618. * created. This should not be earlier than the server start. */
  7619. /* Server side nonce check is valuable in all situations but one:
  7620. * if the server restarts frequently, but the client should not see
  7621. * that, so the server should accept nonces from previous starts. */
  7622. /* However, the reasonable default is to not accept a nonce from a
  7623. * previous start, so if anyone changed the access rights between
  7624. * two restarts, a new login is required. */
  7625. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7626. /* nonce is from a previous start of the server and no longer valid
  7627. * (replay attack?) */
  7628. return 0;
  7629. }
  7630. /* Check if the nonce is too high, so it has not (yet) been used by the
  7631. * server. */
  7632. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7633. + conn->dom_ctx->nonce_count)) {
  7634. return 0;
  7635. }
  7636. #else
  7637. (void)nonce;
  7638. #endif
  7639. /* CGI needs it as REMOTE_USER */
  7640. if (ah->user != NULL) {
  7641. conn->request_info.remote_user =
  7642. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7643. } else {
  7644. return 0;
  7645. }
  7646. return 1;
  7647. }
  7648. static const char *
  7649. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7650. {
  7651. if (!filep) {
  7652. return NULL;
  7653. }
  7654. if (filep->access.fp != NULL) {
  7655. return fgets(buf, (int)size, filep->access.fp);
  7656. } else {
  7657. return NULL;
  7658. }
  7659. }
  7660. /* Define the initial recursion depth for procesesing htpasswd files that
  7661. * include other htpasswd
  7662. * (or even the same) files. It is not difficult to provide a file or files
  7663. * s.t. they force civetweb
  7664. * to infinitely recurse and then crash.
  7665. */
  7666. #define INITIAL_DEPTH 9
  7667. #if INITIAL_DEPTH <= 0
  7668. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7669. #endif
  7670. #if !defined(NO_FILESYSTEMS)
  7671. struct read_auth_file_struct {
  7672. struct mg_connection *conn;
  7673. struct ah ah;
  7674. const char *domain;
  7675. char buf[256 + 256 + 40];
  7676. const char *f_user;
  7677. const char *f_domain;
  7678. const char *f_ha1;
  7679. };
  7680. static int
  7681. read_auth_file(struct mg_file *filep,
  7682. struct read_auth_file_struct *workdata,
  7683. int depth)
  7684. {
  7685. int is_authorized = 0;
  7686. struct mg_file fp;
  7687. size_t l;
  7688. if (!filep || !workdata || (0 == depth)) {
  7689. return 0;
  7690. }
  7691. /* Loop over passwords file */
  7692. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7693. l = strlen(workdata->buf);
  7694. while (l > 0) {
  7695. if (isspace((unsigned char)workdata->buf[l - 1])
  7696. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7697. l--;
  7698. workdata->buf[l] = 0;
  7699. } else
  7700. break;
  7701. }
  7702. if (l < 1) {
  7703. continue;
  7704. }
  7705. workdata->f_user = workdata->buf;
  7706. if (workdata->f_user[0] == ':') {
  7707. /* user names may not contain a ':' and may not be empty,
  7708. * so lines starting with ':' may be used for a special purpose
  7709. */
  7710. if (workdata->f_user[1] == '#') {
  7711. /* :# is a comment */
  7712. continue;
  7713. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7714. if (mg_fopen(workdata->conn,
  7715. workdata->f_user + 9,
  7716. MG_FOPEN_MODE_READ,
  7717. &fp)) {
  7718. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7719. (void)mg_fclose(
  7720. &fp.access); /* ignore error on read only file */
  7721. /* No need to continue processing files once we have a
  7722. * match, since nothing will reset it back
  7723. * to 0.
  7724. */
  7725. if (is_authorized) {
  7726. return is_authorized;
  7727. }
  7728. } else {
  7729. mg_cry_internal(workdata->conn,
  7730. "%s: cannot open authorization file: %s",
  7731. __func__,
  7732. workdata->buf);
  7733. }
  7734. continue;
  7735. }
  7736. /* everything is invalid for the moment (might change in the
  7737. * future) */
  7738. mg_cry_internal(workdata->conn,
  7739. "%s: syntax error in authorization file: %s",
  7740. __func__,
  7741. workdata->buf);
  7742. continue;
  7743. }
  7744. workdata->f_domain = strchr(workdata->f_user, ':');
  7745. if (workdata->f_domain == NULL) {
  7746. mg_cry_internal(workdata->conn,
  7747. "%s: syntax error in authorization file: %s",
  7748. __func__,
  7749. workdata->buf);
  7750. continue;
  7751. }
  7752. *(char *)(workdata->f_domain) = 0;
  7753. (workdata->f_domain)++;
  7754. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7755. if (workdata->f_ha1 == NULL) {
  7756. mg_cry_internal(workdata->conn,
  7757. "%s: syntax error in authorization file: %s",
  7758. __func__,
  7759. workdata->buf);
  7760. continue;
  7761. }
  7762. *(char *)(workdata->f_ha1) = 0;
  7763. (workdata->f_ha1)++;
  7764. if (!strcmp(workdata->ah.user, workdata->f_user)
  7765. && !strcmp(workdata->domain, workdata->f_domain)) {
  7766. return check_password(workdata->conn->request_info.request_method,
  7767. workdata->f_ha1,
  7768. workdata->ah.uri,
  7769. workdata->ah.nonce,
  7770. workdata->ah.nc,
  7771. workdata->ah.cnonce,
  7772. workdata->ah.qop,
  7773. workdata->ah.response);
  7774. }
  7775. }
  7776. return is_authorized;
  7777. }
  7778. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7779. static int
  7780. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7781. {
  7782. struct read_auth_file_struct workdata;
  7783. char buf[MG_BUF_LEN];
  7784. if (!conn || !conn->dom_ctx) {
  7785. return 0;
  7786. }
  7787. memset(&workdata, 0, sizeof(workdata));
  7788. workdata.conn = conn;
  7789. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7790. return 0;
  7791. }
  7792. if (realm) {
  7793. workdata.domain = realm;
  7794. } else {
  7795. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7796. }
  7797. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7798. }
  7799. /* Public function to check http digest authentication header */
  7800. int
  7801. mg_check_digest_access_authentication(struct mg_connection *conn,
  7802. const char *realm,
  7803. const char *filename)
  7804. {
  7805. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7806. int auth;
  7807. if (!conn || !filename) {
  7808. return -1;
  7809. }
  7810. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7811. return -2;
  7812. }
  7813. auth = authorize(conn, &file, realm);
  7814. mg_fclose(&file.access);
  7815. return auth;
  7816. }
  7817. #endif /* NO_FILESYSTEMS */
  7818. /* Return 1 if request is authorised, 0 otherwise. */
  7819. static int
  7820. check_authorization(struct mg_connection *conn, const char *path)
  7821. {
  7822. #if !defined(NO_FILESYSTEMS)
  7823. char fname[PATH_MAX];
  7824. struct vec uri_vec, filename_vec;
  7825. const char *list;
  7826. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7827. int authorized = 1, truncated;
  7828. if (!conn || !conn->dom_ctx) {
  7829. return 0;
  7830. }
  7831. list = conn->dom_ctx->config[PROTECT_URI];
  7832. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7833. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7834. mg_snprintf(conn,
  7835. &truncated,
  7836. fname,
  7837. sizeof(fname),
  7838. "%.*s",
  7839. (int)filename_vec.len,
  7840. filename_vec.ptr);
  7841. if (truncated
  7842. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7843. mg_cry_internal(conn,
  7844. "%s: cannot open %s: %s",
  7845. __func__,
  7846. fname,
  7847. strerror(errno));
  7848. }
  7849. break;
  7850. }
  7851. }
  7852. if (!is_file_opened(&file.access)) {
  7853. open_auth_file(conn, path, &file);
  7854. }
  7855. if (is_file_opened(&file.access)) {
  7856. authorized = authorize(conn, &file, NULL);
  7857. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7858. }
  7859. return authorized;
  7860. #else
  7861. (void)conn;
  7862. (void)path;
  7863. return 1;
  7864. #endif /* NO_FILESYSTEMS */
  7865. }
  7866. /* Internal function. Assumes conn is valid */
  7867. static void
  7868. send_authorization_request(struct mg_connection *conn, const char *realm)
  7869. {
  7870. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7871. int trunc = 0;
  7872. char buf[128];
  7873. if (!realm) {
  7874. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7875. }
  7876. mg_lock_context(conn->phys_ctx);
  7877. nonce += conn->dom_ctx->nonce_count;
  7878. ++conn->dom_ctx->nonce_count;
  7879. mg_unlock_context(conn->phys_ctx);
  7880. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7881. conn->must_close = 1;
  7882. /* Create 401 response */
  7883. mg_response_header_start(conn, 401);
  7884. send_no_cache_header(conn);
  7885. send_additional_header(conn);
  7886. mg_response_header_add(conn, "Content-Length", "0", -1);
  7887. /* Content for "WWW-Authenticate" header */
  7888. mg_snprintf(conn,
  7889. &trunc,
  7890. buf,
  7891. sizeof(buf),
  7892. "Digest qop=\"auth\", realm=\"%s\", "
  7893. "nonce=\"%" UINT64_FMT "\"",
  7894. realm,
  7895. nonce);
  7896. if (!trunc) {
  7897. /* !trunc should always be true */
  7898. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7899. }
  7900. /* Send all headers */
  7901. mg_response_header_send(conn);
  7902. }
  7903. /* Interface function. Parameters are provided by the user, so do
  7904. * at least some basic checks.
  7905. */
  7906. int
  7907. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7908. const char *realm)
  7909. {
  7910. if (conn && conn->dom_ctx) {
  7911. send_authorization_request(conn, realm);
  7912. return 0;
  7913. }
  7914. return -1;
  7915. }
  7916. #if !defined(NO_FILES)
  7917. static int
  7918. is_authorized_for_put(struct mg_connection *conn)
  7919. {
  7920. if (conn) {
  7921. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7922. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7923. int ret = 0;
  7924. if (passfile != NULL
  7925. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7926. ret = authorize(conn, &file, NULL);
  7927. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7928. }
  7929. return ret;
  7930. }
  7931. return 0;
  7932. }
  7933. #endif
  7934. int
  7935. mg_modify_passwords_file(const char *fname,
  7936. const char *domain,
  7937. const char *user,
  7938. const char *pass)
  7939. {
  7940. int found, i;
  7941. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7942. FILE *fp, *fp2;
  7943. found = 0;
  7944. fp = fp2 = NULL;
  7945. /* Regard empty password as no password - remove user record. */
  7946. if ((pass != NULL) && (pass[0] == '\0')) {
  7947. pass = NULL;
  7948. }
  7949. /* Other arguments must not be empty */
  7950. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7951. return 0;
  7952. }
  7953. /* Using the given file format, user name and domain must not contain
  7954. * ':'
  7955. */
  7956. if (strchr(user, ':') != NULL) {
  7957. return 0;
  7958. }
  7959. if (strchr(domain, ':') != NULL) {
  7960. return 0;
  7961. }
  7962. /* Do not allow control characters like newline in user name and domain.
  7963. * Do not allow excessively long names either. */
  7964. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7965. if (iscntrl((unsigned char)user[i])) {
  7966. return 0;
  7967. }
  7968. }
  7969. if (user[i]) {
  7970. return 0;
  7971. }
  7972. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7973. if (iscntrl((unsigned char)domain[i])) {
  7974. return 0;
  7975. }
  7976. }
  7977. if (domain[i]) {
  7978. return 0;
  7979. }
  7980. /* The maximum length of the path to the password file is limited */
  7981. if ((strlen(fname) + 4) >= PATH_MAX) {
  7982. return 0;
  7983. }
  7984. /* Create a temporary file name. Length has been checked before. */
  7985. strcpy(tmp, fname);
  7986. strcat(tmp, ".tmp");
  7987. /* Create the file if does not exist */
  7988. /* Use of fopen here is OK, since fname is only ASCII */
  7989. if ((fp = fopen(fname, "a+")) != NULL) {
  7990. (void)fclose(fp);
  7991. }
  7992. /* Open the given file and temporary file */
  7993. if ((fp = fopen(fname, "r")) == NULL) {
  7994. return 0;
  7995. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7996. fclose(fp);
  7997. return 0;
  7998. }
  7999. /* Copy the stuff to temporary file */
  8000. while (fgets(line, sizeof(line), fp) != NULL) {
  8001. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  8002. continue;
  8003. }
  8004. u[255] = 0;
  8005. d[255] = 0;
  8006. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8007. found++;
  8008. if (pass != NULL) {
  8009. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8010. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8011. }
  8012. } else {
  8013. fprintf(fp2, "%s", line);
  8014. }
  8015. }
  8016. /* If new user, just add it */
  8017. if (!found && (pass != NULL)) {
  8018. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  8019. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  8020. }
  8021. /* Close files */
  8022. fclose(fp);
  8023. fclose(fp2);
  8024. /* Put the temp file in place of real file */
  8025. IGNORE_UNUSED_RESULT(remove(fname));
  8026. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  8027. return 1;
  8028. }
  8029. static int
  8030. is_valid_port(unsigned long port)
  8031. {
  8032. return (port <= 0xffff);
  8033. }
  8034. static int
  8035. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8036. {
  8037. struct addrinfo hints, *res, *ressave;
  8038. int func_ret = 0;
  8039. int gai_ret;
  8040. memset(&hints, 0, sizeof(struct addrinfo));
  8041. hints.ai_family = af;
  8042. if (!resolve_src) {
  8043. hints.ai_flags = AI_NUMERICHOST;
  8044. }
  8045. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8046. if (gai_ret != 0) {
  8047. /* gai_strerror could be used to convert gai_ret to a string */
  8048. /* POSIX return values: see
  8049. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8050. */
  8051. /* Windows return values: see
  8052. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8053. */
  8054. return 0;
  8055. }
  8056. ressave = res;
  8057. while (res) {
  8058. if ((dstlen >= (size_t)res->ai_addrlen)
  8059. && (res->ai_addr->sa_family == af)) {
  8060. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8061. func_ret = 1;
  8062. }
  8063. res = res->ai_next;
  8064. }
  8065. freeaddrinfo(ressave);
  8066. return func_ret;
  8067. }
  8068. static int
  8069. connect_socket(struct mg_context *ctx /* may be NULL */,
  8070. const char *host,
  8071. int port,
  8072. int use_ssl,
  8073. char *ebuf,
  8074. size_t ebuf_len,
  8075. SOCKET *sock /* output: socket, must not be NULL */,
  8076. union usa *sa /* output: socket address, must not be NULL */
  8077. )
  8078. {
  8079. int ip_ver = 0;
  8080. int conn_ret = -1;
  8081. int sockerr = 0;
  8082. *sock = INVALID_SOCKET;
  8083. memset(sa, 0, sizeof(*sa));
  8084. if (ebuf_len > 0) {
  8085. *ebuf = 0;
  8086. }
  8087. if (host == NULL) {
  8088. mg_snprintf(NULL,
  8089. NULL, /* No truncation check for ebuf */
  8090. ebuf,
  8091. ebuf_len,
  8092. "%s",
  8093. "NULL host");
  8094. return 0;
  8095. }
  8096. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8097. mg_snprintf(NULL,
  8098. NULL, /* No truncation check for ebuf */
  8099. ebuf,
  8100. ebuf_len,
  8101. "%s",
  8102. "invalid port");
  8103. return 0;
  8104. }
  8105. #if !defined(NO_SSL)
  8106. #if !defined(NO_SSL_DL)
  8107. #if defined(OPENSSL_API_1_1)
  8108. if (use_ssl && (TLS_client_method == NULL)) {
  8109. mg_snprintf(NULL,
  8110. NULL, /* No truncation check for ebuf */
  8111. ebuf,
  8112. ebuf_len,
  8113. "%s",
  8114. "SSL is not initialized");
  8115. return 0;
  8116. }
  8117. #else
  8118. if (use_ssl && (SSLv23_client_method == NULL)) {
  8119. mg_snprintf(NULL,
  8120. NULL, /* No truncation check for ebuf */
  8121. ebuf,
  8122. ebuf_len,
  8123. "%s",
  8124. "SSL is not initialized");
  8125. return 0;
  8126. }
  8127. #endif /* OPENSSL_API_1_1 */
  8128. #else
  8129. (void)use_ssl;
  8130. #endif /* NO_SSL_DL */
  8131. #else
  8132. (void)use_ssl;
  8133. #endif /* !defined(NO_SSL) */
  8134. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8135. sa->sin.sin_port = htons((uint16_t)port);
  8136. ip_ver = 4;
  8137. #if defined(USE_IPV6)
  8138. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8139. sa->sin6.sin6_port = htons((uint16_t)port);
  8140. ip_ver = 6;
  8141. } else if (host[0] == '[') {
  8142. /* While getaddrinfo on Windows will work with [::1],
  8143. * getaddrinfo on Linux only works with ::1 (without []). */
  8144. size_t l = strlen(host + 1);
  8145. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8146. if (h) {
  8147. h[l - 1] = 0;
  8148. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8149. sa->sin6.sin6_port = htons((uint16_t)port);
  8150. ip_ver = 6;
  8151. }
  8152. mg_free(h);
  8153. }
  8154. #endif
  8155. }
  8156. if (ip_ver == 0) {
  8157. mg_snprintf(NULL,
  8158. NULL, /* No truncation check for ebuf */
  8159. ebuf,
  8160. ebuf_len,
  8161. "%s",
  8162. "host not found");
  8163. return 0;
  8164. }
  8165. if (ip_ver == 4) {
  8166. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8167. }
  8168. #if defined(USE_IPV6)
  8169. else if (ip_ver == 6) {
  8170. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8171. }
  8172. #endif
  8173. #if 0 /* Not available as client */
  8174. #if defined(USE_X_DOM_SOCKET)
  8175. else if (ip_ver == 99) {
  8176. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8177. }
  8178. #endif
  8179. #endif
  8180. if (*sock == INVALID_SOCKET) {
  8181. mg_snprintf(NULL,
  8182. NULL, /* No truncation check for ebuf */
  8183. ebuf,
  8184. ebuf_len,
  8185. "socket(): %s",
  8186. strerror(ERRNO));
  8187. return 0;
  8188. }
  8189. if (0 != set_non_blocking_mode(*sock)) {
  8190. mg_snprintf(NULL,
  8191. NULL, /* No truncation check for ebuf */
  8192. ebuf,
  8193. ebuf_len,
  8194. "Cannot set socket to non-blocking: %s",
  8195. strerror(ERRNO));
  8196. closesocket(*sock);
  8197. *sock = INVALID_SOCKET;
  8198. return 0;
  8199. }
  8200. set_close_on_exec(*sock, NULL, ctx);
  8201. if (ip_ver == 4) {
  8202. /* connected with IPv4 */
  8203. conn_ret = connect(*sock,
  8204. (struct sockaddr *)((void *)&sa->sin),
  8205. sizeof(sa->sin));
  8206. }
  8207. #if defined(USE_IPV6)
  8208. else if (ip_ver == 6) {
  8209. /* connected with IPv6 */
  8210. conn_ret = connect(*sock,
  8211. (struct sockaddr *)((void *)&sa->sin6),
  8212. sizeof(sa->sin6));
  8213. }
  8214. #endif
  8215. if (conn_ret != 0) {
  8216. sockerr = ERRNO;
  8217. }
  8218. #if defined(_WIN32)
  8219. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8220. #else
  8221. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8222. #endif
  8223. /* Data for getsockopt */
  8224. void *psockerr = &sockerr;
  8225. int ret;
  8226. #if defined(_WIN32)
  8227. int len = (int)sizeof(sockerr);
  8228. #else
  8229. socklen_t len = (socklen_t)sizeof(sockerr);
  8230. #endif
  8231. /* Data for poll */
  8232. struct mg_pollfd pfd[1];
  8233. int pollres;
  8234. int ms_wait = 10000; /* 10 second timeout */
  8235. stop_flag_t nonstop;
  8236. STOP_FLAG_ASSIGN(&nonstop, 0);
  8237. /* For a non-blocking socket, the connect sequence is:
  8238. * 1) call connect (will not block)
  8239. * 2) wait until the socket is ready for writing (select or poll)
  8240. * 3) check connection state with getsockopt
  8241. */
  8242. pfd[0].fd = *sock;
  8243. pfd[0].events = POLLOUT;
  8244. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8245. if (pollres != 1) {
  8246. /* Not connected */
  8247. mg_snprintf(NULL,
  8248. NULL, /* No truncation check for ebuf */
  8249. ebuf,
  8250. ebuf_len,
  8251. "connect(%s:%d): timeout",
  8252. host,
  8253. port);
  8254. closesocket(*sock);
  8255. *sock = INVALID_SOCKET;
  8256. return 0;
  8257. }
  8258. #if defined(_WIN32)
  8259. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8260. #else
  8261. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8262. #endif
  8263. if ((ret == 0) && (sockerr == 0)) {
  8264. conn_ret = 0;
  8265. }
  8266. }
  8267. if (conn_ret != 0) {
  8268. /* Not connected */
  8269. mg_snprintf(NULL,
  8270. NULL, /* No truncation check for ebuf */
  8271. ebuf,
  8272. ebuf_len,
  8273. "connect(%s:%d): error %s",
  8274. host,
  8275. port,
  8276. strerror(sockerr));
  8277. closesocket(*sock);
  8278. *sock = INVALID_SOCKET;
  8279. return 0;
  8280. }
  8281. return 1;
  8282. }
  8283. int
  8284. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8285. {
  8286. static const char *dont_escape = "._-$,;~()";
  8287. static const char *hex = "0123456789abcdef";
  8288. char *pos = dst;
  8289. const char *end = dst + dst_len - 1;
  8290. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8291. if (isalnum((unsigned char)*src)
  8292. || (strchr(dont_escape, *src) != NULL)) {
  8293. *pos = *src;
  8294. } else if (pos + 2 < end) {
  8295. pos[0] = '%';
  8296. pos[1] = hex[(unsigned char)*src >> 4];
  8297. pos[2] = hex[(unsigned char)*src & 0xf];
  8298. pos += 2;
  8299. } else {
  8300. break;
  8301. }
  8302. }
  8303. *pos = '\0';
  8304. return (*src == '\0') ? (int)(pos - dst) : -1;
  8305. }
  8306. /* Return 0 on success, non-zero if an error occurs. */
  8307. static int
  8308. print_dir_entry(struct de *de)
  8309. {
  8310. size_t namesize, escsize, i;
  8311. char *href, *esc, *p;
  8312. char size[64], mod[64];
  8313. #if defined(REENTRANT_TIME)
  8314. struct tm _tm;
  8315. struct tm *tm = &_tm;
  8316. #else
  8317. struct tm *tm;
  8318. #endif
  8319. /* Estimate worst case size for encoding and escaping */
  8320. namesize = strlen(de->file_name) + 1;
  8321. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8322. href = (char *)mg_malloc(namesize * 3 + escsize);
  8323. if (href == NULL) {
  8324. return -1;
  8325. }
  8326. mg_url_encode(de->file_name, href, namesize * 3);
  8327. esc = NULL;
  8328. if (escsize > 0) {
  8329. /* HTML escaping needed */
  8330. esc = href + namesize * 3;
  8331. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8332. mg_strlcpy(p, de->file_name + i, 2);
  8333. if (*p == '&') {
  8334. strcpy(p, "&amp;");
  8335. } else if (*p == '<') {
  8336. strcpy(p, "&lt;");
  8337. } else if (*p == '>') {
  8338. strcpy(p, "&gt;");
  8339. }
  8340. }
  8341. }
  8342. if (de->file.is_directory) {
  8343. mg_snprintf(de->conn,
  8344. NULL, /* Buffer is big enough */
  8345. size,
  8346. sizeof(size),
  8347. "%s",
  8348. "[DIRECTORY]");
  8349. } else {
  8350. /* We use (signed) cast below because MSVC 6 compiler cannot
  8351. * convert unsigned __int64 to double. Sigh. */
  8352. if (de->file.size < 1024) {
  8353. mg_snprintf(de->conn,
  8354. NULL, /* Buffer is big enough */
  8355. size,
  8356. sizeof(size),
  8357. "%d",
  8358. (int)de->file.size);
  8359. } else if (de->file.size < 0x100000) {
  8360. mg_snprintf(de->conn,
  8361. NULL, /* Buffer is big enough */
  8362. size,
  8363. sizeof(size),
  8364. "%.1fk",
  8365. (double)de->file.size / 1024.0);
  8366. } else if (de->file.size < 0x40000000) {
  8367. mg_snprintf(de->conn,
  8368. NULL, /* Buffer is big enough */
  8369. size,
  8370. sizeof(size),
  8371. "%.1fM",
  8372. (double)de->file.size / 1048576);
  8373. } else {
  8374. mg_snprintf(de->conn,
  8375. NULL, /* Buffer is big enough */
  8376. size,
  8377. sizeof(size),
  8378. "%.1fG",
  8379. (double)de->file.size / 1073741824);
  8380. }
  8381. }
  8382. /* Note: mg_snprintf will not cause a buffer overflow above.
  8383. * So, string truncation checks are not required here. */
  8384. #if defined(REENTRANT_TIME)
  8385. localtime_r(&de->file.last_modified, tm);
  8386. #else
  8387. tm = localtime(&de->file.last_modified);
  8388. #endif
  8389. if (tm != NULL) {
  8390. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8391. } else {
  8392. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8393. mod[sizeof(mod) - 1] = '\0';
  8394. }
  8395. mg_printf(de->conn,
  8396. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8397. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8398. href,
  8399. de->file.is_directory ? "/" : "",
  8400. esc ? esc : de->file_name,
  8401. de->file.is_directory ? "/" : "",
  8402. mod,
  8403. size);
  8404. mg_free(href);
  8405. return 0;
  8406. }
  8407. /* This function is called from send_directory() and used for
  8408. * sorting directory entries by size, or name, or modification time.
  8409. * On windows, __cdecl specification is needed in case if project is built
  8410. * with __stdcall convention. qsort always requires __cdels callback. */
  8411. static int WINCDECL
  8412. compare_dir_entries(const void *p1, const void *p2)
  8413. {
  8414. if (p1 && p2) {
  8415. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8416. const char *query_string = a->conn->request_info.query_string;
  8417. int cmp_result = 0;
  8418. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8419. query_string = "n";
  8420. }
  8421. if (a->file.is_directory && !b->file.is_directory) {
  8422. return -1; /* Always put directories on top */
  8423. } else if (!a->file.is_directory && b->file.is_directory) {
  8424. return 1; /* Always put directories on top */
  8425. } else if (*query_string == 'n') {
  8426. cmp_result = strcmp(a->file_name, b->file_name);
  8427. } else if (*query_string == 's') {
  8428. cmp_result = (a->file.size == b->file.size)
  8429. ? 0
  8430. : ((a->file.size > b->file.size) ? 1 : -1);
  8431. } else if (*query_string == 'd') {
  8432. cmp_result =
  8433. (a->file.last_modified == b->file.last_modified)
  8434. ? 0
  8435. : ((a->file.last_modified > b->file.last_modified) ? 1
  8436. : -1);
  8437. }
  8438. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8439. }
  8440. return 0;
  8441. }
  8442. static int
  8443. must_hide_file(struct mg_connection *conn, const char *path)
  8444. {
  8445. if (conn && conn->dom_ctx) {
  8446. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8447. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8448. return (match_prefix_strlen(pw_pattern, path) > 0)
  8449. || (match_prefix_strlen(pattern, path) > 0);
  8450. }
  8451. return 0;
  8452. }
  8453. #if !defined(NO_FILESYSTEMS)
  8454. static int
  8455. scan_directory(struct mg_connection *conn,
  8456. const char *dir,
  8457. void *data,
  8458. int (*cb)(struct de *, void *))
  8459. {
  8460. char path[PATH_MAX];
  8461. struct dirent *dp;
  8462. DIR *dirp;
  8463. struct de de;
  8464. int truncated;
  8465. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8466. return 0;
  8467. } else {
  8468. de.conn = conn;
  8469. while ((dp = mg_readdir(dirp)) != NULL) {
  8470. /* Do not show current dir and hidden files */
  8471. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8472. || must_hide_file(conn, dp->d_name)) {
  8473. continue;
  8474. }
  8475. mg_snprintf(
  8476. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8477. /* If we don't memset stat structure to zero, mtime will have
  8478. * garbage and strftime() will segfault later on in
  8479. * print_dir_entry(). memset is required only if mg_stat()
  8480. * fails. For more details, see
  8481. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8482. memset(&de.file, 0, sizeof(de.file));
  8483. if (truncated) {
  8484. /* If the path is not complete, skip processing. */
  8485. continue;
  8486. }
  8487. if (!mg_stat(conn, path, &de.file)) {
  8488. mg_cry_internal(conn,
  8489. "%s: mg_stat(%s) failed: %s",
  8490. __func__,
  8491. path,
  8492. strerror(ERRNO));
  8493. }
  8494. de.file_name = dp->d_name;
  8495. if (cb(&de, data)) {
  8496. /* stopped */
  8497. break;
  8498. }
  8499. }
  8500. (void)mg_closedir(dirp);
  8501. }
  8502. return 1;
  8503. }
  8504. #endif /* NO_FILESYSTEMS */
  8505. #if !defined(NO_FILES)
  8506. static int
  8507. remove_directory(struct mg_connection *conn, const char *dir)
  8508. {
  8509. char path[PATH_MAX];
  8510. struct dirent *dp;
  8511. DIR *dirp;
  8512. struct de de;
  8513. int truncated;
  8514. int ok = 1;
  8515. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8516. return 0;
  8517. } else {
  8518. de.conn = conn;
  8519. while ((dp = mg_readdir(dirp)) != NULL) {
  8520. /* Do not show current dir (but show hidden files as they will
  8521. * also be removed) */
  8522. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8523. continue;
  8524. }
  8525. mg_snprintf(
  8526. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8527. /* If we don't memset stat structure to zero, mtime will have
  8528. * garbage and strftime() will segfault later on in
  8529. * print_dir_entry(). memset is required only if mg_stat()
  8530. * fails. For more details, see
  8531. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8532. memset(&de.file, 0, sizeof(de.file));
  8533. if (truncated) {
  8534. /* Do not delete anything shorter */
  8535. ok = 0;
  8536. continue;
  8537. }
  8538. if (!mg_stat(conn, path, &de.file)) {
  8539. mg_cry_internal(conn,
  8540. "%s: mg_stat(%s) failed: %s",
  8541. __func__,
  8542. path,
  8543. strerror(ERRNO));
  8544. ok = 0;
  8545. }
  8546. if (de.file.is_directory) {
  8547. if (remove_directory(conn, path) == 0) {
  8548. ok = 0;
  8549. }
  8550. } else {
  8551. /* This will fail file is the file is in memory */
  8552. if (mg_remove(conn, path) == 0) {
  8553. ok = 0;
  8554. }
  8555. }
  8556. }
  8557. (void)mg_closedir(dirp);
  8558. IGNORE_UNUSED_RESULT(rmdir(dir));
  8559. }
  8560. return ok;
  8561. }
  8562. #endif
  8563. struct dir_scan_data {
  8564. struct de *entries;
  8565. size_t num_entries;
  8566. size_t arr_size;
  8567. };
  8568. #if !defined(NO_FILESYSTEMS)
  8569. static int
  8570. dir_scan_callback(struct de *de, void *data)
  8571. {
  8572. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8573. struct de *entries = dsd->entries;
  8574. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8575. /* Here "entries" is a temporary pointer and can be replaced,
  8576. * "dsd->entries" is the original pointer */
  8577. entries =
  8578. (struct de *)mg_realloc(entries,
  8579. dsd->arr_size * 2 * sizeof(entries[0]));
  8580. if (entries == NULL) {
  8581. /* stop scan */
  8582. return 1;
  8583. }
  8584. dsd->entries = entries;
  8585. dsd->arr_size *= 2;
  8586. }
  8587. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8588. if (entries[dsd->num_entries].file_name == NULL) {
  8589. /* stop scan */
  8590. return 1;
  8591. }
  8592. entries[dsd->num_entries].file = de->file;
  8593. entries[dsd->num_entries].conn = de->conn;
  8594. dsd->num_entries++;
  8595. return 0;
  8596. }
  8597. static void
  8598. handle_directory_request(struct mg_connection *conn, const char *dir)
  8599. {
  8600. size_t i;
  8601. int sort_direction;
  8602. struct dir_scan_data data = {NULL, 0, 128};
  8603. char date[64], *esc, *p;
  8604. const char *title;
  8605. time_t curtime = time(NULL);
  8606. if (!conn) {
  8607. return;
  8608. }
  8609. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8610. mg_send_http_error(conn,
  8611. 500,
  8612. "Error: Cannot open directory\nopendir(%s): %s",
  8613. dir,
  8614. strerror(ERRNO));
  8615. return;
  8616. }
  8617. gmt_time_string(date, sizeof(date), &curtime);
  8618. esc = NULL;
  8619. title = conn->request_info.local_uri;
  8620. if (title[strcspn(title, "&<>")]) {
  8621. /* HTML escaping needed */
  8622. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8623. if (esc) {
  8624. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8625. mg_strlcpy(p, title + i, 2);
  8626. if (*p == '&') {
  8627. strcpy(p, "&amp;");
  8628. } else if (*p == '<') {
  8629. strcpy(p, "&lt;");
  8630. } else if (*p == '>') {
  8631. strcpy(p, "&gt;");
  8632. }
  8633. }
  8634. } else {
  8635. title = "";
  8636. }
  8637. }
  8638. sort_direction = ((conn->request_info.query_string != NULL)
  8639. && (conn->request_info.query_string[0] != '\0')
  8640. && (conn->request_info.query_string[1] == 'd'))
  8641. ? 'a'
  8642. : 'd';
  8643. conn->must_close = 1;
  8644. /* Create 200 OK response */
  8645. mg_response_header_start(conn, 200);
  8646. send_static_cache_header(conn);
  8647. send_additional_header(conn);
  8648. mg_response_header_add(conn,
  8649. "Content-Type",
  8650. "text/html; charset=utf-8",
  8651. -1);
  8652. /* Send all headers */
  8653. mg_response_header_send(conn);
  8654. /* Body */
  8655. mg_printf(conn,
  8656. "<html><head><title>Index of %s</title>"
  8657. "<style>th {text-align: left;}</style></head>"
  8658. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8659. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8660. "<th><a href=\"?d%c\">Modified</a></th>"
  8661. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8662. "<tr><td colspan=\"3\"><hr></td></tr>",
  8663. esc ? esc : title,
  8664. esc ? esc : title,
  8665. sort_direction,
  8666. sort_direction,
  8667. sort_direction);
  8668. mg_free(esc);
  8669. /* Print first entry - link to a parent directory */
  8670. mg_printf(conn,
  8671. "<tr><td><a href=\"%s\">%s</a></td>"
  8672. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8673. "..",
  8674. "Parent directory",
  8675. "-",
  8676. "-");
  8677. /* Sort and print directory entries */
  8678. if (data.entries != NULL) {
  8679. qsort(data.entries,
  8680. data.num_entries,
  8681. sizeof(data.entries[0]),
  8682. compare_dir_entries);
  8683. for (i = 0; i < data.num_entries; i++) {
  8684. print_dir_entry(&data.entries[i]);
  8685. mg_free(data.entries[i].file_name);
  8686. }
  8687. mg_free(data.entries);
  8688. }
  8689. mg_printf(conn, "%s", "</table></pre></body></html>");
  8690. conn->status_code = 200;
  8691. }
  8692. #endif /* NO_FILESYSTEMS */
  8693. /* Send len bytes from the opened file to the client. */
  8694. static void
  8695. send_file_data(struct mg_connection *conn,
  8696. struct mg_file *filep,
  8697. int64_t offset,
  8698. int64_t len)
  8699. {
  8700. char buf[MG_BUF_LEN];
  8701. int to_read, num_read, num_written;
  8702. int64_t size;
  8703. if (!filep || !conn) {
  8704. return;
  8705. }
  8706. /* Sanity check the offset */
  8707. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8708. : (int64_t)(filep->stat.size);
  8709. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8710. if (len > 0 && filep->access.fp != NULL) {
  8711. /* file stored on disk */
  8712. #if defined(__linux__)
  8713. /* sendfile is only available for Linux */
  8714. if ((conn->ssl == 0) && (conn->throttle == 0)
  8715. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8716. "yes"))) {
  8717. off_t sf_offs = (off_t)offset;
  8718. ssize_t sf_sent;
  8719. int sf_file = fileno(filep->access.fp);
  8720. int loop_cnt = 0;
  8721. do {
  8722. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8723. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8724. size_t sf_tosend =
  8725. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8726. sf_sent =
  8727. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8728. if (sf_sent > 0) {
  8729. len -= sf_sent;
  8730. offset += sf_sent;
  8731. } else if (loop_cnt == 0) {
  8732. /* This file can not be sent using sendfile.
  8733. * This might be the case for pseudo-files in the
  8734. * /sys/ and /proc/ file system.
  8735. * Use the regular user mode copy code instead. */
  8736. break;
  8737. } else if (sf_sent == 0) {
  8738. /* No error, but 0 bytes sent. May be EOF? */
  8739. return;
  8740. }
  8741. loop_cnt++;
  8742. } while ((len > 0) && (sf_sent >= 0));
  8743. if (sf_sent > 0) {
  8744. return; /* OK */
  8745. }
  8746. /* sf_sent<0 means error, thus fall back to the classic way */
  8747. /* This is always the case, if sf_file is not a "normal" file,
  8748. * e.g., for sending data from the output of a CGI process. */
  8749. offset = (int64_t)sf_offs;
  8750. }
  8751. #endif
  8752. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8753. mg_cry_internal(conn,
  8754. "%s: fseeko() failed: %s",
  8755. __func__,
  8756. strerror(ERRNO));
  8757. mg_send_http_error(
  8758. conn,
  8759. 500,
  8760. "%s",
  8761. "Error: Unable to access file at requested position.");
  8762. } else {
  8763. while (len > 0) {
  8764. /* Calculate how much to read from the file in the buffer */
  8765. to_read = sizeof(buf);
  8766. if ((int64_t)to_read > len) {
  8767. to_read = (int)len;
  8768. }
  8769. /* Read from file, exit the loop on error */
  8770. if ((num_read =
  8771. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8772. <= 0) {
  8773. break;
  8774. }
  8775. /* Send read bytes to the client, exit the loop on error */
  8776. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8777. != num_read) {
  8778. break;
  8779. }
  8780. /* Both read and were successful, adjust counters */
  8781. len -= num_written;
  8782. }
  8783. }
  8784. }
  8785. }
  8786. static int
  8787. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8788. {
  8789. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8790. }
  8791. static void
  8792. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8793. {
  8794. if ((filestat != NULL) && (buf != NULL)) {
  8795. mg_snprintf(NULL,
  8796. NULL, /* All calls to construct_etag use 64 byte buffer */
  8797. buf,
  8798. buf_len,
  8799. "\"%lx.%" INT64_FMT "\"",
  8800. (unsigned long)filestat->last_modified,
  8801. filestat->size);
  8802. }
  8803. }
  8804. static void
  8805. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8806. {
  8807. if (filep != NULL && filep->fp != NULL) {
  8808. #if defined(_WIN32)
  8809. (void)conn; /* Unused. */
  8810. #else
  8811. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8812. mg_cry_internal(conn,
  8813. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8814. __func__,
  8815. strerror(ERRNO));
  8816. }
  8817. #endif
  8818. }
  8819. }
  8820. #if defined(USE_ZLIB)
  8821. #include "mod_zlib.inl"
  8822. #endif
  8823. #if !defined(NO_FILESYSTEMS)
  8824. static void
  8825. handle_static_file_request(struct mg_connection *conn,
  8826. const char *path,
  8827. struct mg_file *filep,
  8828. const char *mime_type,
  8829. const char *additional_headers)
  8830. {
  8831. char lm[64], etag[64];
  8832. char range[128]; /* large enough, so there will be no overflow */
  8833. const char *range_hdr;
  8834. int64_t cl, r1, r2;
  8835. struct vec mime_vec;
  8836. int n, truncated;
  8837. char gz_path[PATH_MAX];
  8838. const char *encoding = 0;
  8839. const char *origin_hdr;
  8840. const char *cors_orig_cfg;
  8841. const char *cors1, *cors2;
  8842. int is_head_request;
  8843. #if defined(USE_ZLIB)
  8844. /* Compression is allowed, unless there is a reason not to use
  8845. * compression. If the file is already compressed, too small or a
  8846. * "range" request was made, on the fly compression is not possible. */
  8847. int allow_on_the_fly_compression = 1;
  8848. #endif
  8849. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8850. return;
  8851. }
  8852. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8853. if (mime_type == NULL) {
  8854. get_mime_type(conn, path, &mime_vec);
  8855. } else {
  8856. mime_vec.ptr = mime_type;
  8857. mime_vec.len = strlen(mime_type);
  8858. }
  8859. if (filep->stat.size > INT64_MAX) {
  8860. mg_send_http_error(conn,
  8861. 500,
  8862. "Error: File size is too large to send\n%" INT64_FMT,
  8863. filep->stat.size);
  8864. return;
  8865. }
  8866. cl = (int64_t)filep->stat.size;
  8867. conn->status_code = 200;
  8868. range[0] = '\0';
  8869. #if defined(USE_ZLIB)
  8870. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8871. * it's important to rewrite the filename after resolving
  8872. * the mime type from it, to preserve the actual file's type */
  8873. if (!conn->accept_gzip) {
  8874. allow_on_the_fly_compression = 0;
  8875. }
  8876. #endif
  8877. /* Check if there is a range header */
  8878. range_hdr = mg_get_header(conn, "Range");
  8879. /* For gzipped files, add *.gz */
  8880. if (filep->stat.is_gzipped) {
  8881. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8882. if (truncated) {
  8883. mg_send_http_error(conn,
  8884. 500,
  8885. "Error: Path of zipped file too long (%s)",
  8886. path);
  8887. return;
  8888. }
  8889. path = gz_path;
  8890. encoding = "gzip";
  8891. #if defined(USE_ZLIB)
  8892. /* File is already compressed. No "on the fly" compression. */
  8893. allow_on_the_fly_compression = 0;
  8894. #endif
  8895. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8896. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8897. struct mg_file_stat file_stat;
  8898. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8899. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8900. && !file_stat.is_directory) {
  8901. file_stat.is_gzipped = 1;
  8902. filep->stat = file_stat;
  8903. cl = (int64_t)filep->stat.size;
  8904. path = gz_path;
  8905. encoding = "gzip";
  8906. #if defined(USE_ZLIB)
  8907. /* File is already compressed. No "on the fly" compression. */
  8908. allow_on_the_fly_compression = 0;
  8909. #endif
  8910. }
  8911. }
  8912. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8913. mg_send_http_error(conn,
  8914. 500,
  8915. "Error: Cannot open file\nfopen(%s): %s",
  8916. path,
  8917. strerror(ERRNO));
  8918. return;
  8919. }
  8920. fclose_on_exec(&filep->access, conn);
  8921. /* If "Range" request was made: parse header, send only selected part
  8922. * of the file. */
  8923. r1 = r2 = 0;
  8924. if ((range_hdr != NULL)
  8925. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8926. && (r2 >= 0)) {
  8927. /* actually, range requests don't play well with a pre-gzipped
  8928. * file (since the range is specified in the uncompressed space) */
  8929. if (filep->stat.is_gzipped) {
  8930. mg_send_http_error(
  8931. conn,
  8932. 416, /* 416 = Range Not Satisfiable */
  8933. "%s",
  8934. "Error: Range requests in gzipped files are not supported");
  8935. (void)mg_fclose(
  8936. &filep->access); /* ignore error on read only file */
  8937. return;
  8938. }
  8939. conn->status_code = 206;
  8940. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8941. mg_snprintf(conn,
  8942. NULL, /* range buffer is big enough */
  8943. range,
  8944. sizeof(range),
  8945. "bytes "
  8946. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8947. r1,
  8948. r1 + cl - 1,
  8949. filep->stat.size);
  8950. #if defined(USE_ZLIB)
  8951. /* Do not compress ranges. */
  8952. allow_on_the_fly_compression = 0;
  8953. #endif
  8954. }
  8955. /* Do not compress small files. Small files do not benefit from file
  8956. * compression, but there is still some overhead. */
  8957. #if defined(USE_ZLIB)
  8958. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8959. /* File is below the size limit. */
  8960. allow_on_the_fly_compression = 0;
  8961. }
  8962. #endif
  8963. /* Standard CORS header */
  8964. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8965. origin_hdr = mg_get_header(conn, "Origin");
  8966. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8967. /* Cross-origin resource sharing (CORS), see
  8968. * http://www.html5rocks.com/en/tutorials/cors/,
  8969. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8970. * -
  8971. * preflight is not supported for files. */
  8972. cors1 = "Access-Control-Allow-Origin";
  8973. cors2 = cors_orig_cfg;
  8974. } else {
  8975. cors1 = cors2 = "";
  8976. }
  8977. /* Prepare Etag, and Last-Modified headers. */
  8978. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8979. construct_etag(etag, sizeof(etag), &filep->stat);
  8980. /* Create 2xx (200, 206) response */
  8981. mg_response_header_start(conn, conn->status_code);
  8982. send_static_cache_header(conn);
  8983. send_additional_header(conn);
  8984. mg_response_header_add(conn,
  8985. "Content-Type",
  8986. mime_vec.ptr,
  8987. (int)mime_vec.len);
  8988. if (cors1[0] != 0) {
  8989. mg_response_header_add(conn, cors1, cors2, -1);
  8990. }
  8991. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8992. mg_response_header_add(conn, "Etag", etag, -1);
  8993. #if defined(USE_ZLIB)
  8994. /* On the fly compression allowed */
  8995. if (allow_on_the_fly_compression) {
  8996. /* For on the fly compression, we don't know the content size in
  8997. * advance, so we have to use chunked encoding */
  8998. encoding = "gzip";
  8999. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9000. /* HTTP/2 is always using "chunks" (frames) */
  9001. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9002. }
  9003. } else
  9004. #endif
  9005. {
  9006. /* Without on-the-fly compression, we know the content-length
  9007. * and we can use ranges (with on-the-fly compression we cannot).
  9008. * So we send these response headers only in this case. */
  9009. char len[32];
  9010. int trunc = 0;
  9011. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9012. if (!trunc) {
  9013. mg_response_header_add(conn, "Content-Length", len, -1);
  9014. }
  9015. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9016. }
  9017. if (encoding) {
  9018. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9019. }
  9020. if (range[0] != 0) {
  9021. mg_response_header_add(conn, "Content-Range", range, -1);
  9022. }
  9023. /* The code above does not add any header starting with X- to make
  9024. * sure no one of the additional_headers is included twice */
  9025. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9026. mg_response_header_add_lines(conn, additional_headers);
  9027. }
  9028. /* Send all headers */
  9029. mg_response_header_send(conn);
  9030. if (!is_head_request) {
  9031. #if defined(USE_ZLIB)
  9032. if (allow_on_the_fly_compression) {
  9033. /* Compress and send */
  9034. send_compressed_data(conn, filep);
  9035. } else
  9036. #endif
  9037. {
  9038. /* Send file directly */
  9039. send_file_data(conn, filep, r1, cl);
  9040. }
  9041. }
  9042. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9043. }
  9044. int
  9045. mg_send_file_body(struct mg_connection *conn, const char *path)
  9046. {
  9047. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9048. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9049. return -1;
  9050. }
  9051. fclose_on_exec(&file.access, conn);
  9052. send_file_data(conn, &file, 0, INT64_MAX);
  9053. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9054. return 0; /* >= 0 for OK */
  9055. }
  9056. #endif /* NO_FILESYSTEMS */
  9057. #if !defined(NO_CACHING)
  9058. /* Return True if we should reply 304 Not Modified. */
  9059. static int
  9060. is_not_modified(const struct mg_connection *conn,
  9061. const struct mg_file_stat *filestat)
  9062. {
  9063. char etag[64];
  9064. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9065. const char *inm = mg_get_header(conn, "If-None-Match");
  9066. construct_etag(etag, sizeof(etag), filestat);
  9067. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9068. || ((ims != NULL)
  9069. && (filestat->last_modified <= parse_date_string(ims)));
  9070. }
  9071. static void
  9072. handle_not_modified_static_file_request(struct mg_connection *conn,
  9073. struct mg_file *filep)
  9074. {
  9075. char lm[64], etag[64];
  9076. if ((conn == NULL) || (filep == NULL)) {
  9077. return;
  9078. }
  9079. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9080. construct_etag(etag, sizeof(etag), &filep->stat);
  9081. /* Create 304 "not modified" response */
  9082. mg_response_header_start(conn, 304);
  9083. send_static_cache_header(conn);
  9084. send_additional_header(conn);
  9085. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9086. mg_response_header_add(conn, "Etag", etag, -1);
  9087. /* Send all headers */
  9088. mg_response_header_send(conn);
  9089. }
  9090. #endif
  9091. #if !defined(NO_FILESYSTEMS)
  9092. void
  9093. mg_send_file(struct mg_connection *conn, const char *path)
  9094. {
  9095. mg_send_mime_file2(conn, path, NULL, NULL);
  9096. }
  9097. void
  9098. mg_send_mime_file(struct mg_connection *conn,
  9099. const char *path,
  9100. const char *mime_type)
  9101. {
  9102. mg_send_mime_file2(conn, path, mime_type, NULL);
  9103. }
  9104. void
  9105. mg_send_mime_file2(struct mg_connection *conn,
  9106. const char *path,
  9107. const char *mime_type,
  9108. const char *additional_headers)
  9109. {
  9110. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9111. if (!conn) {
  9112. /* No conn */
  9113. return;
  9114. }
  9115. if (mg_stat(conn, path, &file.stat)) {
  9116. #if !defined(NO_CACHING)
  9117. if (is_not_modified(conn, &file.stat)) {
  9118. /* Send 304 "Not Modified" - this must not send any body data */
  9119. handle_not_modified_static_file_request(conn, &file);
  9120. } else
  9121. #endif /* NO_CACHING */
  9122. if (file.stat.is_directory) {
  9123. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9124. "yes")) {
  9125. handle_directory_request(conn, path);
  9126. } else {
  9127. mg_send_http_error(conn,
  9128. 403,
  9129. "%s",
  9130. "Error: Directory listing denied");
  9131. }
  9132. } else {
  9133. handle_static_file_request(
  9134. conn, path, &file, mime_type, additional_headers);
  9135. }
  9136. } else {
  9137. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9138. }
  9139. }
  9140. /* For a given PUT path, create all intermediate subdirectories.
  9141. * Return 0 if the path itself is a directory.
  9142. * Return 1 if the path leads to a file.
  9143. * Return -1 for if the path is too long.
  9144. * Return -2 if path can not be created.
  9145. */
  9146. static int
  9147. put_dir(struct mg_connection *conn, const char *path)
  9148. {
  9149. char buf[PATH_MAX];
  9150. const char *s, *p;
  9151. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9152. size_t len;
  9153. int res = 1;
  9154. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9155. len = (size_t)(p - path);
  9156. if (len >= sizeof(buf)) {
  9157. /* path too long */
  9158. res = -1;
  9159. break;
  9160. }
  9161. memcpy(buf, path, len);
  9162. buf[len] = '\0';
  9163. /* Try to create intermediate directory */
  9164. DEBUG_TRACE("mkdir(%s)", buf);
  9165. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9166. /* path does not exixt and can not be created */
  9167. res = -2;
  9168. break;
  9169. }
  9170. /* Is path itself a directory? */
  9171. if (p[1] == '\0') {
  9172. res = 0;
  9173. }
  9174. }
  9175. return res;
  9176. }
  9177. static void
  9178. remove_bad_file(const struct mg_connection *conn, const char *path)
  9179. {
  9180. int r = mg_remove(conn, path);
  9181. if (r != 0) {
  9182. mg_cry_internal(conn,
  9183. "%s: Cannot remove invalid file %s",
  9184. __func__,
  9185. path);
  9186. }
  9187. }
  9188. long long
  9189. mg_store_body(struct mg_connection *conn, const char *path)
  9190. {
  9191. char buf[MG_BUF_LEN];
  9192. long long len = 0;
  9193. int ret, n;
  9194. struct mg_file fi;
  9195. if (conn->consumed_content != 0) {
  9196. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9197. return -11;
  9198. }
  9199. ret = put_dir(conn, path);
  9200. if (ret < 0) {
  9201. /* -1 for path too long,
  9202. * -2 for path can not be created. */
  9203. return ret;
  9204. }
  9205. if (ret != 1) {
  9206. /* Return 0 means, path itself is a directory. */
  9207. return 0;
  9208. }
  9209. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9210. return -12;
  9211. }
  9212. ret = mg_read(conn, buf, sizeof(buf));
  9213. while (ret > 0) {
  9214. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9215. if (n != ret) {
  9216. (void)mg_fclose(
  9217. &fi.access); /* File is bad and will be removed anyway. */
  9218. remove_bad_file(conn, path);
  9219. return -13;
  9220. }
  9221. len += ret;
  9222. ret = mg_read(conn, buf, sizeof(buf));
  9223. }
  9224. /* File is open for writing. If fclose fails, there was probably an
  9225. * error flushing the buffer to disk, so the file on disk might be
  9226. * broken. Delete it and return an error to the caller. */
  9227. if (mg_fclose(&fi.access) != 0) {
  9228. remove_bad_file(conn, path);
  9229. return -14;
  9230. }
  9231. return len;
  9232. }
  9233. #endif /* NO_FILESYSTEMS */
  9234. /* Parse a buffer:
  9235. * Forward the string pointer till the end of a word, then
  9236. * terminate it and forward till the begin of the next word.
  9237. */
  9238. static int
  9239. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9240. {
  9241. /* Forward until a space is found - use isgraph here */
  9242. /* See http://www.cplusplus.com/reference/cctype/ */
  9243. while (isgraph((unsigned char)**ppw)) {
  9244. (*ppw)++;
  9245. }
  9246. /* Check end of word */
  9247. if (eol) {
  9248. /* must be a end of line */
  9249. if ((**ppw != '\r') && (**ppw != '\n')) {
  9250. return -1;
  9251. }
  9252. } else {
  9253. /* must be a end of a word, but not a line */
  9254. if (**ppw != ' ') {
  9255. return -1;
  9256. }
  9257. }
  9258. /* Terminate and forward to the next word */
  9259. do {
  9260. **ppw = 0;
  9261. (*ppw)++;
  9262. } while (isspace((unsigned char)**ppw));
  9263. /* Check after term */
  9264. if (!eol) {
  9265. /* if it's not the end of line, there must be a next word */
  9266. if (!isgraph((unsigned char)**ppw)) {
  9267. return -1;
  9268. }
  9269. }
  9270. /* ok */
  9271. return 1;
  9272. }
  9273. /* Parse HTTP headers from the given buffer, advance buf pointer
  9274. * to the point where parsing stopped.
  9275. * All parameters must be valid pointers (not NULL).
  9276. * Return <0 on error. */
  9277. static int
  9278. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9279. {
  9280. int i;
  9281. int num_headers = 0;
  9282. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9283. char *dp = *buf;
  9284. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9285. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9286. dp++;
  9287. }
  9288. if (dp == *buf) {
  9289. /* End of headers reached. */
  9290. break;
  9291. }
  9292. /* Drop all spaces after header name before : */
  9293. while (*dp == ' ') {
  9294. *dp = 0;
  9295. dp++;
  9296. }
  9297. if (*dp != ':') {
  9298. /* This is not a valid field. */
  9299. return -1;
  9300. }
  9301. /* End of header key (*dp == ':') */
  9302. /* Truncate here and set the key name */
  9303. *dp = 0;
  9304. hdr[i].name = *buf;
  9305. /* Skip all spaces */
  9306. do {
  9307. dp++;
  9308. } while ((*dp == ' ') || (*dp == '\t'));
  9309. /* The rest of the line is the value */
  9310. hdr[i].value = dp;
  9311. /* Find end of line */
  9312. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9313. dp++;
  9314. };
  9315. /* eliminate \r */
  9316. if (*dp == '\r') {
  9317. *dp = 0;
  9318. dp++;
  9319. if (*dp != '\n') {
  9320. /* This is not a valid line. */
  9321. return -1;
  9322. }
  9323. }
  9324. /* here *dp is either 0 or '\n' */
  9325. /* in any case, we have a new header */
  9326. num_headers = i + 1;
  9327. if (*dp) {
  9328. *dp = 0;
  9329. dp++;
  9330. *buf = dp;
  9331. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9332. /* This is the end of the header */
  9333. break;
  9334. }
  9335. } else {
  9336. *buf = dp;
  9337. break;
  9338. }
  9339. }
  9340. return num_headers;
  9341. }
  9342. struct mg_http_method_info {
  9343. const char *name;
  9344. int request_has_body;
  9345. int response_has_body;
  9346. int is_safe;
  9347. int is_idempotent;
  9348. int is_cacheable;
  9349. };
  9350. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9351. static const struct mg_http_method_info http_methods[] = {
  9352. /* HTTP (RFC 2616) */
  9353. {"GET", 0, 1, 1, 1, 1},
  9354. {"POST", 1, 1, 0, 0, 0},
  9355. {"PUT", 1, 0, 0, 1, 0},
  9356. {"DELETE", 0, 0, 0, 1, 0},
  9357. {"HEAD", 0, 0, 1, 1, 1},
  9358. {"OPTIONS", 0, 0, 1, 1, 0},
  9359. {"CONNECT", 1, 1, 0, 0, 0},
  9360. /* TRACE method (RFC 2616) is not supported for security reasons */
  9361. /* PATCH method (RFC 5789) */
  9362. {"PATCH", 1, 0, 0, 0, 0},
  9363. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9364. /* WEBDAV (RFC 2518) */
  9365. {"PROPFIND", 0, 1, 1, 1, 0},
  9366. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9367. * Some PROPFIND results MAY be cached, with care,
  9368. * as there is no cache validation mechanism for
  9369. * most properties. This method is both safe and
  9370. * idempotent (see Section 9.1 of [RFC2616]). */
  9371. {"MKCOL", 0, 0, 0, 1, 0},
  9372. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9373. * When MKCOL is invoked without a request body,
  9374. * the newly created collection SHOULD have no
  9375. * members. A MKCOL request message may contain
  9376. * a message body. The precise behavior of a MKCOL
  9377. * request when the body is present is undefined,
  9378. * ... ==> We do not support MKCOL with body data.
  9379. * This method is idempotent, but not safe (see
  9380. * Section 9.1 of [RFC2616]). Responses to this
  9381. * method MUST NOT be cached. */
  9382. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9383. {"LOCK", 1, 1, 0, 0, 0},
  9384. {"UNLOCK", 1, 0, 0, 0, 0},
  9385. {"PROPPATCH", 1, 1, 0, 0, 0},
  9386. /* Unsupported WEBDAV Methods: */
  9387. /* COPY, MOVE (RFC 2518) */
  9388. /* + 11 methods from RFC 3253 */
  9389. /* ORDERPATCH (RFC 3648) */
  9390. /* ACL (RFC 3744) */
  9391. /* SEARCH (RFC 5323) */
  9392. /* + MicroSoft extensions
  9393. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9394. /* REPORT method (RFC 3253) */
  9395. {"REPORT", 1, 1, 1, 1, 1},
  9396. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9397. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9398. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9399. * to be useful for REST in case a "GET request with body" is
  9400. * required. */
  9401. {NULL, 0, 0, 0, 0, 0}
  9402. /* end of list */
  9403. };
  9404. static const struct mg_http_method_info *
  9405. get_http_method_info(const char *method)
  9406. {
  9407. /* Check if the method is known to the server. The list of all known
  9408. * HTTP methods can be found here at
  9409. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9410. */
  9411. const struct mg_http_method_info *m = http_methods;
  9412. while (m->name) {
  9413. if (!strcmp(m->name, method)) {
  9414. return m;
  9415. }
  9416. m++;
  9417. }
  9418. return NULL;
  9419. }
  9420. static int
  9421. is_valid_http_method(const char *method)
  9422. {
  9423. return (get_http_method_info(method) != NULL);
  9424. }
  9425. /* Parse HTTP request, fill in mg_request_info structure.
  9426. * This function modifies the buffer by NUL-terminating
  9427. * HTTP request components, header names and header values.
  9428. * Parameters:
  9429. * buf (in/out): pointer to the HTTP header to parse and split
  9430. * len (in): length of HTTP header buffer
  9431. * re (out): parsed header as mg_request_info
  9432. * buf and ri must be valid pointers (not NULL), len>0.
  9433. * Returns <0 on error. */
  9434. static int
  9435. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9436. {
  9437. int request_length;
  9438. int init_skip = 0;
  9439. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9440. * remote_port */
  9441. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9442. NULL;
  9443. ri->num_headers = 0;
  9444. /* RFC says that all initial whitespaces should be ingored */
  9445. /* This included all leading \r and \n (isspace) */
  9446. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9447. while ((len > 0) && isspace((unsigned char)*buf)) {
  9448. buf++;
  9449. len--;
  9450. init_skip++;
  9451. }
  9452. if (len == 0) {
  9453. /* Incomplete request */
  9454. return 0;
  9455. }
  9456. /* Control characters are not allowed, including zero */
  9457. if (iscntrl((unsigned char)*buf)) {
  9458. return -1;
  9459. }
  9460. /* Find end of HTTP header */
  9461. request_length = get_http_header_len(buf, len);
  9462. if (request_length <= 0) {
  9463. return request_length;
  9464. }
  9465. buf[request_length - 1] = '\0';
  9466. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9467. return -1;
  9468. }
  9469. /* The first word has to be the HTTP method */
  9470. ri->request_method = buf;
  9471. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9472. return -1;
  9473. }
  9474. /* Check for a valid http method */
  9475. if (!is_valid_http_method(ri->request_method)) {
  9476. return -1;
  9477. }
  9478. /* The second word is the URI */
  9479. ri->request_uri = buf;
  9480. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9481. return -1;
  9482. }
  9483. /* Next would be the HTTP version */
  9484. ri->http_version = buf;
  9485. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9486. return -1;
  9487. }
  9488. /* Check for a valid HTTP version key */
  9489. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9490. /* Invalid request */
  9491. return -1;
  9492. }
  9493. ri->http_version += 5;
  9494. /* Parse all HTTP headers */
  9495. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9496. if (ri->num_headers < 0) {
  9497. /* Error while parsing headers */
  9498. return -1;
  9499. }
  9500. return request_length + init_skip;
  9501. }
  9502. static int
  9503. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9504. {
  9505. int response_length;
  9506. int init_skip = 0;
  9507. char *tmp, *tmp2;
  9508. long l;
  9509. /* Initialize elements. */
  9510. ri->http_version = ri->status_text = NULL;
  9511. ri->num_headers = ri->status_code = 0;
  9512. /* RFC says that all initial whitespaces should be ingored */
  9513. /* This included all leading \r and \n (isspace) */
  9514. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9515. while ((len > 0) && isspace((unsigned char)*buf)) {
  9516. buf++;
  9517. len--;
  9518. init_skip++;
  9519. }
  9520. if (len == 0) {
  9521. /* Incomplete request */
  9522. return 0;
  9523. }
  9524. /* Control characters are not allowed, including zero */
  9525. if (iscntrl((unsigned char)*buf)) {
  9526. return -1;
  9527. }
  9528. /* Find end of HTTP header */
  9529. response_length = get_http_header_len(buf, len);
  9530. if (response_length <= 0) {
  9531. return response_length;
  9532. }
  9533. buf[response_length - 1] = '\0';
  9534. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9535. return -1;
  9536. }
  9537. /* The first word is the HTTP version */
  9538. /* Check for a valid HTTP version key */
  9539. if (strncmp(buf, "HTTP/", 5) != 0) {
  9540. /* Invalid request */
  9541. return -1;
  9542. }
  9543. buf += 5;
  9544. if (!isgraph((unsigned char)buf[0])) {
  9545. /* Invalid request */
  9546. return -1;
  9547. }
  9548. ri->http_version = buf;
  9549. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9550. return -1;
  9551. }
  9552. /* The second word is the status as a number */
  9553. tmp = buf;
  9554. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9555. return -1;
  9556. }
  9557. l = strtol(tmp, &tmp2, 10);
  9558. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9559. /* Everything else but a 3 digit code is invalid */
  9560. return -1;
  9561. }
  9562. ri->status_code = (int)l;
  9563. /* The rest of the line is the status text */
  9564. ri->status_text = buf;
  9565. /* Find end of status text */
  9566. /* isgraph or isspace = isprint */
  9567. while (isprint((unsigned char)*buf)) {
  9568. buf++;
  9569. }
  9570. if ((*buf != '\r') && (*buf != '\n')) {
  9571. return -1;
  9572. }
  9573. /* Terminate string and forward buf to next line */
  9574. do {
  9575. *buf = 0;
  9576. buf++;
  9577. } while (isspace((unsigned char)*buf));
  9578. /* Parse all HTTP headers */
  9579. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9580. if (ri->num_headers < 0) {
  9581. /* Error while parsing headers */
  9582. return -1;
  9583. }
  9584. return response_length + init_skip;
  9585. }
  9586. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9587. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9588. * buffer (which marks the end of HTTP request). Buffer buf may already
  9589. * have some data. The length of the data is stored in nread.
  9590. * Upon every read operation, increase nread by the number of bytes read. */
  9591. static int
  9592. read_message(FILE *fp,
  9593. struct mg_connection *conn,
  9594. char *buf,
  9595. int bufsiz,
  9596. int *nread)
  9597. {
  9598. int request_len, n = 0;
  9599. struct timespec last_action_time;
  9600. double request_timeout;
  9601. if (!conn) {
  9602. return 0;
  9603. }
  9604. memset(&last_action_time, 0, sizeof(last_action_time));
  9605. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9606. /* value of request_timeout is in seconds, config in milliseconds */
  9607. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9608. } else {
  9609. request_timeout =
  9610. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9611. }
  9612. if (conn->handled_requests > 0) {
  9613. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9614. request_timeout =
  9615. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9616. }
  9617. }
  9618. request_len = get_http_header_len(buf, *nread);
  9619. while (request_len == 0) {
  9620. /* Full request not yet received */
  9621. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9622. /* Server is to be stopped. */
  9623. return -1;
  9624. }
  9625. if (*nread >= bufsiz) {
  9626. /* Request too long */
  9627. return -2;
  9628. }
  9629. n = pull_inner(
  9630. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9631. if (n == -2) {
  9632. /* Receive error */
  9633. return -1;
  9634. }
  9635. /* update clock after every read request */
  9636. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9637. if (n > 0) {
  9638. *nread += n;
  9639. request_len = get_http_header_len(buf, *nread);
  9640. }
  9641. if ((request_len == 0) && (request_timeout >= 0)) {
  9642. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9643. > request_timeout) {
  9644. /* Timeout */
  9645. return -1;
  9646. }
  9647. }
  9648. }
  9649. return request_len;
  9650. }
  9651. #if !defined(NO_CGI) || !defined(NO_FILES)
  9652. static int
  9653. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9654. {
  9655. const char *expect;
  9656. char buf[MG_BUF_LEN];
  9657. int success = 0;
  9658. if (!conn) {
  9659. return 0;
  9660. }
  9661. expect = mg_get_header(conn, "Expect");
  9662. DEBUG_ASSERT(fp != NULL);
  9663. if (!fp) {
  9664. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9665. return 0;
  9666. }
  9667. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9668. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9669. */
  9670. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9671. } else {
  9672. if (expect != NULL) {
  9673. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9674. conn->status_code = 100;
  9675. } else {
  9676. conn->status_code = 200;
  9677. }
  9678. DEBUG_ASSERT(conn->consumed_content == 0);
  9679. if (conn->consumed_content != 0) {
  9680. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9681. return 0;
  9682. }
  9683. for (;;) {
  9684. int nread = mg_read(conn, buf, sizeof(buf));
  9685. if (nread <= 0) {
  9686. success = (nread == 0);
  9687. break;
  9688. }
  9689. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9690. break;
  9691. }
  9692. }
  9693. /* Each error code path in this function must send an error */
  9694. if (!success) {
  9695. /* NOTE: Maybe some data has already been sent. */
  9696. /* TODO (low): If some data has been sent, a correct error
  9697. * reply can no longer be sent, so just close the connection */
  9698. mg_send_http_error(conn, 500, "%s", "");
  9699. }
  9700. }
  9701. return success;
  9702. }
  9703. #endif
  9704. #if defined(USE_TIMERS)
  9705. #define TIMER_API static
  9706. #include "timer.inl"
  9707. #endif /* USE_TIMERS */
  9708. #if !defined(NO_CGI)
  9709. /* This structure helps to create an environment for the spawned CGI
  9710. * program.
  9711. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9712. * last element must be NULL.
  9713. * However, on Windows there is a requirement that all these
  9714. * VARIABLE=VALUE\0
  9715. * strings must reside in a contiguous buffer. The end of the buffer is
  9716. * marked by two '\0' characters.
  9717. * We satisfy both worlds: we create an envp array (which is vars), all
  9718. * entries are actually pointers inside buf. */
  9719. struct cgi_environment {
  9720. struct mg_connection *conn;
  9721. /* Data block */
  9722. char *buf; /* Environment buffer */
  9723. size_t buflen; /* Space available in buf */
  9724. size_t bufused; /* Space taken in buf */
  9725. /* Index block */
  9726. char **var; /* char **envp */
  9727. size_t varlen; /* Number of variables available in var */
  9728. size_t varused; /* Number of variables stored in var */
  9729. };
  9730. static void addenv(struct cgi_environment *env,
  9731. PRINTF_FORMAT_STRING(const char *fmt),
  9732. ...) PRINTF_ARGS(2, 3);
  9733. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9734. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9735. static void
  9736. addenv(struct cgi_environment *env, const char *fmt, ...)
  9737. {
  9738. size_t i, n, space;
  9739. int truncated = 0;
  9740. char *added;
  9741. va_list ap;
  9742. if ((env->varlen - env->varused) < 2) {
  9743. mg_cry_internal(env->conn,
  9744. "%s: Cannot register CGI variable [%s]",
  9745. __func__,
  9746. fmt);
  9747. return;
  9748. }
  9749. /* Calculate how much space is left in the buffer */
  9750. space = (env->buflen - env->bufused);
  9751. do {
  9752. /* Space for "\0\0" is always needed. */
  9753. if (space <= 2) {
  9754. /* Allocate new buffer */
  9755. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9756. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9757. if (!added) {
  9758. /* Out of memory */
  9759. mg_cry_internal(
  9760. env->conn,
  9761. "%s: Cannot allocate memory for CGI variable [%s]",
  9762. __func__,
  9763. fmt);
  9764. return;
  9765. }
  9766. /* Retarget pointers */
  9767. env->buf = added;
  9768. env->buflen = n;
  9769. for (i = 0, n = 0; i < env->varused; i++) {
  9770. env->var[i] = added + n;
  9771. n += strlen(added + n) + 1;
  9772. }
  9773. space = (env->buflen - env->bufused);
  9774. }
  9775. /* Make a pointer to the free space int the buffer */
  9776. added = env->buf + env->bufused;
  9777. /* Copy VARIABLE=VALUE\0 string into the free space */
  9778. va_start(ap, fmt);
  9779. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9780. va_end(ap);
  9781. /* Do not add truncated strings to the environment */
  9782. if (truncated) {
  9783. /* Reallocate the buffer */
  9784. space = 0;
  9785. }
  9786. } while (truncated);
  9787. /* Calculate number of bytes added to the environment */
  9788. n = strlen(added) + 1;
  9789. env->bufused += n;
  9790. /* Append a pointer to the added string into the envp array */
  9791. env->var[env->varused] = added;
  9792. env->varused++;
  9793. }
  9794. /* Return 0 on success, non-zero if an error occurs. */
  9795. static int
  9796. prepare_cgi_environment(struct mg_connection *conn,
  9797. const char *prog,
  9798. struct cgi_environment *env)
  9799. {
  9800. const char *s;
  9801. struct vec var_vec;
  9802. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9803. int i, truncated, uri_len;
  9804. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9805. return -1;
  9806. }
  9807. env->conn = conn;
  9808. env->buflen = CGI_ENVIRONMENT_SIZE;
  9809. env->bufused = 0;
  9810. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9811. if (env->buf == NULL) {
  9812. mg_cry_internal(conn,
  9813. "%s: Not enough memory for environmental buffer",
  9814. __func__);
  9815. return -1;
  9816. }
  9817. env->varlen = MAX_CGI_ENVIR_VARS;
  9818. env->varused = 0;
  9819. env->var =
  9820. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9821. if (env->var == NULL) {
  9822. mg_cry_internal(conn,
  9823. "%s: Not enough memory for environmental variables",
  9824. __func__);
  9825. mg_free(env->buf);
  9826. return -1;
  9827. }
  9828. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9829. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9830. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9831. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9832. /* Prepare the environment block */
  9833. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9834. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9835. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9836. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9837. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9838. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9839. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9840. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9841. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9842. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9843. /* SCRIPT_NAME */
  9844. uri_len = (int)strlen(conn->request_info.local_uri);
  9845. if (conn->path_info == NULL) {
  9846. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9847. /* URI: /path_to_script/script.cgi */
  9848. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9849. } else {
  9850. /* URI: /path_to_script/ ... using index.cgi */
  9851. const char *index_file = strrchr(prog, '/');
  9852. if (index_file) {
  9853. addenv(env,
  9854. "SCRIPT_NAME=%s%s",
  9855. conn->request_info.local_uri,
  9856. index_file + 1);
  9857. }
  9858. }
  9859. } else {
  9860. /* URI: /path_to_script/script.cgi/path_info */
  9861. addenv(env,
  9862. "SCRIPT_NAME=%.*s",
  9863. uri_len - (int)strlen(conn->path_info),
  9864. conn->request_info.local_uri);
  9865. }
  9866. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9867. if (conn->path_info == NULL) {
  9868. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9869. } else {
  9870. addenv(env,
  9871. "PATH_TRANSLATED=%s%s",
  9872. conn->dom_ctx->config[DOCUMENT_ROOT],
  9873. conn->path_info);
  9874. }
  9875. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9876. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9877. addenv(env, "CONTENT_TYPE=%s", s);
  9878. }
  9879. if (conn->request_info.query_string != NULL) {
  9880. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9881. }
  9882. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9883. addenv(env, "CONTENT_LENGTH=%s", s);
  9884. }
  9885. if ((s = getenv("PATH")) != NULL) {
  9886. addenv(env, "PATH=%s", s);
  9887. }
  9888. if (conn->path_info != NULL) {
  9889. addenv(env, "PATH_INFO=%s", conn->path_info);
  9890. }
  9891. if (conn->status_code > 0) {
  9892. /* CGI error handler should show the status code */
  9893. addenv(env, "STATUS=%d", conn->status_code);
  9894. }
  9895. #if defined(_WIN32)
  9896. if ((s = getenv("COMSPEC")) != NULL) {
  9897. addenv(env, "COMSPEC=%s", s);
  9898. }
  9899. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9900. addenv(env, "SYSTEMROOT=%s", s);
  9901. }
  9902. if ((s = getenv("SystemDrive")) != NULL) {
  9903. addenv(env, "SystemDrive=%s", s);
  9904. }
  9905. if ((s = getenv("ProgramFiles")) != NULL) {
  9906. addenv(env, "ProgramFiles=%s", s);
  9907. }
  9908. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9909. addenv(env, "ProgramFiles(x86)=%s", s);
  9910. }
  9911. #else
  9912. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9913. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9914. }
  9915. #endif /* _WIN32 */
  9916. if ((s = getenv("PERLLIB")) != NULL) {
  9917. addenv(env, "PERLLIB=%s", s);
  9918. }
  9919. if (conn->request_info.remote_user != NULL) {
  9920. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9921. addenv(env, "%s", "AUTH_TYPE=Digest");
  9922. }
  9923. /* Add all headers as HTTP_* variables */
  9924. for (i = 0; i < conn->request_info.num_headers; i++) {
  9925. (void)mg_snprintf(conn,
  9926. &truncated,
  9927. http_var_name,
  9928. sizeof(http_var_name),
  9929. "HTTP_%s",
  9930. conn->request_info.http_headers[i].name);
  9931. if (truncated) {
  9932. mg_cry_internal(conn,
  9933. "%s: HTTP header variable too long [%s]",
  9934. __func__,
  9935. conn->request_info.http_headers[i].name);
  9936. continue;
  9937. }
  9938. /* Convert variable name into uppercase, and change - to _ */
  9939. for (p = http_var_name; *p != '\0'; p++) {
  9940. if (*p == '-') {
  9941. *p = '_';
  9942. }
  9943. *p = (char)toupper((unsigned char)*p);
  9944. }
  9945. addenv(env,
  9946. "%s=%s",
  9947. http_var_name,
  9948. conn->request_info.http_headers[i].value);
  9949. }
  9950. /* Add user-specified variables */
  9951. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9952. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9953. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9954. }
  9955. env->var[env->varused] = NULL;
  9956. env->buf[env->bufused] = '\0';
  9957. return 0;
  9958. }
  9959. /* Data for CGI process control: PID and number of references */
  9960. struct process_control_data {
  9961. pid_t pid;
  9962. ptrdiff_t references;
  9963. };
  9964. static int
  9965. abort_cgi_process(void *data)
  9966. {
  9967. /* Waitpid checks for child status and won't work for a pid that does
  9968. * not identify a child of the current process. Thus, if the pid is
  9969. * reused, we will not affect a different process. */
  9970. struct process_control_data *proc = (struct process_control_data *)data;
  9971. int status = 0;
  9972. ptrdiff_t refs;
  9973. pid_t ret_pid;
  9974. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9975. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9976. /* Stop child process */
  9977. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9978. kill(proc->pid, SIGABRT);
  9979. /* Wait until process is terminated (don't leave zombies) */
  9980. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9981. ;
  9982. } else {
  9983. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9984. }
  9985. /* Dec reference counter */
  9986. refs = mg_atomic_dec(&proc->references);
  9987. if (refs == 0) {
  9988. /* no more references - free data */
  9989. mg_free(data);
  9990. }
  9991. return 0;
  9992. }
  9993. /* Local (static) function assumes all arguments are valid. */
  9994. static void
  9995. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9996. {
  9997. char *buf;
  9998. size_t buflen;
  9999. int headers_len, data_len, i, truncated;
  10000. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10001. const char *status, *status_text, *connection_state;
  10002. char *pbuf, dir[PATH_MAX], *p;
  10003. struct mg_request_info ri;
  10004. struct cgi_environment blk;
  10005. FILE *in = NULL, *out = NULL, *err = NULL;
  10006. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10007. pid_t pid = (pid_t)-1;
  10008. struct process_control_data *proc = NULL;
  10009. #if defined(USE_TIMERS)
  10010. double cgi_timeout;
  10011. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  10012. /* Get timeout in seconds */
  10013. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  10014. } else {
  10015. cgi_timeout =
  10016. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10017. }
  10018. #endif
  10019. buf = NULL;
  10020. buflen = conn->phys_ctx->max_request_size;
  10021. i = prepare_cgi_environment(conn, prog, &blk);
  10022. if (i != 0) {
  10023. blk.buf = NULL;
  10024. blk.var = NULL;
  10025. goto done;
  10026. }
  10027. /* CGI must be executed in its own directory. 'dir' must point to the
  10028. * directory containing executable program, 'p' must point to the
  10029. * executable program name relative to 'dir'. */
  10030. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10031. if (truncated) {
  10032. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10033. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10034. goto done;
  10035. }
  10036. if ((p = strrchr(dir, '/')) != NULL) {
  10037. *p++ = '\0';
  10038. } else {
  10039. dir[0] = '.';
  10040. dir[1] = '\0';
  10041. p = (char *)prog;
  10042. }
  10043. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10044. status = strerror(ERRNO);
  10045. mg_cry_internal(
  10046. conn,
  10047. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10048. prog,
  10049. status);
  10050. mg_send_http_error(conn,
  10051. 500,
  10052. "Error: Cannot create CGI pipe: %s",
  10053. status);
  10054. goto done;
  10055. }
  10056. proc = (struct process_control_data *)
  10057. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10058. if (proc == NULL) {
  10059. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10060. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10061. goto done;
  10062. }
  10063. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10064. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  10065. if (pid == (pid_t)-1) {
  10066. status = strerror(ERRNO);
  10067. mg_cry_internal(
  10068. conn,
  10069. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10070. prog,
  10071. status);
  10072. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10073. mg_free(proc);
  10074. proc = NULL;
  10075. goto done;
  10076. }
  10077. /* Store data in shared process_control_data */
  10078. proc->pid = pid;
  10079. proc->references = 1;
  10080. #if defined(USE_TIMERS)
  10081. if (cgi_timeout > 0.0) {
  10082. proc->references = 2;
  10083. // Start a timer for CGI
  10084. timer_add(conn->phys_ctx,
  10085. cgi_timeout /* in seconds */,
  10086. 0.0,
  10087. 1,
  10088. abort_cgi_process,
  10089. (void *)proc,
  10090. NULL);
  10091. }
  10092. #endif
  10093. /* Parent closes only one side of the pipes.
  10094. * If we don't mark them as closed, close() attempt before
  10095. * return from this function throws an exception on Windows.
  10096. * Windows does not like when closed descriptor is closed again. */
  10097. (void)close(fdin[0]);
  10098. (void)close(fdout[1]);
  10099. (void)close(fderr[1]);
  10100. fdin[0] = fdout[1] = fderr[1] = -1;
  10101. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10102. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10103. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10104. status = strerror(ERRNO);
  10105. mg_cry_internal(conn,
  10106. "Error: CGI program \"%s\": Can not open fd: %s",
  10107. prog,
  10108. status);
  10109. mg_send_http_error(conn,
  10110. 500,
  10111. "Error: CGI can not open fd\nfdopen: %s",
  10112. status);
  10113. goto done;
  10114. }
  10115. setbuf(in, NULL);
  10116. setbuf(out, NULL);
  10117. setbuf(err, NULL);
  10118. fout.access.fp = out;
  10119. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10120. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10121. conn->content_len);
  10122. /* This is a POST/PUT request, or another request with body data. */
  10123. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10124. /* Error sending the body data */
  10125. mg_cry_internal(
  10126. conn,
  10127. "Error: CGI program \"%s\": Forward body data failed",
  10128. prog);
  10129. goto done;
  10130. }
  10131. }
  10132. /* Close so child gets an EOF. */
  10133. fclose(in);
  10134. in = NULL;
  10135. fdin[1] = -1;
  10136. /* Now read CGI reply into a buffer. We need to set correct
  10137. * status code, thus we need to see all HTTP headers first.
  10138. * Do not send anything back to client, until we buffer in all
  10139. * HTTP headers. */
  10140. data_len = 0;
  10141. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10142. if (buf == NULL) {
  10143. mg_send_http_error(conn,
  10144. 500,
  10145. "Error: Not enough memory for CGI buffer (%u bytes)",
  10146. (unsigned int)buflen);
  10147. mg_cry_internal(
  10148. conn,
  10149. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10150. "bytes)",
  10151. prog,
  10152. (unsigned int)buflen);
  10153. goto done;
  10154. }
  10155. DEBUG_TRACE("CGI: %s", "wait for response");
  10156. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10157. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10158. if (headers_len <= 0) {
  10159. /* Could not parse the CGI response. Check if some error message on
  10160. * stderr. */
  10161. i = pull_all(err, conn, buf, (int)buflen);
  10162. if (i > 0) {
  10163. /* CGI program explicitly sent an error */
  10164. /* Write the error message to the internal log */
  10165. mg_cry_internal(conn,
  10166. "Error: CGI program \"%s\" sent error "
  10167. "message: [%.*s]",
  10168. prog,
  10169. i,
  10170. buf);
  10171. /* Don't send the error message back to the client */
  10172. mg_send_http_error(conn,
  10173. 500,
  10174. "Error: CGI program \"%s\" failed.",
  10175. prog);
  10176. } else {
  10177. /* CGI program did not explicitly send an error, but a broken
  10178. * respon header */
  10179. mg_cry_internal(conn,
  10180. "Error: CGI program sent malformed or too big "
  10181. "(>%u bytes) HTTP headers: [%.*s]",
  10182. (unsigned)buflen,
  10183. data_len,
  10184. buf);
  10185. mg_send_http_error(conn,
  10186. 500,
  10187. "Error: CGI program sent malformed or too big "
  10188. "(>%u bytes) HTTP headers: [%.*s]",
  10189. (unsigned)buflen,
  10190. data_len,
  10191. buf);
  10192. }
  10193. /* in both cases, abort processing CGI */
  10194. goto done;
  10195. }
  10196. pbuf = buf;
  10197. buf[headers_len - 1] = '\0';
  10198. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10199. /* Make up and send the status line */
  10200. status_text = "OK";
  10201. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10202. != NULL) {
  10203. conn->status_code = atoi(status);
  10204. status_text = status;
  10205. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10206. status_text++;
  10207. }
  10208. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10209. != NULL) {
  10210. conn->status_code = 307;
  10211. } else {
  10212. conn->status_code = 200;
  10213. }
  10214. connection_state =
  10215. get_header(ri.http_headers, ri.num_headers, "Connection");
  10216. if (!header_has_option(connection_state, "keep-alive")) {
  10217. conn->must_close = 1;
  10218. }
  10219. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10220. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10221. /* Send headers */
  10222. for (i = 0; i < ri.num_headers; i++) {
  10223. DEBUG_TRACE("CGI header: %s: %s",
  10224. ri.http_headers[i].name,
  10225. ri.http_headers[i].value);
  10226. mg_printf(conn,
  10227. "%s: %s\r\n",
  10228. ri.http_headers[i].name,
  10229. ri.http_headers[i].value);
  10230. }
  10231. mg_write(conn, "\r\n", 2);
  10232. /* Send chunk of data that may have been read after the headers */
  10233. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10234. /* Read the rest of CGI output and send to the client */
  10235. DEBUG_TRACE("CGI: %s", "forward all data");
  10236. send_file_data(conn, &fout, 0, INT64_MAX);
  10237. DEBUG_TRACE("CGI: %s", "all data sent");
  10238. done:
  10239. mg_free(blk.var);
  10240. mg_free(blk.buf);
  10241. if (pid != (pid_t)-1) {
  10242. abort_cgi_process((void *)proc);
  10243. }
  10244. if (fdin[0] != -1) {
  10245. close(fdin[0]);
  10246. }
  10247. if (fdout[1] != -1) {
  10248. close(fdout[1]);
  10249. }
  10250. if (fderr[1] != -1) {
  10251. close(fderr[1]);
  10252. }
  10253. if (in != NULL) {
  10254. fclose(in);
  10255. } else if (fdin[1] != -1) {
  10256. close(fdin[1]);
  10257. }
  10258. if (out != NULL) {
  10259. fclose(out);
  10260. } else if (fdout[0] != -1) {
  10261. close(fdout[0]);
  10262. }
  10263. if (err != NULL) {
  10264. fclose(err);
  10265. } else if (fderr[0] != -1) {
  10266. close(fderr[0]);
  10267. }
  10268. mg_free(buf);
  10269. }
  10270. #endif /* !NO_CGI */
  10271. #if !defined(NO_FILES)
  10272. static void
  10273. mkcol(struct mg_connection *conn, const char *path)
  10274. {
  10275. int rc, body_len;
  10276. struct de de;
  10277. if (conn == NULL) {
  10278. return;
  10279. }
  10280. /* TODO (mid): Check the mg_send_http_error situations in this function
  10281. */
  10282. memset(&de.file, 0, sizeof(de.file));
  10283. if (!mg_stat(conn, path, &de.file)) {
  10284. mg_cry_internal(conn,
  10285. "%s: mg_stat(%s) failed: %s",
  10286. __func__,
  10287. path,
  10288. strerror(ERRNO));
  10289. }
  10290. if (de.file.last_modified) {
  10291. /* TODO (mid): This check does not seem to make any sense ! */
  10292. /* TODO (mid): Add a webdav unit test first, before changing
  10293. * anything here. */
  10294. mg_send_http_error(
  10295. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10296. return;
  10297. }
  10298. body_len = conn->data_len - conn->request_len;
  10299. if (body_len > 0) {
  10300. mg_send_http_error(
  10301. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10302. return;
  10303. }
  10304. rc = mg_mkdir(conn, path, 0755);
  10305. if (rc == 0) {
  10306. /* Create 201 "Created" response */
  10307. mg_response_header_start(conn, 201);
  10308. send_static_cache_header(conn);
  10309. send_additional_header(conn);
  10310. mg_response_header_add(conn, "Content-Length", "0", -1);
  10311. /* Send all headers - there is no body */
  10312. mg_response_header_send(conn);
  10313. } else {
  10314. if (errno == EEXIST) {
  10315. mg_send_http_error(
  10316. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10317. } else if (errno == EACCES) {
  10318. mg_send_http_error(
  10319. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10320. } else if (errno == ENOENT) {
  10321. mg_send_http_error(
  10322. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10323. } else {
  10324. mg_send_http_error(
  10325. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10326. }
  10327. }
  10328. }
  10329. static void
  10330. put_file(struct mg_connection *conn, const char *path)
  10331. {
  10332. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10333. const char *range;
  10334. int64_t r1, r2;
  10335. int rc;
  10336. if (conn == NULL) {
  10337. return;
  10338. }
  10339. if (mg_stat(conn, path, &file.stat)) {
  10340. /* File already exists */
  10341. conn->status_code = 200;
  10342. if (file.stat.is_directory) {
  10343. /* This is an already existing directory,
  10344. * so there is nothing to do for the server. */
  10345. rc = 0;
  10346. } else {
  10347. /* File exists and is not a directory. */
  10348. /* Can it be replaced? */
  10349. /* Check if the server may write this file */
  10350. if (access(path, W_OK) == 0) {
  10351. /* Access granted */
  10352. rc = 1;
  10353. } else {
  10354. mg_send_http_error(
  10355. conn,
  10356. 403,
  10357. "Error: Put not possible\nReplacing %s is not allowed",
  10358. path);
  10359. return;
  10360. }
  10361. }
  10362. } else {
  10363. /* File should be created */
  10364. conn->status_code = 201;
  10365. rc = put_dir(conn, path);
  10366. }
  10367. if (rc == 0) {
  10368. /* put_dir returns 0 if path is a directory */
  10369. /* Create response */
  10370. mg_response_header_start(conn, conn->status_code);
  10371. send_no_cache_header(conn);
  10372. send_additional_header(conn);
  10373. mg_response_header_add(conn, "Content-Length", "0", -1);
  10374. /* Send all headers - there is no body */
  10375. mg_response_header_send(conn);
  10376. /* Request to create a directory has been fulfilled successfully.
  10377. * No need to put a file. */
  10378. return;
  10379. }
  10380. if (rc == -1) {
  10381. /* put_dir returns -1 if the path is too long */
  10382. mg_send_http_error(conn,
  10383. 414,
  10384. "Error: Path too long\nput_dir(%s): %s",
  10385. path,
  10386. strerror(ERRNO));
  10387. return;
  10388. }
  10389. if (rc == -2) {
  10390. /* put_dir returns -2 if the directory can not be created */
  10391. mg_send_http_error(conn,
  10392. 500,
  10393. "Error: Can not create directory\nput_dir(%s): %s",
  10394. path,
  10395. strerror(ERRNO));
  10396. return;
  10397. }
  10398. /* A file should be created or overwritten. */
  10399. /* Currently CivetWeb does not nead read+write access. */
  10400. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10401. || file.access.fp == NULL) {
  10402. (void)mg_fclose(&file.access);
  10403. mg_send_http_error(conn,
  10404. 500,
  10405. "Error: Can not create file\nfopen(%s): %s",
  10406. path,
  10407. strerror(ERRNO));
  10408. return;
  10409. }
  10410. fclose_on_exec(&file.access, conn);
  10411. range = mg_get_header(conn, "Content-Range");
  10412. r1 = r2 = 0;
  10413. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10414. conn->status_code = 206; /* Partial content */
  10415. fseeko(file.access.fp, r1, SEEK_SET);
  10416. }
  10417. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10418. /* forward_body_data failed.
  10419. * The error code has already been sent to the client,
  10420. * and conn->status_code is already set. */
  10421. (void)mg_fclose(&file.access);
  10422. return;
  10423. }
  10424. if (mg_fclose(&file.access) != 0) {
  10425. /* fclose failed. This might have different reasons, but a likely
  10426. * one is "no space on disk", http 507. */
  10427. conn->status_code = 507;
  10428. }
  10429. /* Create response (status_code has been set before) */
  10430. mg_response_header_start(conn, conn->status_code);
  10431. send_no_cache_header(conn);
  10432. send_additional_header(conn);
  10433. mg_response_header_add(conn, "Content-Length", "0", -1);
  10434. /* Send all headers - there is no body */
  10435. mg_response_header_send(conn);
  10436. }
  10437. static void
  10438. delete_file(struct mg_connection *conn, const char *path)
  10439. {
  10440. struct de de;
  10441. memset(&de.file, 0, sizeof(de.file));
  10442. if (!mg_stat(conn, path, &de.file)) {
  10443. /* mg_stat returns 0 if the file does not exist */
  10444. mg_send_http_error(conn,
  10445. 404,
  10446. "Error: Cannot delete file\nFile %s not found",
  10447. path);
  10448. return;
  10449. }
  10450. if (de.file.is_directory) {
  10451. if (remove_directory(conn, path)) {
  10452. /* Delete is successful: Return 204 without content. */
  10453. mg_send_http_error(conn, 204, "%s", "");
  10454. } else {
  10455. /* Delete is not successful: Return 500 (Server error). */
  10456. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10457. }
  10458. return;
  10459. }
  10460. /* This is an existing file (not a directory).
  10461. * Check if write permission is granted. */
  10462. if (access(path, W_OK) != 0) {
  10463. /* File is read only */
  10464. mg_send_http_error(
  10465. conn,
  10466. 403,
  10467. "Error: Delete not possible\nDeleting %s is not allowed",
  10468. path);
  10469. return;
  10470. }
  10471. /* Try to delete it. */
  10472. if (mg_remove(conn, path) == 0) {
  10473. /* Delete was successful: Return 204 without content. */
  10474. mg_response_header_start(conn, 204);
  10475. send_no_cache_header(conn);
  10476. send_additional_header(conn);
  10477. mg_response_header_add(conn, "Content-Length", "0", -1);
  10478. mg_response_header_send(conn);
  10479. } else {
  10480. /* Delete not successful (file locked). */
  10481. mg_send_http_error(conn,
  10482. 423,
  10483. "Error: Cannot delete file\nremove(%s): %s",
  10484. path,
  10485. strerror(ERRNO));
  10486. }
  10487. }
  10488. #endif /* !NO_FILES */
  10489. #if !defined(NO_FILESYSTEMS)
  10490. static void
  10491. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10492. static void
  10493. do_ssi_include(struct mg_connection *conn,
  10494. const char *ssi,
  10495. char *tag,
  10496. int include_level)
  10497. {
  10498. char file_name[MG_BUF_LEN], path[512], *p;
  10499. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10500. size_t len;
  10501. int truncated = 0;
  10502. if (conn == NULL) {
  10503. return;
  10504. }
  10505. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10506. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10507. * always < MG_BUF_LEN. */
  10508. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10509. /* File name is relative to the webserver root */
  10510. file_name[511] = 0;
  10511. (void)mg_snprintf(conn,
  10512. &truncated,
  10513. path,
  10514. sizeof(path),
  10515. "%s/%s",
  10516. conn->dom_ctx->config[DOCUMENT_ROOT],
  10517. file_name);
  10518. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10519. /* File name is relative to the webserver working directory
  10520. * or it is absolute system path */
  10521. file_name[511] = 0;
  10522. (void)
  10523. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10524. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10525. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10526. /* File name is relative to the currect document */
  10527. file_name[511] = 0;
  10528. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10529. if (!truncated) {
  10530. if ((p = strrchr(path, '/')) != NULL) {
  10531. p[1] = '\0';
  10532. }
  10533. len = strlen(path);
  10534. (void)mg_snprintf(conn,
  10535. &truncated,
  10536. path + len,
  10537. sizeof(path) - len,
  10538. "%s",
  10539. file_name);
  10540. }
  10541. } else {
  10542. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10543. return;
  10544. }
  10545. if (truncated) {
  10546. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10547. return;
  10548. }
  10549. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10550. mg_cry_internal(conn,
  10551. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10552. tag,
  10553. path,
  10554. strerror(ERRNO));
  10555. } else {
  10556. fclose_on_exec(&file.access, conn);
  10557. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10558. > 0) {
  10559. send_ssi_file(conn, path, &file, include_level + 1);
  10560. } else {
  10561. send_file_data(conn, &file, 0, INT64_MAX);
  10562. }
  10563. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10564. }
  10565. }
  10566. #if !defined(NO_POPEN)
  10567. static void
  10568. do_ssi_exec(struct mg_connection *conn, char *tag)
  10569. {
  10570. char cmd[1024] = "";
  10571. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10572. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10573. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10574. } else {
  10575. cmd[1023] = 0;
  10576. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10577. mg_cry_internal(conn,
  10578. "Cannot SSI #exec: [%s]: %s",
  10579. cmd,
  10580. strerror(ERRNO));
  10581. } else {
  10582. send_file_data(conn, &file, 0, INT64_MAX);
  10583. pclose(file.access.fp);
  10584. }
  10585. }
  10586. }
  10587. #endif /* !NO_POPEN */
  10588. static int
  10589. mg_fgetc(struct mg_file *filep)
  10590. {
  10591. if (filep == NULL) {
  10592. return EOF;
  10593. }
  10594. if (filep->access.fp != NULL) {
  10595. return fgetc(filep->access.fp);
  10596. } else {
  10597. return EOF;
  10598. }
  10599. }
  10600. static void
  10601. send_ssi_file(struct mg_connection *conn,
  10602. const char *path,
  10603. struct mg_file *filep,
  10604. int include_level)
  10605. {
  10606. char buf[MG_BUF_LEN];
  10607. int ch, len, in_tag, in_ssi_tag;
  10608. if (include_level > 10) {
  10609. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10610. return;
  10611. }
  10612. in_tag = in_ssi_tag = len = 0;
  10613. /* Read file, byte by byte, and look for SSI include tags */
  10614. while ((ch = mg_fgetc(filep)) != EOF) {
  10615. if (in_tag) {
  10616. /* We are in a tag, either SSI tag or html tag */
  10617. if (ch == '>') {
  10618. /* Tag is closing */
  10619. buf[len++] = '>';
  10620. if (in_ssi_tag) {
  10621. /* Handle SSI tag */
  10622. buf[len] = 0;
  10623. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10624. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10625. #if !defined(NO_POPEN)
  10626. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10627. do_ssi_exec(conn, buf + 9);
  10628. #endif /* !NO_POPEN */
  10629. } else {
  10630. mg_cry_internal(conn,
  10631. "%s: unknown SSI "
  10632. "command: \"%s\"",
  10633. path,
  10634. buf);
  10635. }
  10636. len = 0;
  10637. in_ssi_tag = in_tag = 0;
  10638. } else {
  10639. /* Not an SSI tag */
  10640. /* Flush buffer */
  10641. (void)mg_write(conn, buf, (size_t)len);
  10642. len = 0;
  10643. in_tag = 0;
  10644. }
  10645. } else {
  10646. /* Tag is still open */
  10647. buf[len++] = (char)(ch & 0xff);
  10648. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10649. /* All SSI tags start with <!--# */
  10650. in_ssi_tag = 1;
  10651. }
  10652. if ((len + 2) > (int)sizeof(buf)) {
  10653. /* Tag to long for buffer */
  10654. mg_cry_internal(conn, "%s: tag is too large", path);
  10655. return;
  10656. }
  10657. }
  10658. } else {
  10659. /* We are not in a tag yet. */
  10660. if (ch == '<') {
  10661. /* Tag is opening */
  10662. in_tag = 1;
  10663. if (len > 0) {
  10664. /* Flush current buffer.
  10665. * Buffer is filled with "len" bytes. */
  10666. (void)mg_write(conn, buf, (size_t)len);
  10667. }
  10668. /* Store the < */
  10669. len = 1;
  10670. buf[0] = '<';
  10671. } else {
  10672. /* No Tag */
  10673. /* Add data to buffer */
  10674. buf[len++] = (char)(ch & 0xff);
  10675. /* Flush if buffer is full */
  10676. if (len == (int)sizeof(buf)) {
  10677. mg_write(conn, buf, (size_t)len);
  10678. len = 0;
  10679. }
  10680. }
  10681. }
  10682. }
  10683. /* Send the rest of buffered data */
  10684. if (len > 0) {
  10685. mg_write(conn, buf, (size_t)len);
  10686. }
  10687. }
  10688. static void
  10689. handle_ssi_file_request(struct mg_connection *conn,
  10690. const char *path,
  10691. struct mg_file *filep)
  10692. {
  10693. char date[64];
  10694. time_t curtime = time(NULL);
  10695. const char *cors_orig_cfg;
  10696. const char *cors1, *cors2;
  10697. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10698. return;
  10699. }
  10700. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10701. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10702. /* Cross-origin resource sharing (CORS). */
  10703. cors1 = "Access-Control-Allow-Origin";
  10704. cors2 = cors_orig_cfg;
  10705. } else {
  10706. cors1 = cors2 = "";
  10707. }
  10708. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10709. /* File exists (precondition for calling this function),
  10710. * but can not be opened by the server. */
  10711. mg_send_http_error(conn,
  10712. 500,
  10713. "Error: Cannot read file\nfopen(%s): %s",
  10714. path,
  10715. strerror(ERRNO));
  10716. } else {
  10717. /* Set "must_close" for HTTP/1.x, since we do not know the
  10718. * content length */
  10719. conn->must_close = 1;
  10720. gmt_time_string(date, sizeof(date), &curtime);
  10721. fclose_on_exec(&filep->access, conn);
  10722. /* 200 OK response */
  10723. mg_response_header_start(conn, 200);
  10724. send_no_cache_header(conn);
  10725. send_additional_header(conn);
  10726. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10727. if (cors1[0]) {
  10728. mg_response_header_add(conn, cors1, cors2, -1);
  10729. }
  10730. mg_response_header_send(conn);
  10731. /* Header sent, now send body */
  10732. send_ssi_file(conn, path, filep, 0);
  10733. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10734. }
  10735. }
  10736. #endif /* NO_FILESYSTEMS */
  10737. #if !defined(NO_FILES)
  10738. static void
  10739. send_options(struct mg_connection *conn)
  10740. {
  10741. if (!conn) {
  10742. return;
  10743. }
  10744. /* We do not set a "Cache-Control" header here, but leave the default.
  10745. * Since browsers do not send an OPTIONS request, we can not test the
  10746. * effect anyway. */
  10747. mg_response_header_start(conn, 200);
  10748. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10749. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10750. /* Use the same as before */
  10751. mg_response_header_add(
  10752. conn,
  10753. "Allow",
  10754. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10755. -1);
  10756. mg_response_header_add(conn, "DAV", "1", -1);
  10757. } else {
  10758. /* TODO: Check this later for HTTP/2 */
  10759. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10760. }
  10761. send_additional_header(conn);
  10762. mg_response_header_send(conn);
  10763. }
  10764. /* Writes PROPFIND properties for a collection element */
  10765. static int
  10766. print_props(struct mg_connection *conn,
  10767. const char *uri,
  10768. const char *name,
  10769. struct mg_file_stat *filep)
  10770. {
  10771. size_t href_size, i, j;
  10772. int len;
  10773. char *href, mtime[64];
  10774. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10775. return 0;
  10776. }
  10777. /* Estimate worst case size for encoding */
  10778. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10779. href = (char *)mg_malloc(href_size);
  10780. if (href == NULL) {
  10781. return 0;
  10782. }
  10783. len = mg_url_encode(uri, href, href_size);
  10784. if (len >= 0) {
  10785. /* Append an extra string */
  10786. mg_url_encode(name, href + len, href_size - (size_t)len);
  10787. }
  10788. /* Directory separator should be preserved. */
  10789. for (i = j = 0; href[i]; j++) {
  10790. if (!strncmp(href + i, "%2f", 3)) {
  10791. href[j] = '/';
  10792. i += 3;
  10793. } else {
  10794. href[j] = href[i++];
  10795. }
  10796. }
  10797. href[j] = '\0';
  10798. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10799. mg_printf(conn,
  10800. "<d:response>"
  10801. "<d:href>%s</d:href>"
  10802. "<d:propstat>"
  10803. "<d:prop>"
  10804. "<d:resourcetype>%s</d:resourcetype>"
  10805. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10806. "<d:getlastmodified>%s</d:getlastmodified>"
  10807. "</d:prop>"
  10808. "<d:status>HTTP/1.1 200 OK</d:status>"
  10809. "</d:propstat>"
  10810. "</d:response>\n",
  10811. href,
  10812. filep->is_directory ? "<d:collection/>" : "",
  10813. filep->size,
  10814. mtime);
  10815. mg_free(href);
  10816. return 1;
  10817. }
  10818. static int
  10819. print_dav_dir_entry(struct de *de, void *data)
  10820. {
  10821. struct mg_connection *conn = (struct mg_connection *)data;
  10822. if (!de || !conn
  10823. || !print_props(
  10824. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10825. /* stop scan */
  10826. return 1;
  10827. }
  10828. return 0;
  10829. }
  10830. static void
  10831. handle_propfind(struct mg_connection *conn,
  10832. const char *path,
  10833. struct mg_file_stat *filep)
  10834. {
  10835. const char *depth = mg_get_header(conn, "Depth");
  10836. char date[64];
  10837. time_t curtime = time(NULL);
  10838. gmt_time_string(date, sizeof(date), &curtime);
  10839. if (!conn || !path || !filep || !conn->dom_ctx) {
  10840. return;
  10841. }
  10842. conn->must_close = 1;
  10843. /* return 207 "Multi-Status" */
  10844. mg_response_header_start(conn, 207);
  10845. send_static_cache_header(conn);
  10846. send_additional_header(conn);
  10847. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10848. mg_response_header_send(conn);
  10849. /* Content */
  10850. mg_printf(conn,
  10851. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10852. "<d:multistatus xmlns:d='DAV:'>\n");
  10853. /* Print properties for the requested resource itself */
  10854. print_props(conn, conn->request_info.local_uri, "", filep);
  10855. /* If it is a directory, print directory entries too if Depth is not 0
  10856. */
  10857. if (filep->is_directory
  10858. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10859. "yes")
  10860. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10861. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10862. }
  10863. mg_printf(conn, "%s\n", "</d:multistatus>");
  10864. }
  10865. #endif
  10866. void
  10867. mg_lock_connection(struct mg_connection *conn)
  10868. {
  10869. if (conn) {
  10870. (void)pthread_mutex_lock(&conn->mutex);
  10871. }
  10872. }
  10873. void
  10874. mg_unlock_connection(struct mg_connection *conn)
  10875. {
  10876. if (conn) {
  10877. (void)pthread_mutex_unlock(&conn->mutex);
  10878. }
  10879. }
  10880. void
  10881. mg_lock_context(struct mg_context *ctx)
  10882. {
  10883. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10884. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10885. }
  10886. }
  10887. void
  10888. mg_unlock_context(struct mg_context *ctx)
  10889. {
  10890. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10891. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10892. }
  10893. }
  10894. #if defined(USE_LUA)
  10895. #include "mod_lua.inl"
  10896. #endif /* USE_LUA */
  10897. #if defined(USE_DUKTAPE)
  10898. #include "mod_duktape.inl"
  10899. #endif /* USE_DUKTAPE */
  10900. #if defined(USE_WEBSOCKET)
  10901. #if !defined(NO_SSL_DL)
  10902. #define SHA_API static
  10903. #include "sha1.inl"
  10904. #endif
  10905. static int
  10906. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10907. {
  10908. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10909. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10910. SHA_CTX sha_ctx;
  10911. int truncated;
  10912. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10913. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10914. if (truncated) {
  10915. conn->must_close = 1;
  10916. return 0;
  10917. }
  10918. DEBUG_TRACE("%s", "Send websocket handshake");
  10919. SHA1_Init(&sha_ctx);
  10920. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10921. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10922. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10923. mg_printf(conn,
  10924. "HTTP/1.1 101 Switching Protocols\r\n"
  10925. "Upgrade: websocket\r\n"
  10926. "Connection: Upgrade\r\n"
  10927. "Sec-WebSocket-Accept: %s\r\n",
  10928. b64_sha);
  10929. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10930. // Send negotiated compression extension parameters
  10931. websocket_deflate_response(conn);
  10932. #endif
  10933. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10934. mg_printf(conn,
  10935. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10936. conn->request_info.acceptedWebSocketSubprotocol);
  10937. } else {
  10938. mg_printf(conn, "%s", "\r\n");
  10939. }
  10940. return 1;
  10941. }
  10942. #if !defined(MG_MAX_UNANSWERED_PING)
  10943. /* Configuration of the maximum number of websocket PINGs that might
  10944. * stay unanswered before the connection is considered broken.
  10945. * Note: The name of this define may still change (until it is
  10946. * defined as a compile parameter in a documentation).
  10947. */
  10948. #define MG_MAX_UNANSWERED_PING (5)
  10949. #endif
  10950. static void
  10951. read_websocket(struct mg_connection *conn,
  10952. mg_websocket_data_handler ws_data_handler,
  10953. void *callback_data)
  10954. {
  10955. /* Pointer to the beginning of the portion of the incoming websocket
  10956. * message queue.
  10957. * The original websocket upgrade request is never removed, so the queue
  10958. * begins after it. */
  10959. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10960. int n, error, exit_by_callback;
  10961. int ret;
  10962. /* body_len is the length of the entire queue in bytes
  10963. * len is the length of the current message
  10964. * data_len is the length of the current message's data payload
  10965. * header_len is the length of the current message's header */
  10966. size_t i, len, mask_len = 0, header_len, body_len;
  10967. uint64_t data_len = 0;
  10968. /* "The masking key is a 32-bit value chosen at random by the client."
  10969. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10970. */
  10971. unsigned char mask[4];
  10972. /* data points to the place where the message is stored when passed to
  10973. * the websocket_data callback. This is either mem on the stack, or a
  10974. * dynamically allocated buffer if it is too large. */
  10975. unsigned char mem[4096];
  10976. unsigned char mop; /* mask flag and opcode */
  10977. /* Variables used for connection monitoring */
  10978. double timeout = -1.0;
  10979. int enable_ping_pong = 0;
  10980. int ping_count = 0;
  10981. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10982. enable_ping_pong =
  10983. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10984. "yes");
  10985. }
  10986. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10987. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10988. }
  10989. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10990. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10991. }
  10992. if (timeout <= 0.0) {
  10993. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10994. }
  10995. /* Enter data processing loop */
  10996. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10997. conn->request_info.remote_addr,
  10998. conn->request_info.remote_port);
  10999. conn->in_websocket_handling = 1;
  11000. mg_set_thread_name("wsock");
  11001. /* Loop continuously, reading messages from the socket, invoking the
  11002. * callback, and waiting repeatedly until an error occurs. */
  11003. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11004. && (!conn->must_close)) {
  11005. header_len = 0;
  11006. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11007. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11008. len = buf[1] & 127;
  11009. mask_len = (buf[1] & 128) ? 4 : 0;
  11010. if ((len < 126) && (body_len >= mask_len)) {
  11011. /* inline 7-bit length field */
  11012. data_len = len;
  11013. header_len = 2 + mask_len;
  11014. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11015. /* 16-bit length field */
  11016. header_len = 4 + mask_len;
  11017. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11018. } else if (body_len >= (10 + mask_len)) {
  11019. /* 64-bit length field */
  11020. uint32_t l1, l2;
  11021. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11022. memcpy(&l2, &buf[6], 4);
  11023. header_len = 10 + mask_len;
  11024. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11025. if (data_len > (uint64_t)0x7FFF0000ul) {
  11026. /* no can do */
  11027. mg_cry_internal(
  11028. conn,
  11029. "%s",
  11030. "websocket out of memory; closing connection");
  11031. break;
  11032. }
  11033. }
  11034. }
  11035. if ((header_len > 0) && (body_len >= header_len)) {
  11036. /* Allocate space to hold websocket payload */
  11037. unsigned char *data = mem;
  11038. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11039. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11040. conn->phys_ctx);
  11041. if (data == NULL) {
  11042. /* Allocation failed, exit the loop and then close the
  11043. * connection */
  11044. mg_cry_internal(
  11045. conn,
  11046. "%s",
  11047. "websocket out of memory; closing connection");
  11048. break;
  11049. }
  11050. }
  11051. /* Copy the mask before we shift the queue and destroy it */
  11052. if (mask_len > 0) {
  11053. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11054. } else {
  11055. memset(mask, 0, sizeof(mask));
  11056. }
  11057. /* Read frame payload from the first message in the queue into
  11058. * data and advance the queue by moving the memory in place. */
  11059. DEBUG_ASSERT(body_len >= header_len);
  11060. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11061. mop = buf[0]; /* current mask and opcode */
  11062. /* Overflow case */
  11063. len = body_len - header_len;
  11064. memcpy(data, buf + header_len, len);
  11065. error = 0;
  11066. while ((uint64_t)len < data_len) {
  11067. n = pull_inner(NULL,
  11068. conn,
  11069. (char *)(data + len),
  11070. (int)(data_len - len),
  11071. timeout);
  11072. if (n <= -2) {
  11073. error = 1;
  11074. break;
  11075. } else if (n > 0) {
  11076. len += (size_t)n;
  11077. } else {
  11078. /* Timeout: should retry */
  11079. /* TODO: retry condition */
  11080. }
  11081. }
  11082. if (error) {
  11083. mg_cry_internal(
  11084. conn,
  11085. "%s",
  11086. "Websocket pull failed; closing connection");
  11087. if (data != mem) {
  11088. mg_free(data);
  11089. }
  11090. break;
  11091. }
  11092. conn->data_len = conn->request_len;
  11093. } else {
  11094. mop = buf[0]; /* current mask and opcode, overwritten by
  11095. * memmove() */
  11096. /* Length of the message being read at the front of the
  11097. * queue. Cast to 31 bit is OK, since we limited
  11098. * data_len before. */
  11099. len = (size_t)data_len + header_len;
  11100. /* Copy the data payload into the data pointer for the
  11101. * callback. Cast to 31 bit is OK, since we
  11102. * limited data_len */
  11103. memcpy(data, buf + header_len, (size_t)data_len);
  11104. /* Move the queue forward len bytes */
  11105. memmove(buf, buf + len, body_len - len);
  11106. /* Mark the queue as advanced */
  11107. conn->data_len -= (int)len;
  11108. }
  11109. /* Apply mask if necessary */
  11110. if (mask_len > 0) {
  11111. for (i = 0; i < (size_t)data_len; i++) {
  11112. data[i] ^= mask[i & 3];
  11113. }
  11114. }
  11115. exit_by_callback = 0;
  11116. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11117. /* filter PONG messages */
  11118. DEBUG_TRACE("PONG from %s:%u",
  11119. conn->request_info.remote_addr,
  11120. conn->request_info.remote_port);
  11121. /* No unanwered PINGs left */
  11122. ping_count = 0;
  11123. } else if (enable_ping_pong
  11124. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11125. /* reply PING messages */
  11126. DEBUG_TRACE("Reply PING from %s:%u",
  11127. conn->request_info.remote_addr,
  11128. conn->request_info.remote_port);
  11129. ret = mg_websocket_write(conn,
  11130. MG_WEBSOCKET_OPCODE_PONG,
  11131. (char *)data,
  11132. (size_t)data_len);
  11133. if (ret <= 0) {
  11134. /* Error: send failed */
  11135. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11136. break;
  11137. }
  11138. } else {
  11139. /* Exit the loop if callback signals to exit (server side),
  11140. * or "connection close" opcode received (client side). */
  11141. if (ws_data_handler != NULL) {
  11142. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11143. if (mop & 0x40) {
  11144. /* Inflate the data received if bit RSV1 is set. */
  11145. if (!conn->websocket_deflate_initialized) {
  11146. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11147. exit_by_callback = 1;
  11148. }
  11149. if (!exit_by_callback) {
  11150. size_t inflate_buf_size_old = 0;
  11151. size_t inflate_buf_size =
  11152. data_len
  11153. * 10; // Initial guess of the inflated message
  11154. // size. We double the memory when needed.
  11155. Bytef *inflated;
  11156. Bytef *new_mem;
  11157. conn->websocket_inflate_state.avail_in =
  11158. (uInt)(data_len + 4);
  11159. conn->websocket_inflate_state.next_in = data;
  11160. // Add trailing 0x00 0x00 0xff 0xff bytes
  11161. data[data_len] = '\x00';
  11162. data[data_len + 1] = '\x00';
  11163. data[data_len + 2] = '\xff';
  11164. data[data_len + 3] = '\xff';
  11165. do {
  11166. if (inflate_buf_size_old == 0) {
  11167. new_mem = mg_calloc(inflate_buf_size,
  11168. sizeof(Bytef));
  11169. } else {
  11170. inflate_buf_size *= 2;
  11171. new_mem =
  11172. mg_realloc(inflated, inflate_buf_size);
  11173. }
  11174. if (new_mem == NULL) {
  11175. mg_cry_internal(
  11176. conn,
  11177. "Out of memory: Cannot allocate "
  11178. "inflate buffer of %zu bytes",
  11179. inflate_buf_size);
  11180. exit_by_callback = 1;
  11181. break;
  11182. }
  11183. inflated = new_mem;
  11184. conn->websocket_inflate_state.avail_out =
  11185. (uInt)(inflate_buf_size
  11186. - inflate_buf_size_old);
  11187. conn->websocket_inflate_state.next_out =
  11188. inflated + inflate_buf_size_old;
  11189. int ret =
  11190. inflate(&conn->websocket_inflate_state,
  11191. Z_SYNC_FLUSH);
  11192. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11193. || ret == Z_MEM_ERROR) {
  11194. mg_cry_internal(
  11195. conn,
  11196. "ZLIB inflate error: %i %s",
  11197. ret,
  11198. (conn->websocket_inflate_state.msg
  11199. ? conn->websocket_inflate_state.msg
  11200. : "<no error message>"));
  11201. exit_by_callback = 1;
  11202. break;
  11203. }
  11204. inflate_buf_size_old = inflate_buf_size;
  11205. } while (conn->websocket_inflate_state.avail_out
  11206. == 0);
  11207. inflate_buf_size -=
  11208. conn->websocket_inflate_state.avail_out;
  11209. if (!ws_data_handler(conn,
  11210. mop,
  11211. (char *)inflated,
  11212. inflate_buf_size,
  11213. callback_data)) {
  11214. exit_by_callback = 1;
  11215. }
  11216. mg_free(inflated);
  11217. }
  11218. } else
  11219. #endif
  11220. if (!ws_data_handler(conn,
  11221. mop,
  11222. (char *)data,
  11223. (size_t)data_len,
  11224. callback_data)) {
  11225. exit_by_callback = 1;
  11226. }
  11227. }
  11228. }
  11229. /* It a buffer has been allocated, free it again */
  11230. if (data != mem) {
  11231. mg_free(data);
  11232. }
  11233. if (exit_by_callback) {
  11234. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11235. conn->request_info.remote_addr,
  11236. conn->request_info.remote_port);
  11237. break;
  11238. }
  11239. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11240. /* Opcode == 8, connection close */
  11241. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11242. conn->request_info.remote_addr,
  11243. conn->request_info.remote_port);
  11244. break;
  11245. }
  11246. /* Not breaking the loop, process next websocket frame. */
  11247. } else {
  11248. /* Read from the socket into the next available location in the
  11249. * message queue. */
  11250. n = pull_inner(NULL,
  11251. conn,
  11252. conn->buf + conn->data_len,
  11253. conn->buf_size - conn->data_len,
  11254. timeout);
  11255. if (n <= -2) {
  11256. /* Error, no bytes read */
  11257. DEBUG_TRACE("PULL from %s:%u failed",
  11258. conn->request_info.remote_addr,
  11259. conn->request_info.remote_port);
  11260. break;
  11261. }
  11262. if (n > 0) {
  11263. conn->data_len += n;
  11264. /* Reset open PING count */
  11265. ping_count = 0;
  11266. } else {
  11267. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11268. && (!conn->must_close)) {
  11269. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11270. /* Stop sending PING */
  11271. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11272. "- closing connection",
  11273. ping_count,
  11274. conn->request_info.remote_addr,
  11275. conn->request_info.remote_port);
  11276. break;
  11277. }
  11278. if (enable_ping_pong) {
  11279. /* Send Websocket PING message */
  11280. DEBUG_TRACE("PING to %s:%u",
  11281. conn->request_info.remote_addr,
  11282. conn->request_info.remote_port);
  11283. ret = mg_websocket_write(conn,
  11284. MG_WEBSOCKET_OPCODE_PING,
  11285. NULL,
  11286. 0);
  11287. if (ret <= 0) {
  11288. /* Error: send failed */
  11289. DEBUG_TRACE("Send PING failed (%i)", ret);
  11290. break;
  11291. }
  11292. ping_count++;
  11293. }
  11294. }
  11295. /* Timeout: should retry */
  11296. /* TODO: get timeout def */
  11297. }
  11298. }
  11299. }
  11300. /* Leave data processing loop */
  11301. mg_set_thread_name("worker");
  11302. conn->in_websocket_handling = 0;
  11303. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11304. conn->request_info.remote_addr,
  11305. conn->request_info.remote_port);
  11306. }
  11307. static int
  11308. mg_websocket_write_exec(struct mg_connection *conn,
  11309. int opcode,
  11310. const char *data,
  11311. size_t dataLen,
  11312. uint32_t masking_key)
  11313. {
  11314. unsigned char header[14];
  11315. size_t headerLen;
  11316. int retval;
  11317. #if defined(GCC_DIAGNOSTIC)
  11318. /* Disable spurious conversion warning for GCC */
  11319. #pragma GCC diagnostic push
  11320. #pragma GCC diagnostic ignored "-Wconversion"
  11321. #endif
  11322. /* Note that POSIX/Winsock's send() is threadsafe
  11323. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11324. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11325. * push(), although that is only a problem if the packet is large or
  11326. * outgoing buffer is full). */
  11327. /* TODO: Check if this lock should be moved to user land.
  11328. * Currently the server sets this lock for websockets, but
  11329. * not for any other connection. It must be set for every
  11330. * conn read/written by more than one thread, no matter if
  11331. * it is a websocket or regular connection. */
  11332. (void)mg_lock_connection(conn);
  11333. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11334. size_t deflated_size;
  11335. Bytef *deflated;
  11336. // Deflate websocket messages over 100kb
  11337. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11338. if (use_deflate) {
  11339. if (!conn->websocket_deflate_initialized) {
  11340. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11341. return 0;
  11342. }
  11343. // Deflating the message
  11344. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11345. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11346. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11347. deflated_size = compressBound((uLong)dataLen);
  11348. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11349. if (deflated == NULL) {
  11350. mg_cry_internal(
  11351. conn,
  11352. "Out of memory: Cannot allocate deflate buffer of %zu bytes",
  11353. deflated_size);
  11354. mg_unlock_connection(conn);
  11355. return -1;
  11356. }
  11357. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11358. conn->websocket_deflate_state.next_out = deflated;
  11359. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11360. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11361. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11362. } else
  11363. #endif
  11364. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11365. #if defined(GCC_DIAGNOSTIC)
  11366. #pragma GCC diagnostic pop
  11367. #endif
  11368. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11369. if (dataLen < 126) {
  11370. /* inline 7-bit length field */
  11371. header[1] = (unsigned char)dataLen;
  11372. headerLen = 2;
  11373. } else if (dataLen <= 0xFFFF) {
  11374. /* 16-bit length field */
  11375. uint16_t len = htons((uint16_t)dataLen);
  11376. header[1] = 126;
  11377. memcpy(header + 2, &len, 2);
  11378. headerLen = 4;
  11379. } else {
  11380. /* 64-bit length field */
  11381. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11382. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11383. header[1] = 127;
  11384. memcpy(header + 2, &len1, 4);
  11385. memcpy(header + 6, &len2, 4);
  11386. headerLen = 10;
  11387. }
  11388. if (masking_key) {
  11389. /* add mask */
  11390. header[1] |= 0x80;
  11391. memcpy(header + headerLen, &masking_key, 4);
  11392. headerLen += 4;
  11393. }
  11394. retval = mg_write(conn, header, headerLen);
  11395. if (retval != (int)headerLen) {
  11396. /* Did not send complete header */
  11397. retval = -1;
  11398. } else {
  11399. if (dataLen > 0) {
  11400. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11401. if (use_deflate) {
  11402. retval = mg_write(conn, deflated, dataLen);
  11403. mg_free(deflated);
  11404. } else
  11405. #endif
  11406. retval = mg_write(conn, data, dataLen);
  11407. }
  11408. /* if dataLen == 0, the header length (2) is returned */
  11409. }
  11410. /* TODO: Remove this unlock as well, when lock is removed. */
  11411. mg_unlock_connection(conn);
  11412. return retval;
  11413. }
  11414. int
  11415. mg_websocket_write(struct mg_connection *conn,
  11416. int opcode,
  11417. const char *data,
  11418. size_t dataLen)
  11419. {
  11420. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11421. }
  11422. static void
  11423. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11424. {
  11425. size_t i = 0;
  11426. i = 0;
  11427. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11428. /* Convert in 32 bit words, if data is 4 byte aligned */
  11429. while (i < (in_len - 3)) {
  11430. *(uint32_t *)(void *)(out + i) =
  11431. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11432. i += 4;
  11433. }
  11434. }
  11435. if (i != in_len) {
  11436. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11437. while (i < in_len) {
  11438. *(uint8_t *)(void *)(out + i) =
  11439. *(uint8_t *)(void *)(in + i)
  11440. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11441. i++;
  11442. }
  11443. }
  11444. }
  11445. int
  11446. mg_websocket_client_write(struct mg_connection *conn,
  11447. int opcode,
  11448. const char *data,
  11449. size_t dataLen)
  11450. {
  11451. int retval = -1;
  11452. char *masked_data =
  11453. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11454. uint32_t masking_key = 0;
  11455. if (masked_data == NULL) {
  11456. /* Return -1 in an error case */
  11457. mg_cry_internal(conn,
  11458. "%s",
  11459. "Cannot allocate buffer for masked websocket response: "
  11460. "Out of memory");
  11461. return -1;
  11462. }
  11463. do {
  11464. /* Get a masking key - but not 0 */
  11465. masking_key = (uint32_t)get_random();
  11466. } while (masking_key == 0);
  11467. mask_data(data, dataLen, masking_key, masked_data);
  11468. retval = mg_websocket_write_exec(
  11469. conn, opcode, masked_data, dataLen, masking_key);
  11470. mg_free(masked_data);
  11471. return retval;
  11472. }
  11473. static void
  11474. handle_websocket_request(struct mg_connection *conn,
  11475. const char *path,
  11476. int is_callback_resource,
  11477. struct mg_websocket_subprotocols *subprotocols,
  11478. mg_websocket_connect_handler ws_connect_handler,
  11479. mg_websocket_ready_handler ws_ready_handler,
  11480. mg_websocket_data_handler ws_data_handler,
  11481. mg_websocket_close_handler ws_close_handler,
  11482. void *cbData)
  11483. {
  11484. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11485. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11486. ptrdiff_t lua_websock = 0;
  11487. #if !defined(USE_LUA)
  11488. (void)path;
  11489. #endif
  11490. /* Step 1: Check websocket protocol version. */
  11491. /* Step 1.1: Check Sec-WebSocket-Key. */
  11492. if (!websock_key) {
  11493. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11494. * requires a Sec-WebSocket-Key header.
  11495. */
  11496. /* It could be the hixie draft version
  11497. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11498. */
  11499. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11500. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11501. char key3[8];
  11502. if ((key1 != NULL) && (key2 != NULL)) {
  11503. /* This version uses 8 byte body data in a GET request */
  11504. conn->content_len = 8;
  11505. if (8 == mg_read(conn, key3, 8)) {
  11506. /* This is the hixie version */
  11507. mg_send_http_error(conn,
  11508. 426,
  11509. "%s",
  11510. "Protocol upgrade to RFC 6455 required");
  11511. return;
  11512. }
  11513. }
  11514. /* This is an unknown version */
  11515. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11516. return;
  11517. }
  11518. /* Step 1.2: Check websocket protocol version. */
  11519. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11520. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11521. /* Reject wrong versions */
  11522. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11523. return;
  11524. }
  11525. /* Step 1.3: Could check for "Host", but we do not really nead this
  11526. * value for anything, so just ignore it. */
  11527. /* Step 2: If a callback is responsible, call it. */
  11528. if (is_callback_resource) {
  11529. /* Step 2.1 check and select subprotocol */
  11530. const char *protocols[64]; // max 64 headers
  11531. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11532. "Sec-WebSocket-Protocol",
  11533. protocols,
  11534. 64);
  11535. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11536. int cnt = 0;
  11537. int idx;
  11538. unsigned long len;
  11539. const char *sep, *curSubProtocol,
  11540. *acceptedWebSocketSubprotocol = NULL;
  11541. /* look for matching subprotocol */
  11542. do {
  11543. const char *protocol = protocols[cnt];
  11544. do {
  11545. sep = strchr(protocol, ',');
  11546. curSubProtocol = protocol;
  11547. len = sep ? (unsigned long)(sep - protocol)
  11548. : (unsigned long)strlen(protocol);
  11549. while (sep && isspace((unsigned char)*++sep))
  11550. ; // ignore leading whitespaces
  11551. protocol = sep;
  11552. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11553. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11554. && (strncmp(curSubProtocol,
  11555. subprotocols->subprotocols[idx],
  11556. len)
  11557. == 0)) {
  11558. acceptedWebSocketSubprotocol =
  11559. subprotocols->subprotocols[idx];
  11560. break;
  11561. }
  11562. }
  11563. } while (sep && !acceptedWebSocketSubprotocol);
  11564. } while (++cnt < nbSubprotocolHeader
  11565. && !acceptedWebSocketSubprotocol);
  11566. conn->request_info.acceptedWebSocketSubprotocol =
  11567. acceptedWebSocketSubprotocol;
  11568. } else if (nbSubprotocolHeader > 0) {
  11569. /* keep legacy behavior */
  11570. const char *protocol = protocols[0];
  11571. /* The protocol is a comma separated list of names. */
  11572. /* The server must only return one value from this list. */
  11573. /* First check if it is a list or just a single value. */
  11574. const char *sep = strrchr(protocol, ',');
  11575. if (sep == NULL) {
  11576. /* Just a single protocol -> accept it. */
  11577. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11578. } else {
  11579. /* Multiple protocols -> accept the last one. */
  11580. /* This is just a quick fix if the client offers multiple
  11581. * protocols. The handler should have a list of accepted
  11582. * protocols on his own
  11583. * and use it to select one protocol among those the client
  11584. * has
  11585. * offered.
  11586. */
  11587. while (isspace((unsigned char)*++sep)) {
  11588. ; /* ignore leading whitespaces */
  11589. }
  11590. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11591. }
  11592. }
  11593. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11594. websocket_deflate_negotiate(conn);
  11595. #endif
  11596. if ((ws_connect_handler != NULL)
  11597. && (ws_connect_handler(conn, cbData) != 0)) {
  11598. /* C callback has returned non-zero, do not proceed with
  11599. * handshake.
  11600. */
  11601. /* Note that C callbacks are no longer called when Lua is
  11602. * responsible, so C can no longer filter callbacks for Lua. */
  11603. return;
  11604. }
  11605. }
  11606. #if defined(USE_LUA)
  11607. /* Step 3: No callback. Check if Lua is responsible. */
  11608. else {
  11609. /* Step 3.1: Check if Lua is responsible. */
  11610. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11611. lua_websock = match_prefix_strlen(
  11612. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11613. }
  11614. if (lua_websock) {
  11615. /* Step 3.2: Lua is responsible: call it. */
  11616. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11617. if (!conn->lua_websocket_state) {
  11618. /* Lua rejected the new client */
  11619. return;
  11620. }
  11621. }
  11622. }
  11623. #endif
  11624. /* Step 4: Check if there is a responsible websocket handler. */
  11625. if (!is_callback_resource && !lua_websock) {
  11626. /* There is no callback, and Lua is not responsible either. */
  11627. /* Reply with a 404 Not Found. We are still at a standard
  11628. * HTTP request here, before the websocket handshake, so
  11629. * we can still send standard HTTP error replies. */
  11630. mg_send_http_error(conn, 404, "%s", "Not found");
  11631. return;
  11632. }
  11633. /* Step 5: The websocket connection has been accepted */
  11634. if (!send_websocket_handshake(conn, websock_key)) {
  11635. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11636. return;
  11637. }
  11638. /* Step 6: Call the ready handler */
  11639. if (is_callback_resource) {
  11640. if (ws_ready_handler != NULL) {
  11641. ws_ready_handler(conn, cbData);
  11642. }
  11643. #if defined(USE_LUA)
  11644. } else if (lua_websock) {
  11645. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11646. /* the ready handler returned false */
  11647. return;
  11648. }
  11649. #endif
  11650. }
  11651. /* Step 7: Enter the read loop */
  11652. if (is_callback_resource) {
  11653. read_websocket(conn, ws_data_handler, cbData);
  11654. #if defined(USE_LUA)
  11655. } else if (lua_websock) {
  11656. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11657. #endif
  11658. }
  11659. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11660. /* Step 8: Close the deflate & inflate buffers */
  11661. if (conn->websocket_deflate_initialized) {
  11662. deflateEnd(&conn->websocket_deflate_state);
  11663. inflateEnd(&conn->websocket_inflate_state);
  11664. }
  11665. #endif
  11666. /* Step 9: Call the close handler */
  11667. if (ws_close_handler) {
  11668. ws_close_handler(conn, cbData);
  11669. }
  11670. }
  11671. #endif /* !USE_WEBSOCKET */
  11672. /* Is upgrade request:
  11673. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11674. * 1 = upgrade to websocket
  11675. * 2 = upgrade to HTTP/2
  11676. * -1 = upgrade to unknown protocol
  11677. */
  11678. static int
  11679. should_switch_to_protocol(const struct mg_connection *conn)
  11680. {
  11681. const char *upgrade, *connection;
  11682. /* A websocket protocoll has the following HTTP headers:
  11683. *
  11684. * Connection: Upgrade
  11685. * Upgrade: Websocket
  11686. */
  11687. connection = mg_get_header(conn, "Connection");
  11688. if (connection == NULL) {
  11689. return PROTOCOL_TYPE_HTTP1;
  11690. }
  11691. if (!mg_strcasestr(connection, "upgrade")) {
  11692. return PROTOCOL_TYPE_HTTP1;
  11693. }
  11694. upgrade = mg_get_header(conn, "Upgrade");
  11695. if (upgrade == NULL) {
  11696. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11697. return -1;
  11698. }
  11699. /* Upgrade to ... */
  11700. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11701. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11702. * "Sec-WebSocket-Version" are also required.
  11703. * Don't check them here, since even an unsupported websocket protocol
  11704. * request still IS a websocket request (in contrast to a standard HTTP
  11705. * request). It will fail later in handle_websocket_request.
  11706. */
  11707. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11708. }
  11709. if (0 != mg_strcasestr(upgrade, "h2")) {
  11710. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11711. }
  11712. /* Upgrade to another protocol */
  11713. return -1;
  11714. }
  11715. static int
  11716. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11717. {
  11718. int n;
  11719. unsigned int a, b, c, d, slash;
  11720. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11721. slash = 32;
  11722. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11723. n = 0;
  11724. }
  11725. }
  11726. if ((n > 0) && ((size_t)n == vec->len)) {
  11727. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11728. /* IPv4 format */
  11729. if (sa->sa.sa_family == AF_INET) {
  11730. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11731. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11732. | ((uint32_t)c << 8) | (uint32_t)d;
  11733. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11734. return (ip & mask) == net;
  11735. }
  11736. return 0;
  11737. }
  11738. }
  11739. #if defined(USE_IPV6)
  11740. else {
  11741. char ad[50];
  11742. const char *p;
  11743. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11744. slash = 128;
  11745. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11746. n = 0;
  11747. }
  11748. }
  11749. if ((n <= 0) && no_strict) {
  11750. /* no square brackets? */
  11751. p = strchr(vec->ptr, '/');
  11752. if (p && (p < (vec->ptr + vec->len))) {
  11753. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11754. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11755. n += (int)(p - vec->ptr);
  11756. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11757. } else {
  11758. n = 0;
  11759. }
  11760. } else if (vec->len < sizeof(ad)) {
  11761. n = (int)vec->len;
  11762. slash = 128;
  11763. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11764. }
  11765. }
  11766. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11767. p = ad;
  11768. c = 0;
  11769. /* zone indexes are unsupported, at least two colons are needed */
  11770. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11771. if (*(p++) == ':') {
  11772. c++;
  11773. }
  11774. }
  11775. if ((*p == '\0') && (c >= 2)) {
  11776. struct sockaddr_in6 sin6;
  11777. unsigned int i;
  11778. /* for strict validation, an actual IPv6 argument is needed */
  11779. if (sa->sa.sa_family != AF_INET6) {
  11780. return 0;
  11781. }
  11782. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11783. /* IPv6 format */
  11784. for (i = 0; i < 16; i++) {
  11785. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11786. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11787. uint8_t mask = 0;
  11788. if (8 * i + 8 < slash) {
  11789. mask = 0xFFu;
  11790. } else if (8 * i < slash) {
  11791. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11792. }
  11793. if ((ip & mask) != net) {
  11794. return 0;
  11795. }
  11796. }
  11797. return 1;
  11798. }
  11799. }
  11800. }
  11801. }
  11802. #else
  11803. (void)no_strict;
  11804. #endif
  11805. /* malformed */
  11806. return -1;
  11807. }
  11808. static int
  11809. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11810. {
  11811. int throttle = 0;
  11812. struct vec vec, val;
  11813. char mult;
  11814. double v;
  11815. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11816. mult = ',';
  11817. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11818. || (v < 0)
  11819. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11820. && (mult != ','))) {
  11821. continue;
  11822. }
  11823. v *= (lowercase(&mult) == 'k')
  11824. ? 1024
  11825. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11826. if (vec.len == 1 && vec.ptr[0] == '*') {
  11827. throttle = (int)v;
  11828. } else {
  11829. int matched = parse_match_net(&vec, rsa, 0);
  11830. if (matched >= 0) {
  11831. /* a valid IP subnet */
  11832. if (matched) {
  11833. throttle = (int)v;
  11834. }
  11835. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11836. throttle = (int)v;
  11837. }
  11838. }
  11839. }
  11840. return throttle;
  11841. }
  11842. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11843. #include "handle_form.inl"
  11844. static int
  11845. get_first_ssl_listener_index(const struct mg_context *ctx)
  11846. {
  11847. unsigned int i;
  11848. int idx = -1;
  11849. if (ctx) {
  11850. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11851. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11852. }
  11853. }
  11854. return idx;
  11855. }
  11856. /* Return host (without port) */
  11857. static void
  11858. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11859. {
  11860. const char *host_header =
  11861. get_header(ri->http_headers, ri->num_headers, "Host");
  11862. host->ptr = NULL;
  11863. host->len = 0;
  11864. if (host_header != NULL) {
  11865. char *pos;
  11866. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11867. * is found. */
  11868. if (*host_header == '[') {
  11869. pos = strchr(host_header, ']');
  11870. if (!pos) {
  11871. /* Malformed hostname starts with '[', but no ']' found */
  11872. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11873. return;
  11874. }
  11875. /* terminate after ']' */
  11876. host->ptr = host_header;
  11877. host->len = (size_t)(pos + 1 - host_header);
  11878. } else {
  11879. /* Otherwise, a ':' separates hostname and port number */
  11880. pos = strchr(host_header, ':');
  11881. if (pos != NULL) {
  11882. host->len = (size_t)(pos - host_header);
  11883. } else {
  11884. host->len = strlen(host_header);
  11885. }
  11886. host->ptr = host_header;
  11887. }
  11888. }
  11889. }
  11890. static int
  11891. switch_domain_context(struct mg_connection *conn)
  11892. {
  11893. struct vec host;
  11894. get_host_from_request_info(&host, &conn->request_info);
  11895. if (host.ptr) {
  11896. if (conn->ssl) {
  11897. /* This is a HTTPS connection, maybe we have a hostname
  11898. * from SNI (set in ssl_servername_callback). */
  11899. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11900. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11901. /* We are not using the default domain */
  11902. if ((strlen(sslhost) != host.len)
  11903. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11904. /* Mismatch between SNI domain and HTTP domain */
  11905. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11906. sslhost,
  11907. (int)host.len,
  11908. host.ptr);
  11909. return 0;
  11910. }
  11911. }
  11912. } else {
  11913. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11914. while (dom) {
  11915. if ((strlen(dom->config[AUTHENTICATION_DOMAIN]) == host.len)
  11916. && !mg_strncasecmp(host.ptr,
  11917. dom->config[AUTHENTICATION_DOMAIN],
  11918. host.len)) {
  11919. /* Found matching domain */
  11920. DEBUG_TRACE("HTTP domain %s found",
  11921. dom->config[AUTHENTICATION_DOMAIN]);
  11922. /* TODO: Check if this is a HTTP or HTTPS domain */
  11923. conn->dom_ctx = dom;
  11924. break;
  11925. }
  11926. mg_lock_context(conn->phys_ctx);
  11927. dom = dom->next;
  11928. mg_unlock_context(conn->phys_ctx);
  11929. }
  11930. }
  11931. } else {
  11932. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11933. return 1;
  11934. }
  11935. DEBUG_TRACE("HTTP%s Host: %.*s",
  11936. conn->ssl ? "S" : "",
  11937. (int)host.len,
  11938. host.ptr);
  11939. return 1;
  11940. }
  11941. static int mg_construct_local_link(const struct mg_connection *conn,
  11942. char *buf,
  11943. size_t buflen,
  11944. const char *define_proto,
  11945. int define_port,
  11946. const char *define_uri);
  11947. static void
  11948. redirect_to_https_port(struct mg_connection *conn, int port)
  11949. {
  11950. char target_url[MG_BUF_LEN];
  11951. int truncated = 0;
  11952. const char *expect_proto =
  11953. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11954. /* Use "308 Permanent Redirect" */
  11955. int redirect_code = 308;
  11956. /* In any case, close the current connection */
  11957. conn->must_close = 1;
  11958. /* Send host, port, uri and (if it exists) ?query_string */
  11959. if (mg_construct_local_link(
  11960. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11961. < 0) {
  11962. truncated = 1;
  11963. } else if (conn->request_info.query_string != NULL) {
  11964. size_t slen1 = strlen(target_url);
  11965. size_t slen2 = strlen(conn->request_info.query_string);
  11966. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11967. target_url[slen1] = '?';
  11968. memcpy(target_url + slen1 + 1,
  11969. conn->request_info.query_string,
  11970. slen2);
  11971. target_url[slen1 + slen2 + 1] = 0;
  11972. } else {
  11973. truncated = 1;
  11974. }
  11975. }
  11976. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11977. * is used as buffer size) */
  11978. if (truncated) {
  11979. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11980. return;
  11981. }
  11982. /* Use redirect helper function */
  11983. mg_send_http_redirect(conn, target_url, redirect_code);
  11984. }
  11985. static void
  11986. mg_set_handler_type(struct mg_context *phys_ctx,
  11987. struct mg_domain_context *dom_ctx,
  11988. const char *uri,
  11989. int handler_type,
  11990. int is_delete_request,
  11991. mg_request_handler handler,
  11992. struct mg_websocket_subprotocols *subprotocols,
  11993. mg_websocket_connect_handler connect_handler,
  11994. mg_websocket_ready_handler ready_handler,
  11995. mg_websocket_data_handler data_handler,
  11996. mg_websocket_close_handler close_handler,
  11997. mg_authorization_handler auth_handler,
  11998. void *cbdata)
  11999. {
  12000. struct mg_handler_info *tmp_rh, **lastref;
  12001. size_t urilen = strlen(uri);
  12002. if (handler_type == WEBSOCKET_HANDLER) {
  12003. DEBUG_ASSERT(handler == NULL);
  12004. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12005. || ready_handler != NULL || data_handler != NULL
  12006. || close_handler != NULL);
  12007. DEBUG_ASSERT(auth_handler == NULL);
  12008. if (handler != NULL) {
  12009. return;
  12010. }
  12011. if (!is_delete_request && (connect_handler == NULL)
  12012. && (ready_handler == NULL) && (data_handler == NULL)
  12013. && (close_handler == NULL)) {
  12014. return;
  12015. }
  12016. if (auth_handler != NULL) {
  12017. return;
  12018. }
  12019. } else if (handler_type == REQUEST_HANDLER) {
  12020. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12021. && data_handler == NULL && close_handler == NULL);
  12022. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12023. DEBUG_ASSERT(auth_handler == NULL);
  12024. if ((connect_handler != NULL) || (ready_handler != NULL)
  12025. || (data_handler != NULL) || (close_handler != NULL)) {
  12026. return;
  12027. }
  12028. if (!is_delete_request && (handler == NULL)) {
  12029. return;
  12030. }
  12031. if (auth_handler != NULL) {
  12032. return;
  12033. }
  12034. } else if (handler_type == AUTH_HANDLER) {
  12035. DEBUG_ASSERT(handler == NULL);
  12036. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12037. && data_handler == NULL && close_handler == NULL);
  12038. DEBUG_ASSERT(!is_delete_request && (auth_handler != NULL));
  12039. if (handler != NULL) {
  12040. return;
  12041. }
  12042. if ((connect_handler != NULL) || (ready_handler != NULL)
  12043. || (data_handler != NULL) || (close_handler != NULL)) {
  12044. return;
  12045. }
  12046. if (!is_delete_request && (auth_handler == NULL)) {
  12047. return;
  12048. }
  12049. } else {
  12050. /* Unknown handler type. */
  12051. return;
  12052. }
  12053. if (!phys_ctx || !dom_ctx) {
  12054. /* no context available */
  12055. return;
  12056. }
  12057. mg_lock_context(phys_ctx);
  12058. /* first try to find an existing handler */
  12059. do {
  12060. lastref = &(dom_ctx->handlers);
  12061. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12062. tmp_rh = tmp_rh->next) {
  12063. if (tmp_rh->handler_type == handler_type
  12064. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12065. if (!is_delete_request) {
  12066. /* update existing handler */
  12067. if (handler_type == REQUEST_HANDLER) {
  12068. /* Wait for end of use before updating */
  12069. if (tmp_rh->refcount) {
  12070. mg_unlock_context(phys_ctx);
  12071. mg_sleep(1);
  12072. mg_lock_context(phys_ctx);
  12073. /* tmp_rh might have been freed, search again. */
  12074. break;
  12075. }
  12076. /* Ok, the handler is no more use -> Update it */
  12077. tmp_rh->handler = handler;
  12078. } else if (handler_type == WEBSOCKET_HANDLER) {
  12079. tmp_rh->subprotocols = subprotocols;
  12080. tmp_rh->connect_handler = connect_handler;
  12081. tmp_rh->ready_handler = ready_handler;
  12082. tmp_rh->data_handler = data_handler;
  12083. tmp_rh->close_handler = close_handler;
  12084. } else { /* AUTH_HANDLER */
  12085. tmp_rh->auth_handler = auth_handler;
  12086. }
  12087. tmp_rh->cbdata = cbdata;
  12088. } else {
  12089. /* remove existing handler */
  12090. if (handler_type == REQUEST_HANDLER) {
  12091. /* Wait for end of use before removing */
  12092. if (tmp_rh->refcount) {
  12093. tmp_rh->removing = 1;
  12094. mg_unlock_context(phys_ctx);
  12095. mg_sleep(1);
  12096. mg_lock_context(phys_ctx);
  12097. /* tmp_rh might have been freed, search again. */
  12098. break;
  12099. }
  12100. /* Ok, the handler is no more used */
  12101. }
  12102. *lastref = tmp_rh->next;
  12103. mg_free(tmp_rh->uri);
  12104. mg_free(tmp_rh);
  12105. }
  12106. mg_unlock_context(phys_ctx);
  12107. return;
  12108. }
  12109. lastref = &(tmp_rh->next);
  12110. }
  12111. } while (tmp_rh != NULL);
  12112. if (is_delete_request) {
  12113. /* no handler to set, this was a remove request to a non-existing
  12114. * handler */
  12115. mg_unlock_context(phys_ctx);
  12116. return;
  12117. }
  12118. tmp_rh =
  12119. (struct mg_handler_info *)mg_calloc_ctx(1,
  12120. sizeof(struct mg_handler_info),
  12121. phys_ctx);
  12122. if (tmp_rh == NULL) {
  12123. mg_unlock_context(phys_ctx);
  12124. mg_cry_ctx_internal(phys_ctx,
  12125. "%s",
  12126. "Cannot create new request handler struct, OOM");
  12127. return;
  12128. }
  12129. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12130. if (!tmp_rh->uri) {
  12131. mg_unlock_context(phys_ctx);
  12132. mg_free(tmp_rh);
  12133. mg_cry_ctx_internal(phys_ctx,
  12134. "%s",
  12135. "Cannot create new request handler struct, OOM");
  12136. return;
  12137. }
  12138. tmp_rh->uri_len = urilen;
  12139. if (handler_type == REQUEST_HANDLER) {
  12140. tmp_rh->refcount = 0;
  12141. tmp_rh->removing = 0;
  12142. tmp_rh->handler = handler;
  12143. } else if (handler_type == WEBSOCKET_HANDLER) {
  12144. tmp_rh->subprotocols = subprotocols;
  12145. tmp_rh->connect_handler = connect_handler;
  12146. tmp_rh->ready_handler = ready_handler;
  12147. tmp_rh->data_handler = data_handler;
  12148. tmp_rh->close_handler = close_handler;
  12149. } else { /* AUTH_HANDLER */
  12150. tmp_rh->auth_handler = auth_handler;
  12151. }
  12152. tmp_rh->cbdata = cbdata;
  12153. tmp_rh->handler_type = handler_type;
  12154. tmp_rh->next = NULL;
  12155. *lastref = tmp_rh;
  12156. mg_unlock_context(phys_ctx);
  12157. }
  12158. void
  12159. mg_set_request_handler(struct mg_context *ctx,
  12160. const char *uri,
  12161. mg_request_handler handler,
  12162. void *cbdata)
  12163. {
  12164. mg_set_handler_type(ctx,
  12165. &(ctx->dd),
  12166. uri,
  12167. REQUEST_HANDLER,
  12168. handler == NULL,
  12169. handler,
  12170. NULL,
  12171. NULL,
  12172. NULL,
  12173. NULL,
  12174. NULL,
  12175. NULL,
  12176. cbdata);
  12177. }
  12178. void
  12179. mg_set_websocket_handler(struct mg_context *ctx,
  12180. const char *uri,
  12181. mg_websocket_connect_handler connect_handler,
  12182. mg_websocket_ready_handler ready_handler,
  12183. mg_websocket_data_handler data_handler,
  12184. mg_websocket_close_handler close_handler,
  12185. void *cbdata)
  12186. {
  12187. mg_set_websocket_handler_with_subprotocols(ctx,
  12188. uri,
  12189. NULL,
  12190. connect_handler,
  12191. ready_handler,
  12192. data_handler,
  12193. close_handler,
  12194. cbdata);
  12195. }
  12196. void
  12197. mg_set_websocket_handler_with_subprotocols(
  12198. struct mg_context *ctx,
  12199. const char *uri,
  12200. struct mg_websocket_subprotocols *subprotocols,
  12201. mg_websocket_connect_handler connect_handler,
  12202. mg_websocket_ready_handler ready_handler,
  12203. mg_websocket_data_handler data_handler,
  12204. mg_websocket_close_handler close_handler,
  12205. void *cbdata)
  12206. {
  12207. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12208. && (data_handler == NULL)
  12209. && (close_handler == NULL);
  12210. mg_set_handler_type(ctx,
  12211. &(ctx->dd),
  12212. uri,
  12213. WEBSOCKET_HANDLER,
  12214. is_delete_request,
  12215. NULL,
  12216. subprotocols,
  12217. connect_handler,
  12218. ready_handler,
  12219. data_handler,
  12220. close_handler,
  12221. NULL,
  12222. cbdata);
  12223. }
  12224. void
  12225. mg_set_auth_handler(struct mg_context *ctx,
  12226. const char *uri,
  12227. mg_authorization_handler handler,
  12228. void *cbdata)
  12229. {
  12230. mg_set_handler_type(ctx,
  12231. &(ctx->dd),
  12232. uri,
  12233. AUTH_HANDLER,
  12234. handler == NULL,
  12235. NULL,
  12236. NULL,
  12237. NULL,
  12238. NULL,
  12239. NULL,
  12240. NULL,
  12241. handler,
  12242. cbdata);
  12243. }
  12244. static int
  12245. get_request_handler(struct mg_connection *conn,
  12246. int handler_type,
  12247. mg_request_handler *handler,
  12248. struct mg_websocket_subprotocols **subprotocols,
  12249. mg_websocket_connect_handler *connect_handler,
  12250. mg_websocket_ready_handler *ready_handler,
  12251. mg_websocket_data_handler *data_handler,
  12252. mg_websocket_close_handler *close_handler,
  12253. mg_authorization_handler *auth_handler,
  12254. void **cbdata,
  12255. struct mg_handler_info **handler_info)
  12256. {
  12257. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12258. if (request_info) {
  12259. const char *uri = request_info->local_uri;
  12260. size_t urilen = strlen(uri);
  12261. struct mg_handler_info *tmp_rh;
  12262. int step, matched;
  12263. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12264. return 0;
  12265. }
  12266. mg_lock_context(conn->phys_ctx);
  12267. for (step = 0; step < 3; step++) {
  12268. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12269. tmp_rh = tmp_rh->next) {
  12270. if (tmp_rh->handler_type != handler_type) {
  12271. continue;
  12272. }
  12273. if (step == 0) {
  12274. /* first try for an exact match */
  12275. matched = (tmp_rh->uri_len == urilen)
  12276. && (strcmp(tmp_rh->uri, uri) == 0);
  12277. } else if (step == 1) {
  12278. /* next try for a partial match, we will accept
  12279. uri/something */
  12280. matched =
  12281. (tmp_rh->uri_len < urilen)
  12282. && (uri[tmp_rh->uri_len] == '/')
  12283. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12284. } else {
  12285. /* finally try for pattern match */
  12286. matched =
  12287. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12288. }
  12289. if (matched) {
  12290. if (handler_type == WEBSOCKET_HANDLER) {
  12291. *subprotocols = tmp_rh->subprotocols;
  12292. *connect_handler = tmp_rh->connect_handler;
  12293. *ready_handler = tmp_rh->ready_handler;
  12294. *data_handler = tmp_rh->data_handler;
  12295. *close_handler = tmp_rh->close_handler;
  12296. } else if (handler_type == REQUEST_HANDLER) {
  12297. if (tmp_rh->removing) {
  12298. /* Treat as none found */
  12299. step = 2;
  12300. break;
  12301. }
  12302. *handler = tmp_rh->handler;
  12303. /* Acquire handler and give it back */
  12304. tmp_rh->refcount++;
  12305. *handler_info = tmp_rh;
  12306. } else { /* AUTH_HANDLER */
  12307. *auth_handler = tmp_rh->auth_handler;
  12308. }
  12309. *cbdata = tmp_rh->cbdata;
  12310. mg_unlock_context(conn->phys_ctx);
  12311. return 1;
  12312. }
  12313. }
  12314. }
  12315. mg_unlock_context(conn->phys_ctx);
  12316. }
  12317. return 0; /* none found */
  12318. }
  12319. /* Check if the script file is in a path, allowed for script files.
  12320. * This can be used if uploading files is possible not only for the server
  12321. * admin, and the upload mechanism does not check the file extension.
  12322. */
  12323. static int
  12324. is_in_script_path(const struct mg_connection *conn, const char *path)
  12325. {
  12326. /* TODO (Feature): Add config value for allowed script path.
  12327. * Default: All allowed. */
  12328. (void)conn;
  12329. (void)path;
  12330. return 1;
  12331. }
  12332. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12333. static int
  12334. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12335. int bits,
  12336. char *data,
  12337. size_t len,
  12338. void *cbdata)
  12339. {
  12340. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12341. if (pcallbacks->websocket_data) {
  12342. return pcallbacks->websocket_data(conn, bits, data, len);
  12343. }
  12344. /* No handler set - assume "OK" */
  12345. return 1;
  12346. }
  12347. static void
  12348. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12349. void *cbdata)
  12350. {
  12351. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12352. if (pcallbacks->connection_close) {
  12353. pcallbacks->connection_close(conn);
  12354. }
  12355. }
  12356. #endif
  12357. /* This is the heart of the Civetweb's logic.
  12358. * This function is called when the request is read, parsed and validated,
  12359. * and Civetweb must decide what action to take: serve a file, or
  12360. * a directory, or call embedded function, etcetera. */
  12361. static void
  12362. handle_request(struct mg_connection *conn)
  12363. {
  12364. struct mg_request_info *ri = &conn->request_info;
  12365. char path[PATH_MAX];
  12366. int uri_len, ssl_index;
  12367. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12368. is_put_or_delete_request = 0, is_callback_resource = 0,
  12369. is_template_text_file = 0;
  12370. int i;
  12371. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12372. mg_request_handler callback_handler = NULL;
  12373. struct mg_handler_info *handler_info = NULL;
  12374. struct mg_websocket_subprotocols *subprotocols;
  12375. mg_websocket_connect_handler ws_connect_handler = NULL;
  12376. mg_websocket_ready_handler ws_ready_handler = NULL;
  12377. mg_websocket_data_handler ws_data_handler = NULL;
  12378. mg_websocket_close_handler ws_close_handler = NULL;
  12379. void *callback_data = NULL;
  12380. mg_authorization_handler auth_handler = NULL;
  12381. void *auth_callback_data = NULL;
  12382. int handler_type;
  12383. time_t curtime = time(NULL);
  12384. char date[64];
  12385. path[0] = 0;
  12386. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12387. conn->request_state = 0;
  12388. /* 1. get the request url */
  12389. /* 1.1. split into url and query string */
  12390. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12391. != NULL) {
  12392. *((char *)conn->request_info.query_string++) = '\0';
  12393. }
  12394. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12395. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12396. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12397. if (ssl_index >= 0) {
  12398. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12399. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12400. redirect_to_https_port(conn, port);
  12401. } else {
  12402. /* A http to https forward port has been specified,
  12403. * but no https port to forward to. */
  12404. mg_send_http_error(conn,
  12405. 503,
  12406. "%s",
  12407. "Error: SSL forward not configured properly");
  12408. mg_cry_internal(conn,
  12409. "%s",
  12410. "Can not redirect to SSL, no SSL port available");
  12411. }
  12412. return;
  12413. }
  12414. uri_len = (int)strlen(ri->local_uri);
  12415. /* 1.3. decode url (if config says so) */
  12416. if (should_decode_url(conn)) {
  12417. mg_url_decode(
  12418. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12419. if (conn->request_info.query_string) {
  12420. url_decode_in_place((char *)conn->request_info.query_string);
  12421. }
  12422. }
  12423. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  12424. * not possible */
  12425. remove_dot_segments((char *)ri->local_uri);
  12426. /* step 1. completed, the url is known now */
  12427. uri_len = (int)strlen(ri->local_uri);
  12428. DEBUG_TRACE("URL: %s", ri->local_uri);
  12429. /* 2. if this ip has limited speed, set it for this connection */
  12430. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12431. &conn->client.rsa,
  12432. ri->local_uri);
  12433. /* 3. call a "handle everything" callback, if registered */
  12434. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12435. /* Note that since V1.7 the "begin_request" function is called
  12436. * before an authorization check. If an authorization check is
  12437. * required, use a request_handler instead. */
  12438. i = conn->phys_ctx->callbacks.begin_request(conn);
  12439. if (i > 0) {
  12440. /* callback already processed the request. Store the
  12441. return value as a status code for the access log. */
  12442. conn->status_code = i;
  12443. if (!conn->must_close) {
  12444. discard_unread_request_data(conn);
  12445. }
  12446. return;
  12447. } else if (i == 0) {
  12448. /* civetweb should process the request */
  12449. } else {
  12450. /* unspecified - may change with the next version */
  12451. return;
  12452. }
  12453. }
  12454. /* request not yet handled by a handler or redirect, so the request
  12455. * is processed here */
  12456. /* 4. Check for CORS preflight requests and handle them (if configured).
  12457. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12458. */
  12459. if (!strcmp(ri->request_method, "OPTIONS")) {
  12460. /* Send a response to CORS preflights only if
  12461. * access_control_allow_methods is not NULL and not an empty string.
  12462. * In this case, scripts can still handle CORS. */
  12463. const char *cors_meth_cfg =
  12464. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12465. const char *cors_orig_cfg =
  12466. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12467. const char *cors_origin =
  12468. get_header(ri->http_headers, ri->num_headers, "Origin");
  12469. const char *cors_acrm = get_header(ri->http_headers,
  12470. ri->num_headers,
  12471. "Access-Control-Request-Method");
  12472. /* Todo: check if cors_origin is in cors_orig_cfg.
  12473. * Or, let the client check this. */
  12474. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12475. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12476. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12477. /* This is a valid CORS preflight, and the server is configured
  12478. * to handle it automatically. */
  12479. const char *cors_acrh =
  12480. get_header(ri->http_headers,
  12481. ri->num_headers,
  12482. "Access-Control-Request-Headers");
  12483. gmt_time_string(date, sizeof(date), &curtime);
  12484. mg_printf(conn,
  12485. "HTTP/1.1 200 OK\r\n"
  12486. "Date: %s\r\n"
  12487. "Access-Control-Allow-Origin: %s\r\n"
  12488. "Access-Control-Allow-Methods: %s\r\n"
  12489. "Content-Length: 0\r\n"
  12490. "Connection: %s\r\n",
  12491. date,
  12492. cors_orig_cfg,
  12493. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12494. suggest_connection_header(conn));
  12495. if (cors_acrh != NULL) {
  12496. /* CORS request is asking for additional headers */
  12497. const char *cors_hdr_cfg =
  12498. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12499. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12500. /* Allow only if access_control_allow_headers is
  12501. * not NULL and not an empty string. If this
  12502. * configuration is set to *, allow everything.
  12503. * Otherwise this configuration must be a list
  12504. * of allowed HTTP header names. */
  12505. mg_printf(conn,
  12506. "Access-Control-Allow-Headers: %s\r\n",
  12507. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12508. : cors_hdr_cfg));
  12509. }
  12510. }
  12511. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12512. mg_printf(conn, "\r\n");
  12513. return;
  12514. }
  12515. }
  12516. /* 5. interpret the url to find out how the request must be handled
  12517. */
  12518. /* 5.1. first test, if the request targets the regular http(s)://
  12519. * protocol namespace or the websocket ws(s):// protocol namespace.
  12520. */
  12521. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12522. #if defined(USE_WEBSOCKET)
  12523. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12524. #else
  12525. handler_type = REQUEST_HANDLER;
  12526. #endif /* defined(USE_WEBSOCKET) */
  12527. if (is_websocket_request) {
  12528. HTTP1_only;
  12529. }
  12530. /* 5.2. check if the request will be handled by a callback */
  12531. if (get_request_handler(conn,
  12532. handler_type,
  12533. &callback_handler,
  12534. &subprotocols,
  12535. &ws_connect_handler,
  12536. &ws_ready_handler,
  12537. &ws_data_handler,
  12538. &ws_close_handler,
  12539. NULL,
  12540. &callback_data,
  12541. &handler_info)) {
  12542. /* 5.2.1. A callback will handle this request. All requests
  12543. * handled by a callback have to be considered as requests
  12544. * to a script resource. */
  12545. is_callback_resource = 1;
  12546. is_script_resource = 1;
  12547. is_put_or_delete_request = is_put_or_delete_method(conn);
  12548. } else {
  12549. no_callback_resource:
  12550. /* 5.2.2. No callback is responsible for this request. The URI
  12551. * addresses a file based resource (static content or Lua/cgi
  12552. * scripts in the file system). */
  12553. is_callback_resource = 0;
  12554. interpret_uri(conn,
  12555. path,
  12556. sizeof(path),
  12557. &file.stat,
  12558. &is_found,
  12559. &is_script_resource,
  12560. &is_websocket_request,
  12561. &is_put_or_delete_request,
  12562. &is_template_text_file);
  12563. }
  12564. /* 6. authorization check */
  12565. /* 6.1. a custom authorization handler is installed */
  12566. if (get_request_handler(conn,
  12567. AUTH_HANDLER,
  12568. NULL,
  12569. NULL,
  12570. NULL,
  12571. NULL,
  12572. NULL,
  12573. NULL,
  12574. &auth_handler,
  12575. &auth_callback_data,
  12576. NULL)) {
  12577. if (!auth_handler(conn, auth_callback_data)) {
  12578. return;
  12579. }
  12580. } else if (is_put_or_delete_request && !is_script_resource
  12581. && !is_callback_resource) {
  12582. HTTP1_only;
  12583. /* 6.2. this request is a PUT/DELETE to a real file */
  12584. /* 6.2.1. thus, the server must have real files */
  12585. #if defined(NO_FILES)
  12586. if (1) {
  12587. #else
  12588. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12589. #endif
  12590. /* This server does not have any real files, thus the
  12591. * PUT/DELETE methods are not valid. */
  12592. mg_send_http_error(conn,
  12593. 405,
  12594. "%s method not allowed",
  12595. conn->request_info.request_method);
  12596. return;
  12597. }
  12598. #if !defined(NO_FILES)
  12599. /* 6.2.2. Check if put authorization for static files is
  12600. * available.
  12601. */
  12602. if (!is_authorized_for_put(conn)) {
  12603. send_authorization_request(conn, NULL);
  12604. return;
  12605. }
  12606. #endif
  12607. } else {
  12608. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12609. * or it is a PUT or DELETE request to a resource that does not
  12610. * correspond to a file. Check authorization. */
  12611. if (!check_authorization(conn, path)) {
  12612. send_authorization_request(conn, NULL);
  12613. return;
  12614. }
  12615. }
  12616. /* request is authorized or does not need authorization */
  12617. /* 7. check if there are request handlers for this uri */
  12618. if (is_callback_resource) {
  12619. HTTP1_only;
  12620. if (!is_websocket_request) {
  12621. i = callback_handler(conn, callback_data);
  12622. /* Callback handler will not be used anymore. Release it */
  12623. mg_lock_context(conn->phys_ctx);
  12624. handler_info->refcount--;
  12625. mg_unlock_context(conn->phys_ctx);
  12626. if (i > 0) {
  12627. /* Do nothing, callback has served the request. Store
  12628. * then return value as status code for the log and discard
  12629. * all data from the client not used by the callback. */
  12630. conn->status_code = i;
  12631. if (!conn->must_close) {
  12632. discard_unread_request_data(conn);
  12633. }
  12634. } else {
  12635. /* The handler did NOT handle the request. */
  12636. /* Some proper reactions would be:
  12637. * a) close the connections without sending anything
  12638. * b) send a 404 not found
  12639. * c) try if there is a file matching the URI
  12640. * It would be possible to do a, b or c in the callback
  12641. * implementation, and return 1 - we cannot do anything
  12642. * here, that is not possible in the callback.
  12643. *
  12644. * TODO: What would be the best reaction here?
  12645. * (Note: The reaction may change, if there is a better
  12646. * idea.)
  12647. */
  12648. /* For the moment, use option c: We look for a proper file,
  12649. * but since a file request is not always a script resource,
  12650. * the authorization check might be different. */
  12651. interpret_uri(conn,
  12652. path,
  12653. sizeof(path),
  12654. &file.stat,
  12655. &is_found,
  12656. &is_script_resource,
  12657. &is_websocket_request,
  12658. &is_put_or_delete_request,
  12659. &is_template_text_file);
  12660. callback_handler = NULL;
  12661. /* Here we are at a dead end:
  12662. * According to URI matching, a callback should be
  12663. * responsible for handling the request,
  12664. * we called it, but the callback declared itself
  12665. * not responsible.
  12666. * We use a goto here, to get out of this dead end,
  12667. * and continue with the default handling.
  12668. * A goto here is simpler and better to understand
  12669. * than some curious loop. */
  12670. goto no_callback_resource;
  12671. }
  12672. } else {
  12673. #if defined(USE_WEBSOCKET)
  12674. handle_websocket_request(conn,
  12675. path,
  12676. is_callback_resource,
  12677. subprotocols,
  12678. ws_connect_handler,
  12679. ws_ready_handler,
  12680. ws_data_handler,
  12681. ws_close_handler,
  12682. callback_data);
  12683. #endif
  12684. }
  12685. return;
  12686. }
  12687. /* 8. handle websocket requests */
  12688. #if defined(USE_WEBSOCKET)
  12689. if (is_websocket_request) {
  12690. HTTP1_only;
  12691. if (is_script_resource) {
  12692. if (is_in_script_path(conn, path)) {
  12693. /* Websocket Lua script */
  12694. handle_websocket_request(conn,
  12695. path,
  12696. 0 /* Lua Script */,
  12697. NULL,
  12698. NULL,
  12699. NULL,
  12700. NULL,
  12701. NULL,
  12702. conn->phys_ctx->user_data);
  12703. } else {
  12704. /* Script was in an illegal path */
  12705. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12706. }
  12707. } else {
  12708. mg_send_http_error(conn, 404, "%s", "Not found");
  12709. }
  12710. return;
  12711. } else
  12712. #endif
  12713. #if defined(NO_FILES)
  12714. /* 9a. In case the server uses only callbacks, this uri is
  12715. * unknown.
  12716. * Then, all request handling ends here. */
  12717. mg_send_http_error(conn, 404, "%s", "Not Found");
  12718. #else
  12719. /* 9b. This request is either for a static file or resource handled
  12720. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12721. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12722. mg_send_http_error(conn, 404, "%s", "Not Found");
  12723. return;
  12724. }
  12725. /* 10. Request is handled by a script */
  12726. if (is_script_resource) {
  12727. HTTP1_only;
  12728. handle_file_based_request(conn, path, &file);
  12729. return;
  12730. }
  12731. /* 11. Handle put/delete/mkcol requests */
  12732. if (is_put_or_delete_request) {
  12733. HTTP1_only;
  12734. /* 11.1. PUT method */
  12735. if (!strcmp(ri->request_method, "PUT")) {
  12736. put_file(conn, path);
  12737. return;
  12738. }
  12739. /* 11.2. DELETE method */
  12740. if (!strcmp(ri->request_method, "DELETE")) {
  12741. delete_file(conn, path);
  12742. return;
  12743. }
  12744. /* 11.3. MKCOL method */
  12745. if (!strcmp(ri->request_method, "MKCOL")) {
  12746. mkcol(conn, path);
  12747. return;
  12748. }
  12749. /* 11.4. PATCH method
  12750. * This method is not supported for static resources,
  12751. * only for scripts (Lua, CGI) and callbacks. */
  12752. mg_send_http_error(conn,
  12753. 405,
  12754. "%s method not allowed",
  12755. conn->request_info.request_method);
  12756. return;
  12757. }
  12758. /* 11. File does not exist, or it was configured that it should be
  12759. * hidden */
  12760. if (!is_found || (must_hide_file(conn, path))) {
  12761. mg_send_http_error(conn, 404, "%s", "Not found");
  12762. return;
  12763. }
  12764. /* 12. Directory uris should end with a slash */
  12765. if (file.stat.is_directory && (uri_len > 0)
  12766. && (ri->local_uri[uri_len - 1] != '/')) {
  12767. size_t len = strlen(ri->request_uri);
  12768. char *new_path = mg_malloc_ctx(len + 2, conn->phys_ctx);
  12769. if (!new_path) {
  12770. mg_send_http_error(conn, 500, "out or memory");
  12771. } else {
  12772. memcpy(new_path, ri->request_uri, len);
  12773. new_path[len] = '/';
  12774. new_path[len + 1] = 0;
  12775. mg_send_http_redirect(conn, new_path, 301);
  12776. }
  12777. return;
  12778. }
  12779. /* 13. Handle other methods than GET/HEAD */
  12780. /* 13.1. Handle PROPFIND */
  12781. if (!strcmp(ri->request_method, "PROPFIND")) {
  12782. handle_propfind(conn, path, &file.stat);
  12783. return;
  12784. }
  12785. /* 13.2. Handle OPTIONS for files */
  12786. if (!strcmp(ri->request_method, "OPTIONS")) {
  12787. /* This standard handler is only used for real files.
  12788. * Scripts should support the OPTIONS method themselves, to allow a
  12789. * maximum flexibility.
  12790. * Lua and CGI scripts may fully support CORS this way (including
  12791. * preflights). */
  12792. send_options(conn);
  12793. return;
  12794. }
  12795. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12796. if ((0 != strcmp(ri->request_method, "GET"))
  12797. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12798. mg_send_http_error(conn,
  12799. 405,
  12800. "%s method not allowed",
  12801. conn->request_info.request_method);
  12802. return;
  12803. }
  12804. /* 14. directories */
  12805. if (file.stat.is_directory) {
  12806. /* Substitute files have already been handled above. */
  12807. /* Here we can either generate and send a directory listing,
  12808. * or send an "access denied" error. */
  12809. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12810. "yes")) {
  12811. handle_directory_request(conn, path);
  12812. } else {
  12813. mg_send_http_error(conn,
  12814. 403,
  12815. "%s",
  12816. "Error: Directory listing denied");
  12817. }
  12818. return;
  12819. }
  12820. /* 15. Files with search/replace patterns: LSP and SSI */
  12821. if (is_template_text_file) {
  12822. HTTP1_only;
  12823. handle_file_based_request(conn, path, &file);
  12824. return;
  12825. }
  12826. /* 16. Static file - maybe cached */
  12827. #if !defined(NO_CACHING)
  12828. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12829. /* Send 304 "Not Modified" - this must not send any body data */
  12830. handle_not_modified_static_file_request(conn, &file);
  12831. return;
  12832. }
  12833. #endif /* !NO_CACHING */
  12834. /* 17. Static file - not cached */
  12835. handle_static_file_request(conn, path, &file, NULL, NULL);
  12836. #endif /* !defined(NO_FILES) */
  12837. }
  12838. #if !defined(NO_FILESYSTEMS)
  12839. static void
  12840. handle_file_based_request(struct mg_connection *conn,
  12841. const char *path,
  12842. struct mg_file *file)
  12843. {
  12844. if (!conn || !conn->dom_ctx) {
  12845. return;
  12846. }
  12847. if (0) {
  12848. #if defined(USE_LUA)
  12849. } else if (match_prefix_strlen(
  12850. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], path)
  12851. > 0) {
  12852. if (is_in_script_path(conn, path)) {
  12853. /* Lua server page: an SSI like page containing mostly plain
  12854. * html code plus some tags with server generated contents. */
  12855. handle_lsp_request(conn, path, file, NULL);
  12856. } else {
  12857. /* Script was in an illegal path */
  12858. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12859. }
  12860. } else if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12861. path)
  12862. > 0) {
  12863. if (is_in_script_path(conn, path)) {
  12864. /* Lua in-server module script: a CGI like script used to
  12865. * generate
  12866. * the
  12867. * entire reply. */
  12868. mg_exec_lua_script(conn, path, NULL);
  12869. } else {
  12870. /* Script was in an illegal path */
  12871. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12872. }
  12873. #endif
  12874. #if defined(USE_DUKTAPE)
  12875. } else if (match_prefix_strlen(
  12876. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], path)
  12877. > 0) {
  12878. if (is_in_script_path(conn, path)) {
  12879. /* Call duktape to generate the page */
  12880. mg_exec_duktape_script(conn, path);
  12881. } else {
  12882. /* Script was in an illegal path */
  12883. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12884. }
  12885. #endif
  12886. #if !defined(NO_CGI)
  12887. } else if (match_prefix_strlen(conn->dom_ctx->config[CGI_EXTENSIONS], path)
  12888. > 0) {
  12889. if (is_in_script_path(conn, path)) {
  12890. /* CGI scripts may support all HTTP methods */
  12891. handle_cgi_request(conn, path);
  12892. } else {
  12893. /* Script was in an illegal path */
  12894. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12895. }
  12896. #endif /* !NO_CGI */
  12897. } else if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  12898. > 0) {
  12899. if (is_in_script_path(conn, path)) {
  12900. handle_ssi_file_request(conn, path, file);
  12901. } else {
  12902. /* Script was in an illegal path */
  12903. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12904. }
  12905. #if !defined(NO_CACHING)
  12906. } else if ((!conn->in_error_handler)
  12907. && is_not_modified(conn, &file->stat)) {
  12908. /* Send 304 "Not Modified" - this must not send any body data */
  12909. handle_not_modified_static_file_request(conn, file);
  12910. #endif /* !NO_CACHING */
  12911. } else {
  12912. handle_static_file_request(conn, path, file, NULL, NULL);
  12913. }
  12914. }
  12915. #endif /* NO_FILESYSTEMS */
  12916. static void
  12917. close_all_listening_sockets(struct mg_context *ctx)
  12918. {
  12919. unsigned int i;
  12920. if (!ctx) {
  12921. return;
  12922. }
  12923. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12924. closesocket(ctx->listening_sockets[i].sock);
  12925. #if defined(USE_X_DOM_SOCKET)
  12926. /* For unix domain sockets, the socket name represents a file that has
  12927. * to be deleted. */
  12928. /* See
  12929. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12930. */
  12931. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12932. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12933. IGNORE_UNUSED_RESULT(
  12934. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12935. }
  12936. #endif
  12937. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12938. }
  12939. mg_free(ctx->listening_sockets);
  12940. ctx->listening_sockets = NULL;
  12941. mg_free(ctx->listening_socket_fds);
  12942. ctx->listening_socket_fds = NULL;
  12943. }
  12944. /* Valid listening port specification is: [ip_address:]port[s]
  12945. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12946. * Examples for IPv6: [::]:80, [::1]:80,
  12947. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12948. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12949. * In order to bind to both, IPv4 and IPv6, you can either add
  12950. * both ports using 8080,[::]:8080, or the short form +8080.
  12951. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12952. * one only accepting IPv4 the other only IPv6. +8080 creates
  12953. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12954. * environment, they might work differently, or might not work
  12955. * at all - it must be tested what options work best in the
  12956. * relevant network environment.
  12957. */
  12958. static int
  12959. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12960. {
  12961. unsigned int a, b, c, d;
  12962. unsigned port;
  12963. unsigned long portUL;
  12964. int ch, len;
  12965. const char *cb;
  12966. char *endptr;
  12967. #if defined(USE_IPV6)
  12968. char buf[100] = {0};
  12969. #endif
  12970. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12971. * Also, all-zeroes in the socket address means binding to all addresses
  12972. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12973. memset(so, 0, sizeof(*so));
  12974. so->lsa.sin.sin_family = AF_INET;
  12975. *ip_version = 0;
  12976. /* Initialize len as invalid. */
  12977. port = 0;
  12978. len = 0;
  12979. /* Test for different ways to format this string */
  12980. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12981. == 5) {
  12982. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12983. so->lsa.sin.sin_addr.s_addr =
  12984. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12985. so->lsa.sin.sin_port = htons((uint16_t)port);
  12986. *ip_version = 4;
  12987. #if defined(USE_IPV6)
  12988. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12989. && ((size_t)len <= vec->len)
  12990. && mg_inet_pton(
  12991. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12992. /* IPv6 address, examples: see above */
  12993. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12994. */
  12995. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12996. *ip_version = 6;
  12997. #endif
  12998. } else if ((vec->ptr[0] == '+')
  12999. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  13000. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13001. /* Add 1 to len for the + character we skipped before */
  13002. len++;
  13003. #if defined(USE_IPV6)
  13004. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13005. so->lsa.sin6.sin6_family = AF_INET6;
  13006. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13007. *ip_version = 4 + 6;
  13008. #else
  13009. /* Bind to IPv4 only, since IPv6 is not built in. */
  13010. so->lsa.sin.sin_port = htons((uint16_t)port);
  13011. *ip_version = 4;
  13012. #endif
  13013. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13014. && (vec->ptr != endptr)) {
  13015. len = (int)(endptr - vec->ptr);
  13016. port = (uint16_t)portUL;
  13017. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13018. so->lsa.sin.sin_port = htons((uint16_t)port);
  13019. *ip_version = 4;
  13020. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13021. /* String could be a hostname. This check algotithm
  13022. * will only work for RFC 952 compliant hostnames,
  13023. * starting with a letter, containing only letters,
  13024. * digits and hyphen ('-'). Newer specs may allow
  13025. * more, but this is not guaranteed here, since it
  13026. * may interfere with rules for port option lists. */
  13027. /* According to RFC 1035, hostnames are restricted to 255 characters
  13028. * in total (63 between two dots). */
  13029. char hostname[256];
  13030. size_t hostnlen = (size_t)(cb - vec->ptr);
  13031. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13032. /* This would be invalid in any case */
  13033. *ip_version = 0;
  13034. return 0;
  13035. }
  13036. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13037. if (mg_inet_pton(
  13038. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13039. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13040. *ip_version = 4;
  13041. so->lsa.sin.sin_port = htons((uint16_t)port);
  13042. len += (int)(hostnlen + 1);
  13043. } else {
  13044. len = 0;
  13045. }
  13046. #if defined(USE_IPV6)
  13047. } else if (mg_inet_pton(AF_INET6,
  13048. hostname,
  13049. &so->lsa.sin6,
  13050. sizeof(so->lsa.sin6),
  13051. 1)) {
  13052. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13053. *ip_version = 6;
  13054. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13055. len += (int)(hostnlen + 1);
  13056. } else {
  13057. len = 0;
  13058. }
  13059. #endif
  13060. } else {
  13061. len = 0;
  13062. }
  13063. #if defined(USE_X_DOM_SOCKET)
  13064. } else if (vec->ptr[0] == 'x') {
  13065. /* unix (linux) domain socket */
  13066. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13067. len = vec->len;
  13068. so->lsa.sun.sun_family = AF_UNIX;
  13069. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13070. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13071. port = 0;
  13072. *ip_version = 99;
  13073. } else {
  13074. /* String too long */
  13075. len = 0;
  13076. }
  13077. #endif
  13078. } else {
  13079. /* Parsing failure. */
  13080. len = 0;
  13081. }
  13082. /* sscanf and the option splitting code ensure the following condition
  13083. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13084. if ((len > 0) && is_valid_port(port)
  13085. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13086. /* Next character after the port number */
  13087. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13088. so->is_ssl = (ch == 's');
  13089. so->ssl_redir = (ch == 'r');
  13090. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13091. return 1;
  13092. }
  13093. }
  13094. /* Reset ip_version to 0 if there is an error */
  13095. *ip_version = 0;
  13096. return 0;
  13097. }
  13098. /* Is there any SSL port in use? */
  13099. static int
  13100. is_ssl_port_used(const char *ports)
  13101. {
  13102. if (ports) {
  13103. /* There are several different allowed syntax variants:
  13104. * - "80" for a single port using every network interface
  13105. * - "localhost:80" for a single port using only localhost
  13106. * - "80,localhost:8080" for two ports, one bound to localhost
  13107. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13108. * to IPv4 localhost, one to IPv6 localhost
  13109. * - "+80" use port 80 for IPv4 and IPv6
  13110. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13111. * for both: IPv4 and IPv4
  13112. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13113. * additionally port 8080 bound to localhost connections
  13114. *
  13115. * If we just look for 's' anywhere in the string, "localhost:80"
  13116. * will be detected as SSL (false positive).
  13117. * Looking for 's' after a digit may cause false positives in
  13118. * "my24service:8080".
  13119. * Looking from 's' backward if there are only ':' and numbers
  13120. * before will not work for "24service:8080" (non SSL, port 8080)
  13121. * or "24s" (SSL, port 24).
  13122. *
  13123. * Remark: Initially hostnames were not allowed to start with a
  13124. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13125. * Section 2.1).
  13126. *
  13127. * To get this correct, the entire string must be parsed as a whole,
  13128. * reading it as a list element for element and parsing with an
  13129. * algorithm equivalent to parse_port_string.
  13130. *
  13131. * In fact, we use local interface names here, not arbitrary
  13132. * hostnames, so in most cases the only name will be "localhost".
  13133. *
  13134. * So, for now, we use this simple algorithm, that may still return
  13135. * a false positive in bizarre cases.
  13136. */
  13137. int i;
  13138. int portslen = (int)strlen(ports);
  13139. char prevIsNumber = 0;
  13140. for (i = 0; i < portslen; i++) {
  13141. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13142. return 1;
  13143. }
  13144. if (ports[i] >= '0' && ports[i] <= '9') {
  13145. prevIsNumber = 1;
  13146. } else {
  13147. prevIsNumber = 0;
  13148. }
  13149. }
  13150. }
  13151. return 0;
  13152. }
  13153. static int
  13154. set_ports_option(struct mg_context *phys_ctx)
  13155. {
  13156. const char *list;
  13157. int on = 1;
  13158. #if defined(USE_IPV6)
  13159. int off = 0;
  13160. #endif
  13161. struct vec vec;
  13162. struct socket so, *ptr;
  13163. struct mg_pollfd *pfd;
  13164. union usa usa;
  13165. socklen_t len;
  13166. int ip_version;
  13167. int portsTotal = 0;
  13168. int portsOk = 0;
  13169. const char *opt_txt;
  13170. long opt_listen_backlog;
  13171. if (!phys_ctx) {
  13172. return 0;
  13173. }
  13174. memset(&so, 0, sizeof(so));
  13175. memset(&usa, 0, sizeof(usa));
  13176. len = sizeof(usa);
  13177. list = phys_ctx->dd.config[LISTENING_PORTS];
  13178. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13179. portsTotal++;
  13180. if (!parse_port_string(&vec, &so, &ip_version)) {
  13181. mg_cry_ctx_internal(
  13182. phys_ctx,
  13183. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13184. (int)vec.len,
  13185. vec.ptr,
  13186. portsTotal,
  13187. "[IP_ADDRESS:]PORT[s|r]");
  13188. continue;
  13189. }
  13190. #if !defined(NO_SSL)
  13191. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13192. mg_cry_ctx_internal(phys_ctx,
  13193. "Cannot add SSL socket (entry %i)",
  13194. portsTotal);
  13195. continue;
  13196. }
  13197. #endif
  13198. /* Create socket. */
  13199. /* For a list of protocol numbers (e.g., TCP==6) see:
  13200. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13201. */
  13202. if ((so.sock =
  13203. socket(so.lsa.sa.sa_family,
  13204. SOCK_STREAM,
  13205. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13206. == INVALID_SOCKET) {
  13207. mg_cry_ctx_internal(phys_ctx,
  13208. "cannot create socket (entry %i)",
  13209. portsTotal);
  13210. continue;
  13211. }
  13212. #if defined(_WIN32)
  13213. /* Windows SO_REUSEADDR lets many procs binds to a
  13214. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13215. * if someone already has the socket -- DTL */
  13216. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13217. * Windows might need a few seconds before
  13218. * the same port can be used again in the
  13219. * same process, so a short Sleep may be
  13220. * required between mg_stop and mg_start.
  13221. */
  13222. if (setsockopt(so.sock,
  13223. SOL_SOCKET,
  13224. SO_EXCLUSIVEADDRUSE,
  13225. (SOCK_OPT_TYPE)&on,
  13226. sizeof(on))
  13227. != 0) {
  13228. /* Set reuse option, but don't abort on errors. */
  13229. mg_cry_ctx_internal(
  13230. phys_ctx,
  13231. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13232. portsTotal);
  13233. }
  13234. #else
  13235. if (setsockopt(so.sock,
  13236. SOL_SOCKET,
  13237. SO_REUSEADDR,
  13238. (SOCK_OPT_TYPE)&on,
  13239. sizeof(on))
  13240. != 0) {
  13241. /* Set reuse option, but don't abort on errors. */
  13242. mg_cry_ctx_internal(
  13243. phys_ctx,
  13244. "cannot set socket option SO_REUSEADDR (entry %i)",
  13245. portsTotal);
  13246. }
  13247. #endif
  13248. #if defined(USE_X_DOM_SOCKET)
  13249. if (ip_version == 99) {
  13250. /* Unix domain socket */
  13251. } else
  13252. #endif
  13253. if (ip_version > 4) {
  13254. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13255. #if defined(USE_IPV6)
  13256. if (ip_version > 6) {
  13257. if (so.lsa.sa.sa_family == AF_INET6
  13258. && setsockopt(so.sock,
  13259. IPPROTO_IPV6,
  13260. IPV6_V6ONLY,
  13261. (void *)&off,
  13262. sizeof(off))
  13263. != 0) {
  13264. /* Set IPv6 only option, but don't abort on errors. */
  13265. mg_cry_ctx_internal(phys_ctx,
  13266. "cannot set socket option "
  13267. "IPV6_V6ONLY=off (entry %i)",
  13268. portsTotal);
  13269. }
  13270. } else {
  13271. if (so.lsa.sa.sa_family == AF_INET6
  13272. && setsockopt(so.sock,
  13273. IPPROTO_IPV6,
  13274. IPV6_V6ONLY,
  13275. (void *)&on,
  13276. sizeof(on))
  13277. != 0) {
  13278. /* Set IPv6 only option, but don't abort on errors. */
  13279. mg_cry_ctx_internal(phys_ctx,
  13280. "cannot set socket option "
  13281. "IPV6_V6ONLY=on (entry %i)",
  13282. portsTotal);
  13283. }
  13284. }
  13285. #else
  13286. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13287. closesocket(so.sock);
  13288. so.sock = INVALID_SOCKET;
  13289. continue;
  13290. #endif
  13291. }
  13292. if (so.lsa.sa.sa_family == AF_INET) {
  13293. len = sizeof(so.lsa.sin);
  13294. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13295. mg_cry_ctx_internal(phys_ctx,
  13296. "cannot bind to %.*s: %d (%s)",
  13297. (int)vec.len,
  13298. vec.ptr,
  13299. (int)ERRNO,
  13300. strerror(errno));
  13301. closesocket(so.sock);
  13302. so.sock = INVALID_SOCKET;
  13303. continue;
  13304. }
  13305. }
  13306. #if defined(USE_IPV6)
  13307. else if (so.lsa.sa.sa_family == AF_INET6) {
  13308. len = sizeof(so.lsa.sin6);
  13309. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13310. mg_cry_ctx_internal(phys_ctx,
  13311. "cannot bind to IPv6 %.*s: %d (%s)",
  13312. (int)vec.len,
  13313. vec.ptr,
  13314. (int)ERRNO,
  13315. strerror(errno));
  13316. closesocket(so.sock);
  13317. so.sock = INVALID_SOCKET;
  13318. continue;
  13319. }
  13320. }
  13321. #endif
  13322. #if defined(USE_X_DOM_SOCKET)
  13323. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13324. len = sizeof(so.lsa.sun);
  13325. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13326. mg_cry_ctx_internal(phys_ctx,
  13327. "cannot bind to unix socket %s: %d (%s)",
  13328. so.lsa.sun.sun_path,
  13329. (int)ERRNO,
  13330. strerror(errno));
  13331. closesocket(so.sock);
  13332. so.sock = INVALID_SOCKET;
  13333. continue;
  13334. }
  13335. }
  13336. #endif
  13337. else {
  13338. mg_cry_ctx_internal(
  13339. phys_ctx,
  13340. "cannot bind: address family not supported (entry %i)",
  13341. portsTotal);
  13342. closesocket(so.sock);
  13343. so.sock = INVALID_SOCKET;
  13344. continue;
  13345. }
  13346. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13347. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13348. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13349. mg_cry_ctx_internal(phys_ctx,
  13350. "%s value \"%s\" is invalid",
  13351. config_options[LISTEN_BACKLOG_SIZE].name,
  13352. opt_txt);
  13353. closesocket(so.sock);
  13354. so.sock = INVALID_SOCKET;
  13355. continue;
  13356. }
  13357. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13358. mg_cry_ctx_internal(phys_ctx,
  13359. "cannot listen to %.*s: %d (%s)",
  13360. (int)vec.len,
  13361. vec.ptr,
  13362. (int)ERRNO,
  13363. strerror(errno));
  13364. closesocket(so.sock);
  13365. so.sock = INVALID_SOCKET;
  13366. continue;
  13367. }
  13368. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13369. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13370. int err = (int)ERRNO;
  13371. mg_cry_ctx_internal(phys_ctx,
  13372. "call to getsockname failed %.*s: %d (%s)",
  13373. (int)vec.len,
  13374. vec.ptr,
  13375. err,
  13376. strerror(errno));
  13377. closesocket(so.sock);
  13378. so.sock = INVALID_SOCKET;
  13379. continue;
  13380. }
  13381. /* Update lsa port in case of random free ports */
  13382. #if defined(USE_IPV6)
  13383. if (so.lsa.sa.sa_family == AF_INET6) {
  13384. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13385. } else
  13386. #endif
  13387. {
  13388. so.lsa.sin.sin_port = usa.sin.sin_port;
  13389. }
  13390. if ((ptr = (struct socket *)
  13391. mg_realloc_ctx(phys_ctx->listening_sockets,
  13392. (phys_ctx->num_listening_sockets + 1)
  13393. * sizeof(phys_ctx->listening_sockets[0]),
  13394. phys_ctx))
  13395. == NULL) {
  13396. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13397. closesocket(so.sock);
  13398. so.sock = INVALID_SOCKET;
  13399. continue;
  13400. }
  13401. if ((pfd = (struct mg_pollfd *)
  13402. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13403. (phys_ctx->num_listening_sockets + 1)
  13404. * sizeof(phys_ctx->listening_socket_fds[0]),
  13405. phys_ctx))
  13406. == NULL) {
  13407. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13408. closesocket(so.sock);
  13409. so.sock = INVALID_SOCKET;
  13410. mg_free(ptr);
  13411. continue;
  13412. }
  13413. set_close_on_exec(so.sock, NULL, phys_ctx);
  13414. phys_ctx->listening_sockets = ptr;
  13415. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13416. phys_ctx->listening_socket_fds = pfd;
  13417. phys_ctx->num_listening_sockets++;
  13418. portsOk++;
  13419. }
  13420. if (portsOk != portsTotal) {
  13421. close_all_listening_sockets(phys_ctx);
  13422. portsOk = 0;
  13423. }
  13424. return portsOk;
  13425. }
  13426. static const char *
  13427. header_val(const struct mg_connection *conn, const char *header)
  13428. {
  13429. const char *header_value;
  13430. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13431. return "-";
  13432. } else {
  13433. return header_value;
  13434. }
  13435. }
  13436. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13437. static void log_access(const struct mg_connection *conn);
  13438. #include "external_log_access.inl"
  13439. #elif !defined(NO_FILESYSTEMS)
  13440. static void
  13441. log_access(const struct mg_connection *conn)
  13442. {
  13443. const struct mg_request_info *ri;
  13444. struct mg_file fi;
  13445. char date[64], src_addr[IP_ADDR_STR_LEN];
  13446. struct tm *tm;
  13447. const char *referer;
  13448. const char *user_agent;
  13449. char buf[4096];
  13450. if (!conn || !conn->dom_ctx) {
  13451. return;
  13452. }
  13453. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13454. if (mg_fopen(conn,
  13455. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13456. MG_FOPEN_MODE_APPEND,
  13457. &fi)
  13458. == 0) {
  13459. fi.access.fp = NULL;
  13460. }
  13461. } else {
  13462. fi.access.fp = NULL;
  13463. }
  13464. /* Log is written to a file and/or a callback. If both are not set,
  13465. * executing the rest of the function is pointless. */
  13466. if ((fi.access.fp == NULL)
  13467. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13468. return;
  13469. }
  13470. tm = localtime(&conn->conn_birth_time);
  13471. if (tm != NULL) {
  13472. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13473. } else {
  13474. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13475. date[sizeof(date) - 1] = '\0';
  13476. }
  13477. ri = &conn->request_info;
  13478. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13479. referer = header_val(conn, "Referer");
  13480. user_agent = header_val(conn, "User-Agent");
  13481. mg_snprintf(conn,
  13482. NULL, /* Ignore truncation in access log */
  13483. buf,
  13484. sizeof(buf),
  13485. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  13486. src_addr,
  13487. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13488. date,
  13489. ri->request_method ? ri->request_method : "-",
  13490. ri->request_uri ? ri->request_uri : "-",
  13491. ri->query_string ? "?" : "",
  13492. ri->query_string ? ri->query_string : "",
  13493. ri->http_version,
  13494. conn->status_code,
  13495. conn->num_bytes_sent,
  13496. referer,
  13497. user_agent);
  13498. if (conn->phys_ctx->callbacks.log_access) {
  13499. conn->phys_ctx->callbacks.log_access(conn, buf);
  13500. }
  13501. if (fi.access.fp) {
  13502. int ok = 1;
  13503. flockfile(fi.access.fp);
  13504. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  13505. ok = 0;
  13506. }
  13507. if (fflush(fi.access.fp) != 0) {
  13508. ok = 0;
  13509. }
  13510. funlockfile(fi.access.fp);
  13511. if (mg_fclose(&fi.access) != 0) {
  13512. ok = 0;
  13513. }
  13514. if (!ok) {
  13515. mg_cry_internal(conn,
  13516. "Error writing log file %s",
  13517. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13518. }
  13519. }
  13520. }
  13521. #else
  13522. #error Must either enable filesystems or provide a custom log_access implementation
  13523. #endif /* Externally provided function */
  13524. /* Verify given socket address against the ACL.
  13525. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13526. */
  13527. static int
  13528. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13529. {
  13530. int allowed, flag, matched;
  13531. struct vec vec;
  13532. if (phys_ctx) {
  13533. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13534. /* If any ACL is set, deny by default */
  13535. allowed = (list == NULL) ? '+' : '-';
  13536. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13537. flag = vec.ptr[0];
  13538. matched = -1;
  13539. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13540. vec.ptr++;
  13541. vec.len--;
  13542. matched = parse_match_net(&vec, sa, 1);
  13543. }
  13544. if (matched < 0) {
  13545. mg_cry_ctx_internal(phys_ctx,
  13546. "%s: subnet must be [+|-]IP-addr[/x]",
  13547. __func__);
  13548. return -1;
  13549. }
  13550. if (matched) {
  13551. allowed = flag;
  13552. }
  13553. }
  13554. return allowed == '+';
  13555. }
  13556. return -1;
  13557. }
  13558. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13559. static int
  13560. set_uid_option(struct mg_context *phys_ctx)
  13561. {
  13562. int success = 0;
  13563. if (phys_ctx) {
  13564. /* We are currently running as curr_uid. */
  13565. const uid_t curr_uid = getuid();
  13566. /* If set, we want to run as run_as_user. */
  13567. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13568. const struct passwd *to_pw = NULL;
  13569. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13570. /* run_as_user does not exist on the system. We can't proceed
  13571. * further. */
  13572. mg_cry_ctx_internal(phys_ctx,
  13573. "%s: unknown user [%s]",
  13574. __func__,
  13575. run_as_user);
  13576. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13577. /* There was either no request to change user, or we're already
  13578. * running as run_as_user. Nothing else to do.
  13579. */
  13580. success = 1;
  13581. } else {
  13582. /* Valid change request. */
  13583. if (setgid(to_pw->pw_gid) == -1) {
  13584. mg_cry_ctx_internal(phys_ctx,
  13585. "%s: setgid(%s): %s",
  13586. __func__,
  13587. run_as_user,
  13588. strerror(errno));
  13589. } else if (setgroups(0, NULL) == -1) {
  13590. mg_cry_ctx_internal(phys_ctx,
  13591. "%s: setgroups(): %s",
  13592. __func__,
  13593. strerror(errno));
  13594. } else if (setuid(to_pw->pw_uid) == -1) {
  13595. mg_cry_ctx_internal(phys_ctx,
  13596. "%s: setuid(%s): %s",
  13597. __func__,
  13598. run_as_user,
  13599. strerror(errno));
  13600. } else {
  13601. success = 1;
  13602. }
  13603. }
  13604. }
  13605. return success;
  13606. }
  13607. #endif /* !_WIN32 */
  13608. static void
  13609. tls_dtor(void *key)
  13610. {
  13611. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13612. /* key == pthread_getspecific(sTlsKey); */
  13613. if (tls) {
  13614. if (tls->is_master == 2) {
  13615. tls->is_master = -3; /* Mark memory as dead */
  13616. mg_free(tls);
  13617. }
  13618. }
  13619. pthread_setspecific(sTlsKey, NULL);
  13620. }
  13621. #if !defined(NO_SSL)
  13622. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13623. struct mg_domain_context *dom_ctx,
  13624. const char *pem,
  13625. const char *chain);
  13626. static const char *ssl_error(void);
  13627. static int
  13628. refresh_trust(struct mg_connection *conn)
  13629. {
  13630. struct stat cert_buf;
  13631. int64_t t = 0;
  13632. const char *pem;
  13633. const char *chain;
  13634. int should_verify_peer;
  13635. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13636. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13637. * refresh_trust still can not work. */
  13638. return 0;
  13639. }
  13640. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13641. if (chain == NULL) {
  13642. /* pem is not NULL here */
  13643. chain = pem;
  13644. }
  13645. if (*chain == 0) {
  13646. chain = NULL;
  13647. }
  13648. if (stat(pem, &cert_buf) != -1) {
  13649. t = (int64_t)cert_buf.st_mtime;
  13650. }
  13651. mg_lock_context(conn->phys_ctx);
  13652. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13653. conn->dom_ctx->ssl_cert_last_mtime = t;
  13654. should_verify_peer = 0;
  13655. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13656. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13657. == 0) {
  13658. should_verify_peer = 1;
  13659. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13660. "optional")
  13661. == 0) {
  13662. should_verify_peer = 1;
  13663. }
  13664. }
  13665. if (should_verify_peer) {
  13666. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13667. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13668. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13669. ca_file,
  13670. ca_path)
  13671. != 1) {
  13672. mg_unlock_context(conn->phys_ctx);
  13673. mg_cry_ctx_internal(
  13674. conn->phys_ctx,
  13675. "SSL_CTX_load_verify_locations error: %s "
  13676. "ssl_verify_peer requires setting "
  13677. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13678. "present in "
  13679. "the .conf file?",
  13680. ssl_error());
  13681. return 0;
  13682. }
  13683. }
  13684. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13685. mg_unlock_context(conn->phys_ctx);
  13686. return 0;
  13687. }
  13688. }
  13689. mg_unlock_context(conn->phys_ctx);
  13690. return 1;
  13691. }
  13692. #if defined(OPENSSL_API_1_1)
  13693. #else
  13694. static pthread_mutex_t *ssl_mutexes;
  13695. #endif /* OPENSSL_API_1_1 */
  13696. static int
  13697. sslize(struct mg_connection *conn,
  13698. int (*func)(SSL *),
  13699. const struct mg_client_options *client_options)
  13700. {
  13701. int ret, err;
  13702. int short_trust;
  13703. unsigned timeout = 1024;
  13704. unsigned i;
  13705. if (!conn) {
  13706. return 0;
  13707. }
  13708. short_trust =
  13709. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13710. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13711. if (short_trust) {
  13712. int trust_ret = refresh_trust(conn);
  13713. if (!trust_ret) {
  13714. return trust_ret;
  13715. }
  13716. }
  13717. mg_lock_context(conn->phys_ctx);
  13718. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13719. mg_unlock_context(conn->phys_ctx);
  13720. if (conn->ssl == NULL) {
  13721. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13722. OPENSSL_REMOVE_THREAD_STATE();
  13723. return 0;
  13724. }
  13725. SSL_set_app_data(conn->ssl, (char *)conn);
  13726. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13727. if (ret != 1) {
  13728. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13729. SSL_free(conn->ssl);
  13730. conn->ssl = NULL;
  13731. OPENSSL_REMOVE_THREAD_STATE();
  13732. return 0;
  13733. }
  13734. if (client_options) {
  13735. if (client_options->host_name) {
  13736. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13737. }
  13738. }
  13739. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13740. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13741. /* NOTE: The loop below acts as a back-off, so we can end
  13742. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13743. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13744. if (to >= 0) {
  13745. timeout = (unsigned)to;
  13746. }
  13747. }
  13748. /* SSL functions may fail and require to be called again:
  13749. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13750. * Here "func" could be SSL_connect or SSL_accept. */
  13751. for (i = 0; i <= timeout; i += 50) {
  13752. ERR_clear_error();
  13753. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13754. ret = func(conn->ssl);
  13755. if (ret != 1) {
  13756. err = SSL_get_error(conn->ssl, ret);
  13757. if ((err == SSL_ERROR_WANT_CONNECT)
  13758. || (err == SSL_ERROR_WANT_ACCEPT)
  13759. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13760. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13761. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13762. /* Don't wait if the server is going to be stopped. */
  13763. break;
  13764. }
  13765. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13766. /* Simply retry the function call. */
  13767. mg_sleep(50);
  13768. } else {
  13769. /* Need to retry the function call "later".
  13770. * See https://linux.die.net/man/3/ssl_get_error
  13771. * This is typical for non-blocking sockets. */
  13772. struct mg_pollfd pfd;
  13773. int pollres;
  13774. pfd.fd = conn->client.sock;
  13775. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13776. || (err == SSL_ERROR_WANT_WRITE))
  13777. ? POLLOUT
  13778. : POLLIN;
  13779. pollres =
  13780. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13781. if (pollres < 0) {
  13782. /* Break if error occured (-1)
  13783. * or server shutdown (-2) */
  13784. break;
  13785. }
  13786. }
  13787. } else if (err == SSL_ERROR_SYSCALL) {
  13788. /* This is an IO error. Look at errno. */
  13789. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13790. break;
  13791. } else {
  13792. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13793. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13794. break;
  13795. }
  13796. } else {
  13797. /* success */
  13798. break;
  13799. }
  13800. }
  13801. ERR_clear_error();
  13802. if (ret != 1) {
  13803. SSL_free(conn->ssl);
  13804. conn->ssl = NULL;
  13805. OPENSSL_REMOVE_THREAD_STATE();
  13806. return 0;
  13807. }
  13808. return 1;
  13809. }
  13810. /* Return OpenSSL error message (from CRYPTO lib) */
  13811. static const char *
  13812. ssl_error(void)
  13813. {
  13814. unsigned long err;
  13815. err = ERR_get_error();
  13816. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13817. }
  13818. static int
  13819. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13820. {
  13821. int i;
  13822. const char hexdigit[] = "0123456789abcdef";
  13823. if ((memlen <= 0) || (buflen <= 0)) {
  13824. return 0;
  13825. }
  13826. if (buflen < (3 * memlen)) {
  13827. return 0;
  13828. }
  13829. for (i = 0; i < memlen; i++) {
  13830. if (i > 0) {
  13831. buf[3 * i - 1] = ' ';
  13832. }
  13833. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13834. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13835. }
  13836. buf[3 * memlen - 1] = 0;
  13837. return 1;
  13838. }
  13839. static int
  13840. ssl_get_client_cert_info(const struct mg_connection *conn,
  13841. struct mg_client_cert *client_cert)
  13842. {
  13843. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13844. if (cert) {
  13845. char str_buf[1024];
  13846. unsigned char buf[256];
  13847. char *str_serial = NULL;
  13848. unsigned int ulen;
  13849. int ilen;
  13850. unsigned char *tmp_buf;
  13851. unsigned char *tmp_p;
  13852. /* Handle to algorithm used for fingerprint */
  13853. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13854. /* Get Subject and issuer */
  13855. X509_NAME *subj = X509_get_subject_name(cert);
  13856. X509_NAME *iss = X509_get_issuer_name(cert);
  13857. /* Get serial number */
  13858. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13859. /* Translate serial number to a hex string */
  13860. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13861. if (serial_bn) {
  13862. str_serial = BN_bn2hex(serial_bn);
  13863. BN_free(serial_bn);
  13864. }
  13865. client_cert->serial =
  13866. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13867. /* Translate subject and issuer to a string */
  13868. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13869. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13870. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13871. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13872. /* Calculate SHA1 fingerprint and store as a hex string */
  13873. ulen = 0;
  13874. /* ASN1_digest is deprecated. Do the calculation manually,
  13875. * using EVP_Digest. */
  13876. ilen = i2d_X509(cert, NULL);
  13877. tmp_buf = (ilen > 0)
  13878. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13879. conn->phys_ctx)
  13880. : NULL;
  13881. if (tmp_buf) {
  13882. tmp_p = tmp_buf;
  13883. (void)i2d_X509(cert, &tmp_p);
  13884. if (!EVP_Digest(
  13885. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13886. ulen = 0;
  13887. }
  13888. mg_free(tmp_buf);
  13889. }
  13890. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13891. *str_buf = 0;
  13892. }
  13893. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13894. client_cert->peer_cert = (void *)cert;
  13895. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13896. * see https://linux.die.net/man/3/bn_bn2hex */
  13897. OPENSSL_free(str_serial);
  13898. return 1;
  13899. }
  13900. return 0;
  13901. }
  13902. #if defined(OPENSSL_API_1_1)
  13903. #else
  13904. static void
  13905. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13906. {
  13907. (void)line;
  13908. (void)file;
  13909. if (mode & 1) {
  13910. /* 1 is CRYPTO_LOCK */
  13911. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13912. } else {
  13913. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13914. }
  13915. }
  13916. #endif /* OPENSSL_API_1_1 */
  13917. #if !defined(NO_SSL_DL)
  13918. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13919. static void *
  13920. load_tls_dll(char *ebuf,
  13921. size_t ebuf_len,
  13922. const char *dll_name,
  13923. struct ssl_func *sw,
  13924. int *feature_missing)
  13925. {
  13926. union {
  13927. void *p;
  13928. void (*fp)(void);
  13929. } u;
  13930. void *dll_handle;
  13931. struct ssl_func *fp;
  13932. int ok;
  13933. int truncated = 0;
  13934. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13935. mg_snprintf(NULL,
  13936. NULL, /* No truncation check for ebuf */
  13937. ebuf,
  13938. ebuf_len,
  13939. "%s: cannot load %s",
  13940. __func__,
  13941. dll_name);
  13942. return NULL;
  13943. }
  13944. ok = 1;
  13945. for (fp = sw; fp->name != NULL; fp++) {
  13946. #if defined(_WIN32)
  13947. /* GetProcAddress() returns pointer to function */
  13948. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13949. #else
  13950. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13951. * pointers to function pointers. We need to use a union to make a
  13952. * cast. */
  13953. u.p = dlsym(dll_handle, fp->name);
  13954. #endif /* _WIN32 */
  13955. /* Set pointer (might be NULL) */
  13956. fp->ptr = u.fp;
  13957. if (u.fp == NULL) {
  13958. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13959. if (feature_missing) {
  13960. feature_missing[fp->required]++;
  13961. }
  13962. if (fp->required == TLS_Mandatory) {
  13963. /* Mandatory function is missing */
  13964. if (ok) {
  13965. /* This is the first missing function.
  13966. * Create a new error message. */
  13967. mg_snprintf(NULL,
  13968. &truncated,
  13969. ebuf,
  13970. ebuf_len,
  13971. "%s: %s: cannot find %s",
  13972. __func__,
  13973. dll_name,
  13974. fp->name);
  13975. ok = 0;
  13976. } else {
  13977. /* This is yet anothermissing function.
  13978. * Append existing error message. */
  13979. size_t cur_len = strlen(ebuf);
  13980. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13981. mg_snprintf(NULL,
  13982. &truncated,
  13983. ebuf + cur_len,
  13984. ebuf_len - cur_len - 3,
  13985. ", %s",
  13986. fp->name);
  13987. if (truncated) {
  13988. /* If truncated, add "..." */
  13989. strcat(ebuf, "...");
  13990. }
  13991. }
  13992. }
  13993. }
  13994. }
  13995. }
  13996. if (!ok) {
  13997. (void)dlclose(dll_handle);
  13998. return NULL;
  13999. }
  14000. return dll_handle;
  14001. }
  14002. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14003. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14004. #endif /* NO_SSL_DL */
  14005. #if defined(SSL_ALREADY_INITIALIZED)
  14006. static volatile ptrdiff_t cryptolib_users =
  14007. 1; /* Reference counter for crypto library. */
  14008. #else
  14009. static volatile ptrdiff_t cryptolib_users =
  14010. 0; /* Reference counter for crypto library. */
  14011. #endif
  14012. static int
  14013. initialize_ssl(char *ebuf, size_t ebuf_len)
  14014. {
  14015. #if !defined(OPENSSL_API_1_1)
  14016. int i, num_locks;
  14017. size_t size;
  14018. #endif
  14019. if (ebuf_len > 0) {
  14020. ebuf[0] = 0;
  14021. }
  14022. #if !defined(NO_SSL_DL)
  14023. if (!cryptolib_dll_handle) {
  14024. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14025. cryptolib_dll_handle = load_tls_dll(
  14026. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14027. if (!cryptolib_dll_handle) {
  14028. mg_snprintf(NULL,
  14029. NULL, /* No truncation check for ebuf */
  14030. ebuf,
  14031. ebuf_len,
  14032. "%s: error loading library %s",
  14033. __func__,
  14034. CRYPTO_LIB);
  14035. DEBUG_TRACE("%s", ebuf);
  14036. return 0;
  14037. }
  14038. }
  14039. #endif /* NO_SSL_DL */
  14040. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14041. return 1;
  14042. }
  14043. #if !defined(OPENSSL_API_1_1)
  14044. /* Initialize locking callbacks, needed for thread safety.
  14045. * http://www.openssl.org/support/faq.html#PROG1
  14046. */
  14047. num_locks = CRYPTO_num_locks();
  14048. if (num_locks < 0) {
  14049. num_locks = 0;
  14050. }
  14051. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14052. /* allocate mutex array, if required */
  14053. if (num_locks == 0) {
  14054. /* No mutex array required */
  14055. ssl_mutexes = NULL;
  14056. } else {
  14057. /* Mutex array required - allocate it */
  14058. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14059. /* Check OOM */
  14060. if (ssl_mutexes == NULL) {
  14061. mg_snprintf(NULL,
  14062. NULL, /* No truncation check for ebuf */
  14063. ebuf,
  14064. ebuf_len,
  14065. "%s: cannot allocate mutexes: %s",
  14066. __func__,
  14067. ssl_error());
  14068. DEBUG_TRACE("%s", ebuf);
  14069. return 0;
  14070. }
  14071. /* initialize mutex array */
  14072. for (i = 0; i < num_locks; i++) {
  14073. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14074. mg_snprintf(NULL,
  14075. NULL, /* No truncation check for ebuf */
  14076. ebuf,
  14077. ebuf_len,
  14078. "%s: error initializing mutex %i of %i",
  14079. __func__,
  14080. i,
  14081. num_locks);
  14082. DEBUG_TRACE("%s", ebuf);
  14083. mg_free(ssl_mutexes);
  14084. return 0;
  14085. }
  14086. }
  14087. }
  14088. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14089. CRYPTO_set_id_callback(&mg_current_thread_id);
  14090. #endif /* OPENSSL_API_1_1 */
  14091. #if !defined(NO_SSL_DL)
  14092. if (!ssllib_dll_handle) {
  14093. ssllib_dll_handle =
  14094. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14095. if (!ssllib_dll_handle) {
  14096. #if !defined(OPENSSL_API_1_1)
  14097. mg_free(ssl_mutexes);
  14098. #endif
  14099. DEBUG_TRACE("%s", ebuf);
  14100. return 0;
  14101. }
  14102. }
  14103. #endif /* NO_SSL_DL */
  14104. #if defined(OPENSSL_API_1_1)
  14105. /* Initialize SSL library */
  14106. OPENSSL_init_ssl(0, NULL);
  14107. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14108. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14109. NULL);
  14110. #else
  14111. /* Initialize SSL library */
  14112. SSL_library_init();
  14113. SSL_load_error_strings();
  14114. #endif
  14115. return 1;
  14116. }
  14117. static int
  14118. ssl_use_pem_file(struct mg_context *phys_ctx,
  14119. struct mg_domain_context *dom_ctx,
  14120. const char *pem,
  14121. const char *chain)
  14122. {
  14123. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14124. mg_cry_ctx_internal(phys_ctx,
  14125. "%s: cannot open certificate file %s: %s",
  14126. __func__,
  14127. pem,
  14128. ssl_error());
  14129. return 0;
  14130. }
  14131. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14132. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14133. mg_cry_ctx_internal(phys_ctx,
  14134. "%s: cannot open private key file %s: %s",
  14135. __func__,
  14136. pem,
  14137. ssl_error());
  14138. return 0;
  14139. }
  14140. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14141. mg_cry_ctx_internal(phys_ctx,
  14142. "%s: certificate and private key do not match: %s",
  14143. __func__,
  14144. pem);
  14145. return 0;
  14146. }
  14147. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14148. * chain files that contain private keys and certificates in
  14149. * SSL_CTX_use_certificate_chain_file.
  14150. * The CivetWeb-Server used pem-Files that contained both information.
  14151. * In order to make wolfSSL work, it is split in two files.
  14152. * One file that contains key and certificate used by the server and
  14153. * an optional chain file for the ssl stack.
  14154. */
  14155. if (chain) {
  14156. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14157. mg_cry_ctx_internal(phys_ctx,
  14158. "%s: cannot use certificate chain file %s: %s",
  14159. __func__,
  14160. chain,
  14161. ssl_error());
  14162. return 0;
  14163. }
  14164. }
  14165. return 1;
  14166. }
  14167. #if defined(OPENSSL_API_1_1)
  14168. static unsigned long
  14169. ssl_get_protocol(int version_id)
  14170. {
  14171. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14172. if (version_id > 0)
  14173. ret |= SSL_OP_NO_SSLv2;
  14174. if (version_id > 1)
  14175. ret |= SSL_OP_NO_SSLv3;
  14176. if (version_id > 2)
  14177. ret |= SSL_OP_NO_TLSv1;
  14178. if (version_id > 3)
  14179. ret |= SSL_OP_NO_TLSv1_1;
  14180. if (version_id > 4)
  14181. ret |= SSL_OP_NO_TLSv1_2;
  14182. #if defined(SSL_OP_NO_TLSv1_3)
  14183. if (version_id > 5)
  14184. ret |= SSL_OP_NO_TLSv1_3;
  14185. #endif
  14186. return ret;
  14187. }
  14188. #else
  14189. static long
  14190. ssl_get_protocol(int version_id)
  14191. {
  14192. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14193. if (version_id > 0)
  14194. ret |= SSL_OP_NO_SSLv2;
  14195. if (version_id > 1)
  14196. ret |= SSL_OP_NO_SSLv3;
  14197. if (version_id > 2)
  14198. ret |= SSL_OP_NO_TLSv1;
  14199. if (version_id > 3)
  14200. ret |= SSL_OP_NO_TLSv1_1;
  14201. if (version_id > 4)
  14202. ret |= SSL_OP_NO_TLSv1_2;
  14203. #if defined(SSL_OP_NO_TLSv1_3)
  14204. if (version_id > 5)
  14205. ret |= SSL_OP_NO_TLSv1_3;
  14206. #endif
  14207. return (long)ret;
  14208. }
  14209. #endif /* OPENSSL_API_1_1 */
  14210. /* SSL callback documentation:
  14211. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14212. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14213. * https://linux.die.net/man/3/ssl_set_info_callback */
  14214. /* Note: There is no "const" for the first argument in the documentation
  14215. * examples, however some (maybe most, but not all) headers of OpenSSL
  14216. * versions / OpenSSL compatibility layers have it. Having a different
  14217. * definition will cause a warning in C and an error in C++. Use "const SSL
  14218. * *", while automatical conversion from "SSL *" works for all compilers,
  14219. * but not other way around */
  14220. static void
  14221. ssl_info_callback(const SSL *ssl, int what, int ret)
  14222. {
  14223. (void)ret;
  14224. if (what & SSL_CB_HANDSHAKE_START) {
  14225. SSL_get_app_data(ssl);
  14226. }
  14227. if (what & SSL_CB_HANDSHAKE_DONE) {
  14228. /* TODO: check for openSSL 1.1 */
  14229. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14230. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14231. }
  14232. }
  14233. static int
  14234. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14235. {
  14236. #if defined(GCC_DIAGNOSTIC)
  14237. #pragma GCC diagnostic push
  14238. #pragma GCC diagnostic ignored "-Wcast-align"
  14239. #endif /* defined(GCC_DIAGNOSTIC) */
  14240. /* We used an aligned pointer in SSL_set_app_data */
  14241. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14242. #if defined(GCC_DIAGNOSTIC)
  14243. #pragma GCC diagnostic pop
  14244. #endif /* defined(GCC_DIAGNOSTIC) */
  14245. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14246. (void)ad;
  14247. (void)arg;
  14248. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14249. DEBUG_ASSERT(0);
  14250. return SSL_TLSEXT_ERR_NOACK;
  14251. }
  14252. conn->dom_ctx = &(conn->phys_ctx->dd);
  14253. /* Old clients (Win XP) will not support SNI. Then, there
  14254. * is no server name available in the request - we can
  14255. * only work with the default certificate.
  14256. * Multiple HTTPS hosts on one IP+port are only possible
  14257. * with a certificate containing all alternative names.
  14258. */
  14259. if ((servername == NULL) || (*servername == 0)) {
  14260. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14261. mg_lock_context(conn->phys_ctx);
  14262. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14263. mg_unlock_context(conn->phys_ctx);
  14264. return SSL_TLSEXT_ERR_NOACK;
  14265. }
  14266. DEBUG_TRACE("TLS connection to host %s", servername);
  14267. while (conn->dom_ctx) {
  14268. if (!mg_strcasecmp(servername,
  14269. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14270. /* Found matching domain */
  14271. DEBUG_TRACE("TLS domain %s found",
  14272. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14273. break;
  14274. }
  14275. mg_lock_context(conn->phys_ctx);
  14276. conn->dom_ctx = conn->dom_ctx->next;
  14277. mg_unlock_context(conn->phys_ctx);
  14278. }
  14279. if (conn->dom_ctx == NULL) {
  14280. /* Default domain */
  14281. DEBUG_TRACE("TLS default domain %s used",
  14282. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14283. conn->dom_ctx = &(conn->phys_ctx->dd);
  14284. }
  14285. mg_lock_context(conn->phys_ctx);
  14286. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14287. mg_unlock_context(conn->phys_ctx);
  14288. return SSL_TLSEXT_ERR_OK;
  14289. }
  14290. #if defined(USE_ALPN)
  14291. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14292. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14293. alpn_proto_list + 3 + 8,
  14294. NULL};
  14295. #if defined(USE_HTTP2)
  14296. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14297. alpn_proto_list + 3,
  14298. alpn_proto_list + 3 + 8,
  14299. NULL};
  14300. #endif
  14301. static int
  14302. alpn_select_cb(SSL *ssl,
  14303. const unsigned char **out,
  14304. unsigned char *outlen,
  14305. const unsigned char *in,
  14306. unsigned int inlen,
  14307. void *arg)
  14308. {
  14309. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14310. unsigned int i, j, enable_http2 = 0;
  14311. const char **alpn_proto_order = alpn_proto_order_http1;
  14312. struct mg_workerTLS *tls =
  14313. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14314. (void)ssl;
  14315. if (tls == NULL) {
  14316. /* Need to store protocol in Thread Local Storage */
  14317. /* If there is no Thread Local Storage, don't use ALPN */
  14318. return SSL_TLSEXT_ERR_NOACK;
  14319. }
  14320. #if defined(USE_HTTP2)
  14321. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14322. if (enable_http2) {
  14323. alpn_proto_order = alpn_proto_order_http2;
  14324. }
  14325. #endif
  14326. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14327. /* check all accepted protocols in this order */
  14328. const char *alpn_proto = alpn_proto_order[j];
  14329. /* search input for matching protocol */
  14330. for (i = 0; i < inlen; i++) {
  14331. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14332. *out = in + i + 1;
  14333. *outlen = in[i];
  14334. tls->alpn_proto = alpn_proto;
  14335. return SSL_TLSEXT_ERR_OK;
  14336. }
  14337. }
  14338. }
  14339. /* Nothing found */
  14340. return SSL_TLSEXT_ERR_NOACK;
  14341. }
  14342. static int
  14343. next_protos_advertised_cb(SSL *ssl,
  14344. const unsigned char **data,
  14345. unsigned int *len,
  14346. void *arg)
  14347. {
  14348. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14349. *data = (const unsigned char *)alpn_proto_list;
  14350. *len = (unsigned int)strlen((const char *)data);
  14351. (void)ssl;
  14352. (void)dom_ctx;
  14353. return SSL_TLSEXT_ERR_OK;
  14354. }
  14355. static int
  14356. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14357. {
  14358. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14359. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14360. (const unsigned char *)alpn_proto_list,
  14361. alpn_len);
  14362. if (ret != 0) {
  14363. mg_cry_ctx_internal(phys_ctx,
  14364. "SSL_CTX_set_alpn_protos error: %s",
  14365. ssl_error());
  14366. }
  14367. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14368. alpn_select_cb,
  14369. (void *)dom_ctx);
  14370. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14371. next_protos_advertised_cb,
  14372. (void *)dom_ctx);
  14373. return ret;
  14374. }
  14375. #endif
  14376. /* Setup SSL CTX as required by CivetWeb */
  14377. static int
  14378. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14379. struct mg_domain_context *dom_ctx,
  14380. const char *pem,
  14381. const char *chain)
  14382. {
  14383. int callback_ret;
  14384. int should_verify_peer;
  14385. int peer_certificate_optional;
  14386. const char *ca_path;
  14387. const char *ca_file;
  14388. int use_default_verify_paths;
  14389. int verify_depth;
  14390. struct timespec now_mt;
  14391. md5_byte_t ssl_context_id[16];
  14392. md5_state_t md5state;
  14393. int protocol_ver;
  14394. int ssl_cache_timeout;
  14395. #if defined(OPENSSL_API_1_1)
  14396. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14397. mg_cry_ctx_internal(phys_ctx,
  14398. "SSL_CTX_new (server) error: %s",
  14399. ssl_error());
  14400. return 0;
  14401. }
  14402. #else
  14403. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14404. mg_cry_ctx_internal(phys_ctx,
  14405. "SSL_CTX_new (server) error: %s",
  14406. ssl_error());
  14407. return 0;
  14408. }
  14409. #endif /* OPENSSL_API_1_1 */
  14410. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14411. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14412. | SSL_OP_NO_TLSv1_1);
  14413. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14414. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14415. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14416. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14417. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14418. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14419. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14420. #if defined(SSL_OP_NO_RENEGOTIATION)
  14421. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14422. #endif
  14423. #if !defined(NO_SSL_DL)
  14424. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14425. #endif /* NO_SSL_DL */
  14426. /* In SSL documentation examples callback defined without const
  14427. * specifier 'void (*)(SSL *, int, int)' See:
  14428. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14429. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14430. * But in the source code const SSL is used:
  14431. * 'void (*)(const SSL *, int, int)' See:
  14432. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14433. * Problem about wrong documentation described, but not resolved:
  14434. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14435. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14436. * But when compiled with modern C++ compiler, correct const should be
  14437. * provided
  14438. */
  14439. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14440. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14441. ssl_servername_callback);
  14442. /* If a callback has been specified, call it. */
  14443. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14444. ? 0
  14445. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14446. phys_ctx->user_data));
  14447. /* If callback returns 0, civetweb sets up the SSL certificate.
  14448. * If it returns 1, civetweb assumes the calback already did this.
  14449. * If it returns -1, initializing ssl fails. */
  14450. if (callback_ret < 0) {
  14451. mg_cry_ctx_internal(phys_ctx,
  14452. "SSL callback returned error: %i",
  14453. callback_ret);
  14454. return 0;
  14455. }
  14456. if (callback_ret > 0) {
  14457. /* Callback did everything. */
  14458. return 1;
  14459. }
  14460. /* If a domain callback has been specified, call it. */
  14461. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14462. ? 0
  14463. : (phys_ctx->callbacks.init_ssl_domain(
  14464. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14465. dom_ctx->ssl_ctx,
  14466. phys_ctx->user_data));
  14467. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14468. * If it returns 1, civetweb assumes the calback already did this.
  14469. * If it returns -1, initializing ssl fails. */
  14470. if (callback_ret < 0) {
  14471. mg_cry_ctx_internal(phys_ctx,
  14472. "Domain SSL callback returned error: %i",
  14473. callback_ret);
  14474. return 0;
  14475. }
  14476. if (callback_ret > 0) {
  14477. /* Domain callback did everything. */
  14478. return 1;
  14479. }
  14480. /* Use some combination of start time, domain and port as a SSL
  14481. * context ID. This should be unique on the current machine. */
  14482. md5_init(&md5state);
  14483. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14484. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14485. md5_append(&md5state,
  14486. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14487. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14488. md5_append(&md5state,
  14489. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14490. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14491. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14492. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14493. md5_finish(&md5state, ssl_context_id);
  14494. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14495. (unsigned char *)ssl_context_id,
  14496. sizeof(ssl_context_id));
  14497. if (pem != NULL) {
  14498. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14499. return 0;
  14500. }
  14501. }
  14502. /* Should we support client certificates? */
  14503. /* Default is "no". */
  14504. should_verify_peer = 0;
  14505. peer_certificate_optional = 0;
  14506. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14507. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14508. /* Yes, they are mandatory */
  14509. should_verify_peer = 1;
  14510. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14511. "optional")
  14512. == 0) {
  14513. /* Yes, they are optional */
  14514. should_verify_peer = 1;
  14515. peer_certificate_optional = 1;
  14516. }
  14517. }
  14518. use_default_verify_paths =
  14519. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14520. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14521. == 0);
  14522. if (should_verify_peer) {
  14523. ca_path = dom_ctx->config[SSL_CA_PATH];
  14524. ca_file = dom_ctx->config[SSL_CA_FILE];
  14525. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14526. != 1) {
  14527. mg_cry_ctx_internal(phys_ctx,
  14528. "SSL_CTX_load_verify_locations error: %s "
  14529. "ssl_verify_peer requires setting "
  14530. "either ssl_ca_path or ssl_ca_file. "
  14531. "Is any of them present in the "
  14532. ".conf file?",
  14533. ssl_error());
  14534. return 0;
  14535. }
  14536. if (peer_certificate_optional) {
  14537. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14538. } else {
  14539. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14540. SSL_VERIFY_PEER
  14541. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14542. NULL);
  14543. }
  14544. if (use_default_verify_paths
  14545. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14546. mg_cry_ctx_internal(phys_ctx,
  14547. "SSL_CTX_set_default_verify_paths error: %s",
  14548. ssl_error());
  14549. return 0;
  14550. }
  14551. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14552. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14553. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14554. }
  14555. }
  14556. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14557. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14558. dom_ctx->config[SSL_CIPHER_LIST])
  14559. != 1) {
  14560. mg_cry_ctx_internal(phys_ctx,
  14561. "SSL_CTX_set_cipher_list error: %s",
  14562. ssl_error());
  14563. }
  14564. }
  14565. /* SSL session caching */
  14566. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14567. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14568. : 0);
  14569. if (ssl_cache_timeout > 0) {
  14570. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14571. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14572. * default */
  14573. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14574. }
  14575. #if defined(USE_ALPN)
  14576. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14577. #if !defined(NO_SSL_DL)
  14578. if (!tls_feature_missing[TLS_ALPN])
  14579. #endif
  14580. {
  14581. init_alpn(phys_ctx, dom_ctx);
  14582. }
  14583. #endif
  14584. return 1;
  14585. }
  14586. /* Check if SSL is required.
  14587. * If so, dynamically load SSL library
  14588. * and set up ctx->ssl_ctx pointer. */
  14589. static int
  14590. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14591. {
  14592. void *ssl_ctx = 0;
  14593. int callback_ret;
  14594. const char *pem;
  14595. const char *chain;
  14596. char ebuf[128];
  14597. if (!phys_ctx) {
  14598. return 0;
  14599. }
  14600. if (!dom_ctx) {
  14601. dom_ctx = &(phys_ctx->dd);
  14602. }
  14603. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14604. /* No SSL port is set. No need to setup SSL. */
  14605. return 1;
  14606. }
  14607. /* Check for external SSL_CTX */
  14608. callback_ret =
  14609. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14610. ? 0
  14611. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14612. phys_ctx->user_data));
  14613. if (callback_ret < 0) {
  14614. /* Callback exists and returns <0: Initializing failed. */
  14615. mg_cry_ctx_internal(phys_ctx,
  14616. "external_ssl_ctx callback returned error: %i",
  14617. callback_ret);
  14618. return 0;
  14619. } else if (callback_ret > 0) {
  14620. /* Callback exists and returns >0: Initializing complete,
  14621. * civetweb should not modify the SSL context. */
  14622. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14623. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14624. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14625. return 0;
  14626. }
  14627. return 1;
  14628. }
  14629. /* If the callback does not exist or return 0, civetweb must initialize
  14630. * the SSL context. Handle "domain" callback next. */
  14631. /* Check for external domain SSL_CTX callback. */
  14632. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14633. ? 0
  14634. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14635. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14636. &ssl_ctx,
  14637. phys_ctx->user_data));
  14638. if (callback_ret < 0) {
  14639. /* Callback < 0: Error. Abort init. */
  14640. mg_cry_ctx_internal(
  14641. phys_ctx,
  14642. "external_ssl_ctx_domain callback returned error: %i",
  14643. callback_ret);
  14644. return 0;
  14645. } else if (callback_ret > 0) {
  14646. /* Callback > 0: Consider init done. */
  14647. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14648. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14649. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14650. return 0;
  14651. }
  14652. return 1;
  14653. }
  14654. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14655. * 0, CivetWeb should continue initializing SSL */
  14656. /* If PEM file is not specified and the init_ssl callbacks
  14657. * are not specified, setup will fail. */
  14658. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14659. && (phys_ctx->callbacks.init_ssl == NULL)
  14660. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14661. /* No certificate and no init_ssl callbacks:
  14662. * Essential data to set up TLS is missing.
  14663. */
  14664. mg_cry_ctx_internal(phys_ctx,
  14665. "Initializing SSL failed: -%s is not set",
  14666. config_options[SSL_CERTIFICATE].name);
  14667. return 0;
  14668. }
  14669. /* If a certificate chain is configured, use it. */
  14670. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14671. if (chain == NULL) {
  14672. /* Default: certificate chain in PEM file */
  14673. chain = pem;
  14674. }
  14675. if ((chain != NULL) && (*chain == 0)) {
  14676. /* If the chain is an empty string, don't use it. */
  14677. chain = NULL;
  14678. }
  14679. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  14680. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14681. return 0;
  14682. }
  14683. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14684. }
  14685. static void
  14686. uninitialize_ssl(void)
  14687. {
  14688. #if defined(OPENSSL_API_1_1)
  14689. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14690. /* Shutdown according to
  14691. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14692. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14693. */
  14694. CONF_modules_unload(1);
  14695. #else
  14696. int i;
  14697. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14698. /* Shutdown according to
  14699. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14700. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14701. */
  14702. CRYPTO_set_locking_callback(NULL);
  14703. CRYPTO_set_id_callback(NULL);
  14704. ENGINE_cleanup();
  14705. CONF_modules_unload(1);
  14706. ERR_free_strings();
  14707. EVP_cleanup();
  14708. CRYPTO_cleanup_all_ex_data();
  14709. OPENSSL_REMOVE_THREAD_STATE();
  14710. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14711. pthread_mutex_destroy(&ssl_mutexes[i]);
  14712. }
  14713. mg_free(ssl_mutexes);
  14714. ssl_mutexes = NULL;
  14715. #endif /* OPENSSL_API_1_1 */
  14716. }
  14717. }
  14718. #endif /* !NO_SSL */
  14719. #if !defined(NO_FILESYSTEMS)
  14720. static int
  14721. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14722. {
  14723. if (phys_ctx) {
  14724. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14725. const char *path;
  14726. struct mg_connection fc;
  14727. if (!dom_ctx) {
  14728. dom_ctx = &(phys_ctx->dd);
  14729. }
  14730. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14731. if ((path != NULL)
  14732. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14733. mg_cry_ctx_internal(phys_ctx,
  14734. "Cannot open %s: %s",
  14735. path,
  14736. strerror(ERRNO));
  14737. return 0;
  14738. }
  14739. return 1;
  14740. }
  14741. return 0;
  14742. }
  14743. #endif /* NO_FILESYSTEMS */
  14744. static int
  14745. set_acl_option(struct mg_context *phys_ctx)
  14746. {
  14747. union usa sa;
  14748. memset(&sa, 0, sizeof(sa));
  14749. #if defined(USE_IPV6)
  14750. sa.sin6.sin6_family = AF_INET6;
  14751. #else
  14752. sa.sin.sin_family = AF_INET;
  14753. #endif
  14754. return check_acl(phys_ctx, &sa) != -1;
  14755. }
  14756. static void
  14757. reset_per_request_attributes(struct mg_connection *conn)
  14758. {
  14759. if (!conn) {
  14760. return;
  14761. }
  14762. conn->num_bytes_sent = conn->consumed_content = 0;
  14763. conn->path_info = NULL;
  14764. conn->status_code = -1;
  14765. conn->content_len = -1;
  14766. conn->is_chunked = 0;
  14767. conn->must_close = 0;
  14768. conn->request_len = 0;
  14769. conn->request_state = 0;
  14770. conn->throttle = 0;
  14771. conn->accept_gzip = 0;
  14772. conn->response_info.content_length = conn->request_info.content_length = -1;
  14773. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14774. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14775. conn->response_info.status_text = NULL;
  14776. conn->response_info.status_code = 0;
  14777. conn->request_info.remote_user = NULL;
  14778. conn->request_info.request_method = NULL;
  14779. conn->request_info.request_uri = NULL;
  14780. conn->request_info.local_uri = NULL;
  14781. #if defined(MG_LEGACY_INTERFACE)
  14782. /* Legacy before split into local_uri and request_uri */
  14783. conn->request_info.uri = NULL;
  14784. #endif
  14785. }
  14786. static int
  14787. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14788. {
  14789. if ((so->lsa.sa.sa_family == AF_INET)
  14790. || (so->lsa.sa.sa_family == AF_INET6)) {
  14791. /* Only for TCP sockets */
  14792. if (setsockopt(so->sock,
  14793. IPPROTO_TCP,
  14794. TCP_NODELAY,
  14795. (SOCK_OPT_TYPE)&nodelay_on,
  14796. sizeof(nodelay_on))
  14797. != 0) {
  14798. /* Error */
  14799. return 1;
  14800. }
  14801. }
  14802. /* OK */
  14803. return 0;
  14804. }
  14805. #if !defined(__ZEPHYR__)
  14806. static void
  14807. close_socket_gracefully(struct mg_connection *conn)
  14808. {
  14809. #if defined(_WIN32)
  14810. char buf[MG_BUF_LEN];
  14811. int n;
  14812. #endif
  14813. struct linger linger;
  14814. int error_code = 0;
  14815. int linger_timeout = -2;
  14816. socklen_t opt_len = sizeof(error_code);
  14817. if (!conn) {
  14818. return;
  14819. }
  14820. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14821. * "Note that enabling a nonzero timeout on a nonblocking socket
  14822. * is not recommended.", so set it to blocking now */
  14823. set_blocking_mode(conn->client.sock);
  14824. /* Send FIN to the client */
  14825. shutdown(conn->client.sock, SHUTDOWN_WR);
  14826. #if defined(_WIN32)
  14827. /* Read and discard pending incoming data. If we do not do that and
  14828. * close
  14829. * the socket, the data in the send buffer may be discarded. This
  14830. * behaviour is seen on Windows, when client keeps sending data
  14831. * when server decides to close the connection; then when client
  14832. * does recv() it gets no data back. */
  14833. do {
  14834. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14835. } while (n > 0);
  14836. #endif
  14837. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14838. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14839. }
  14840. /* Set linger option according to configuration */
  14841. if (linger_timeout >= 0) {
  14842. /* Set linger option to avoid socket hanging out after close. This
  14843. * prevent ephemeral port exhaust problem under high QPS. */
  14844. linger.l_onoff = 1;
  14845. #if defined(_MSC_VER)
  14846. #pragma warning(push)
  14847. #pragma warning(disable : 4244)
  14848. #endif
  14849. #if defined(GCC_DIAGNOSTIC)
  14850. #pragma GCC diagnostic push
  14851. #pragma GCC diagnostic ignored "-Wconversion"
  14852. #endif
  14853. /* Data type of linger structure elements may differ,
  14854. * so we don't know what cast we need here.
  14855. * Disable type conversion warnings. */
  14856. linger.l_linger = (linger_timeout + 999) / 1000;
  14857. #if defined(GCC_DIAGNOSTIC)
  14858. #pragma GCC diagnostic pop
  14859. #endif
  14860. #if defined(_MSC_VER)
  14861. #pragma warning(pop)
  14862. #endif
  14863. } else {
  14864. linger.l_onoff = 0;
  14865. linger.l_linger = 0;
  14866. }
  14867. if (linger_timeout < -1) {
  14868. /* Default: don't configure any linger */
  14869. } else if (getsockopt(conn->client.sock,
  14870. SOL_SOCKET,
  14871. SO_ERROR,
  14872. #if defined(_WIN32) /* WinSock uses different data type here */
  14873. (char *)&error_code,
  14874. #else
  14875. &error_code,
  14876. #endif
  14877. &opt_len)
  14878. != 0) {
  14879. /* Cannot determine if socket is already closed. This should
  14880. * not occur and never did in a test. Log an error message
  14881. * and continue. */
  14882. mg_cry_internal(conn,
  14883. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14884. __func__,
  14885. strerror(ERRNO));
  14886. #if defined(_WIN32)
  14887. } else if (error_code == WSAECONNRESET) {
  14888. #else
  14889. } else if (error_code == ECONNRESET) {
  14890. #endif
  14891. /* Socket already closed by client/peer, close socket without linger
  14892. */
  14893. } else {
  14894. /* Set linger timeout */
  14895. if (setsockopt(conn->client.sock,
  14896. SOL_SOCKET,
  14897. SO_LINGER,
  14898. (char *)&linger,
  14899. sizeof(linger))
  14900. != 0) {
  14901. mg_cry_internal(
  14902. conn,
  14903. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14904. __func__,
  14905. linger.l_onoff,
  14906. linger.l_linger,
  14907. strerror(ERRNO));
  14908. }
  14909. }
  14910. /* Now we know that our FIN is ACK-ed, safe to close */
  14911. closesocket(conn->client.sock);
  14912. conn->client.sock = INVALID_SOCKET;
  14913. }
  14914. #endif
  14915. static void
  14916. close_connection(struct mg_connection *conn)
  14917. {
  14918. #if defined(USE_SERVER_STATS)
  14919. conn->conn_state = 6; /* to close */
  14920. #endif
  14921. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14922. if (conn->lua_websocket_state) {
  14923. lua_websocket_close(conn, conn->lua_websocket_state);
  14924. conn->lua_websocket_state = NULL;
  14925. }
  14926. #endif
  14927. mg_lock_connection(conn);
  14928. /* Set close flag, so keep-alive loops will stop */
  14929. conn->must_close = 1;
  14930. /* call the connection_close callback if assigned */
  14931. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14932. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14933. conn->phys_ctx->callbacks.connection_close(conn);
  14934. }
  14935. }
  14936. /* Reset user data, after close callback is called.
  14937. * Do not reuse it. If the user needs a destructor,
  14938. * it must be done in the connection_close callback. */
  14939. mg_set_user_connection_data(conn, NULL);
  14940. #if defined(USE_SERVER_STATS)
  14941. conn->conn_state = 7; /* closing */
  14942. #endif
  14943. #if !defined(NO_SSL)
  14944. if (conn->ssl != NULL) {
  14945. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14946. */
  14947. SSL_shutdown(conn->ssl);
  14948. SSL_free(conn->ssl);
  14949. OPENSSL_REMOVE_THREAD_STATE();
  14950. conn->ssl = NULL;
  14951. }
  14952. #endif
  14953. if (conn->client.sock != INVALID_SOCKET) {
  14954. #if defined(__ZEPHYR__)
  14955. closesocket(conn->client.sock);
  14956. #else
  14957. close_socket_gracefully(conn);
  14958. #endif
  14959. conn->client.sock = INVALID_SOCKET;
  14960. }
  14961. mg_unlock_connection(conn);
  14962. #if defined(USE_SERVER_STATS)
  14963. conn->conn_state = 8; /* closed */
  14964. #endif
  14965. }
  14966. void
  14967. mg_close_connection(struct mg_connection *conn)
  14968. {
  14969. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14970. return;
  14971. }
  14972. #if defined(USE_WEBSOCKET)
  14973. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14974. if (conn->in_websocket_handling) {
  14975. /* Set close flag, so the server thread can exit. */
  14976. conn->must_close = 1;
  14977. return;
  14978. }
  14979. }
  14980. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14981. unsigned int i;
  14982. /* client context: loops must end */
  14983. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14984. conn->must_close = 1;
  14985. /* We need to get the client thread out of the select/recv call
  14986. * here. */
  14987. /* Since we use a sleep quantum of some seconds to check for recv
  14988. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14989. /* join worker thread */
  14990. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14991. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14992. }
  14993. }
  14994. #endif /* defined(USE_WEBSOCKET) */
  14995. close_connection(conn);
  14996. #if !defined(NO_SSL)
  14997. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14998. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14999. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15000. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15001. }
  15002. #endif
  15003. #if defined(USE_WEBSOCKET)
  15004. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15005. mg_free(conn->phys_ctx->worker_threadids);
  15006. (void)pthread_mutex_destroy(&conn->mutex);
  15007. mg_free(conn);
  15008. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15009. (void)pthread_mutex_destroy(&conn->mutex);
  15010. mg_free(conn);
  15011. }
  15012. #else
  15013. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15014. (void)pthread_mutex_destroy(&conn->mutex);
  15015. mg_free(conn);
  15016. }
  15017. #endif /* defined(USE_WEBSOCKET) */
  15018. }
  15019. static struct mg_connection *
  15020. mg_connect_client_impl(const struct mg_client_options *client_options,
  15021. int use_ssl,
  15022. char *ebuf,
  15023. size_t ebuf_len)
  15024. {
  15025. struct mg_connection *conn = NULL;
  15026. SOCKET sock;
  15027. union usa sa;
  15028. struct sockaddr *psa;
  15029. socklen_t len;
  15030. unsigned max_req_size =
  15031. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15032. /* Size of structures, aligned to 8 bytes */
  15033. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15034. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15035. conn =
  15036. (struct mg_connection *)mg_calloc(1,
  15037. conn_size + ctx_size + max_req_size);
  15038. if (conn == NULL) {
  15039. mg_snprintf(NULL,
  15040. NULL, /* No truncation check for ebuf */
  15041. ebuf,
  15042. ebuf_len,
  15043. "calloc(): %s",
  15044. strerror(ERRNO));
  15045. return NULL;
  15046. }
  15047. #if defined(GCC_DIAGNOSTIC)
  15048. #pragma GCC diagnostic push
  15049. #pragma GCC diagnostic ignored "-Wcast-align"
  15050. #endif /* defined(GCC_DIAGNOSTIC) */
  15051. /* conn_size is aligned to 8 bytes */
  15052. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15053. #if defined(GCC_DIAGNOSTIC)
  15054. #pragma GCC diagnostic pop
  15055. #endif /* defined(GCC_DIAGNOSTIC) */
  15056. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15057. conn->buf_size = (int)max_req_size;
  15058. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15059. conn->dom_ctx = &(conn->phys_ctx->dd);
  15060. if (!connect_socket(conn->phys_ctx,
  15061. client_options->host,
  15062. client_options->port,
  15063. use_ssl,
  15064. ebuf,
  15065. ebuf_len,
  15066. &sock,
  15067. &sa)) {
  15068. /* ebuf is set by connect_socket,
  15069. * free all memory and return NULL; */
  15070. mg_free(conn);
  15071. return NULL;
  15072. }
  15073. #if !defined(NO_SSL)
  15074. #if defined(OPENSSL_API_1_1)
  15075. if (use_ssl
  15076. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15077. == NULL) {
  15078. mg_snprintf(NULL,
  15079. NULL, /* No truncation check for ebuf */
  15080. ebuf,
  15081. ebuf_len,
  15082. "SSL_CTX_new error: %s",
  15083. ssl_error());
  15084. closesocket(sock);
  15085. mg_free(conn);
  15086. return NULL;
  15087. }
  15088. #else
  15089. if (use_ssl
  15090. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15091. == NULL) {
  15092. mg_snprintf(NULL,
  15093. NULL, /* No truncation check for ebuf */
  15094. ebuf,
  15095. ebuf_len,
  15096. "SSL_CTX_new error: %s",
  15097. ssl_error());
  15098. closesocket(sock);
  15099. mg_free(conn);
  15100. return NULL;
  15101. }
  15102. #endif /* OPENSSL_API_1_1 */
  15103. #endif /* NO_SSL */
  15104. #if defined(USE_IPV6)
  15105. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15106. : sizeof(conn->client.rsa.sin6);
  15107. psa = (sa.sa.sa_family == AF_INET)
  15108. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15109. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15110. #else
  15111. len = sizeof(conn->client.rsa.sin);
  15112. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15113. #endif
  15114. conn->client.sock = sock;
  15115. conn->client.lsa = sa;
  15116. if (getsockname(sock, psa, &len) != 0) {
  15117. mg_cry_internal(conn,
  15118. "%s: getsockname() failed: %s",
  15119. __func__,
  15120. strerror(ERRNO));
  15121. }
  15122. conn->client.is_ssl = use_ssl ? 1 : 0;
  15123. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15124. mg_snprintf(NULL,
  15125. NULL, /* No truncation check for ebuf */
  15126. ebuf,
  15127. ebuf_len,
  15128. "Can not create mutex");
  15129. #if !defined(NO_SSL)
  15130. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15131. #endif
  15132. closesocket(sock);
  15133. mg_free(conn);
  15134. return NULL;
  15135. }
  15136. #if !defined(NO_SSL)
  15137. if (use_ssl) {
  15138. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15139. * SSL_CTX_set_verify call is needed to switch off server
  15140. * certificate checking, which is off by default in OpenSSL and
  15141. * on in yaSSL. */
  15142. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15143. * SSL_VERIFY_PEER, verify_ssl_server); */
  15144. if (client_options->client_cert) {
  15145. if (!ssl_use_pem_file(conn->phys_ctx,
  15146. conn->dom_ctx,
  15147. client_options->client_cert,
  15148. NULL)) {
  15149. mg_snprintf(NULL,
  15150. NULL, /* No truncation check for ebuf */
  15151. ebuf,
  15152. ebuf_len,
  15153. "Can not use SSL client certificate");
  15154. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15155. closesocket(sock);
  15156. mg_free(conn);
  15157. return NULL;
  15158. }
  15159. }
  15160. if (client_options->server_cert) {
  15161. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15162. client_options->server_cert,
  15163. NULL)
  15164. != 1) {
  15165. mg_cry_internal(conn,
  15166. "SSL_CTX_load_verify_locations error: %s ",
  15167. ssl_error());
  15168. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15169. closesocket(sock);
  15170. mg_free(conn);
  15171. return NULL;
  15172. }
  15173. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15174. } else {
  15175. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15176. }
  15177. if (!sslize(conn, SSL_connect, client_options)) {
  15178. mg_snprintf(NULL,
  15179. NULL, /* No truncation check for ebuf */
  15180. ebuf,
  15181. ebuf_len,
  15182. "SSL connection error");
  15183. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15184. closesocket(sock);
  15185. mg_free(conn);
  15186. return NULL;
  15187. }
  15188. }
  15189. #endif
  15190. return conn;
  15191. }
  15192. CIVETWEB_API struct mg_connection *
  15193. mg_connect_client_secure(const struct mg_client_options *client_options,
  15194. char *error_buffer,
  15195. size_t error_buffer_size)
  15196. {
  15197. return mg_connect_client_impl(client_options,
  15198. 1,
  15199. error_buffer,
  15200. error_buffer_size);
  15201. }
  15202. struct mg_connection *
  15203. mg_connect_client(const char *host,
  15204. int port,
  15205. int use_ssl,
  15206. char *error_buffer,
  15207. size_t error_buffer_size)
  15208. {
  15209. struct mg_client_options opts;
  15210. memset(&opts, 0, sizeof(opts));
  15211. opts.host = host;
  15212. opts.port = port;
  15213. return mg_connect_client_impl(&opts,
  15214. use_ssl,
  15215. error_buffer,
  15216. error_buffer_size);
  15217. }
  15218. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15219. struct mg_connection *
  15220. mg_connect_client2(const char *host,
  15221. const char *protocol,
  15222. int port,
  15223. const char *path,
  15224. struct mg_init_data *init,
  15225. struct mg_error_data *error)
  15226. {
  15227. int is_ssl, is_ws;
  15228. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15229. if (error != NULL) {
  15230. error->code = 0;
  15231. if (error->text_buffer_size > 0) {
  15232. *error->text = 0;
  15233. }
  15234. }
  15235. if ((host == NULL) || (protocol == NULL)) {
  15236. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15237. mg_snprintf(NULL,
  15238. NULL, /* No truncation check for error buffers */
  15239. error->text,
  15240. error->text_buffer_size,
  15241. "%s",
  15242. "Invalid parameters");
  15243. }
  15244. return NULL;
  15245. }
  15246. /* check all known protocolls */
  15247. if (!mg_strcasecmp(protocol, "http")) {
  15248. is_ssl = 0;
  15249. is_ws = 0;
  15250. } else if (!mg_strcasecmp(protocol, "https")) {
  15251. is_ssl = 1;
  15252. is_ws = 0;
  15253. #if defined(USE_WEBSOCKET)
  15254. } else if (!mg_strcasecmp(protocol, "ws")) {
  15255. is_ssl = 0;
  15256. is_ws = 1;
  15257. } else if (!mg_strcasecmp(protocol, "wss")) {
  15258. is_ssl = 1;
  15259. is_ws = 1;
  15260. #endif
  15261. } else {
  15262. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15263. mg_snprintf(NULL,
  15264. NULL, /* No truncation check for error buffers */
  15265. error->text,
  15266. error->text_buffer_size,
  15267. "Protocol %s not supported",
  15268. protocol);
  15269. }
  15270. return NULL;
  15271. }
  15272. /* TODO: The current implementation here just calls the old
  15273. * implementations, without using any new options. This is just a first
  15274. * step to test the new interfaces. */
  15275. #if defined(USE_WEBSOCKET)
  15276. if (is_ws) {
  15277. /* TODO: implement all options */
  15278. return mg_connect_websocket_client(
  15279. host,
  15280. port,
  15281. is_ssl,
  15282. ((error != NULL) ? error->text : NULL),
  15283. ((error != NULL) ? error->text_buffer_size : 0),
  15284. (path ? path : ""),
  15285. NULL /* TODO: origin */,
  15286. experimental_websocket_client_data_wrapper,
  15287. experimental_websocket_client_close_wrapper,
  15288. (void *)init->callbacks);
  15289. }
  15290. #endif
  15291. /* TODO: all additional options */
  15292. struct mg_client_options opts;
  15293. memset(&opts, 0, sizeof(opts));
  15294. opts.host = host;
  15295. opts.port = port;
  15296. return mg_connect_client_impl(&opts,
  15297. is_ssl,
  15298. ((error != NULL) ? error->text : NULL),
  15299. ((error != NULL) ? error->text_buffer_size
  15300. : 0));
  15301. }
  15302. #endif
  15303. static const struct {
  15304. const char *proto;
  15305. size_t proto_len;
  15306. unsigned default_port;
  15307. } abs_uri_protocols[] = {{"http://", 7, 80},
  15308. {"https://", 8, 443},
  15309. {"ws://", 5, 80},
  15310. {"wss://", 6, 443},
  15311. {NULL, 0, 0}};
  15312. /* Check if the uri is valid.
  15313. * return 0 for invalid uri,
  15314. * return 1 for *,
  15315. * return 2 for relative uri,
  15316. * return 3 for absolute uri without port,
  15317. * return 4 for absolute uri with port */
  15318. static int
  15319. get_uri_type(const char *uri)
  15320. {
  15321. int i;
  15322. const char *hostend, *portbegin;
  15323. char *portend;
  15324. unsigned long port;
  15325. /* According to the HTTP standard
  15326. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15327. * URI can be an asterisk (*) or should start with slash (relative uri),
  15328. * or it should start with the protocol (absolute uri). */
  15329. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15330. /* asterisk */
  15331. return 1;
  15332. }
  15333. /* Valid URIs according to RFC 3986
  15334. * (https://www.ietf.org/rfc/rfc3986.txt)
  15335. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15336. * and unreserved characters A-Z a-z 0-9 and -._~
  15337. * and % encoded symbols.
  15338. */
  15339. for (i = 0; uri[i] != 0; i++) {
  15340. if (uri[i] < 33) {
  15341. /* control characters and spaces are invalid */
  15342. return 0;
  15343. }
  15344. /* Allow everything else here (See #894) */
  15345. }
  15346. /* A relative uri starts with a / character */
  15347. if (uri[0] == '/') {
  15348. /* relative uri */
  15349. return 2;
  15350. }
  15351. /* It could be an absolute uri: */
  15352. /* This function only checks if the uri is valid, not if it is
  15353. * addressing the current server. So civetweb can also be used
  15354. * as a proxy server. */
  15355. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15356. if (mg_strncasecmp(uri,
  15357. abs_uri_protocols[i].proto,
  15358. abs_uri_protocols[i].proto_len)
  15359. == 0) {
  15360. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15361. if (!hostend) {
  15362. return 0;
  15363. }
  15364. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15365. if (!portbegin) {
  15366. return 3;
  15367. }
  15368. port = strtoul(portbegin + 1, &portend, 10);
  15369. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15370. return 0;
  15371. }
  15372. return 4;
  15373. }
  15374. }
  15375. return 0;
  15376. }
  15377. /* Return NULL or the relative uri at the current server */
  15378. static const char *
  15379. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15380. {
  15381. const char *server_domain;
  15382. size_t server_domain_len;
  15383. size_t request_domain_len = 0;
  15384. unsigned long port = 0;
  15385. int i, auth_domain_check_enabled;
  15386. const char *hostbegin = NULL;
  15387. const char *hostend = NULL;
  15388. const char *portbegin;
  15389. char *portend;
  15390. auth_domain_check_enabled =
  15391. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15392. /* DNS is case insensitive, so use case insensitive string compare here
  15393. */
  15394. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15395. if (mg_strncasecmp(uri,
  15396. abs_uri_protocols[i].proto,
  15397. abs_uri_protocols[i].proto_len)
  15398. == 0) {
  15399. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15400. hostend = strchr(hostbegin, '/');
  15401. if (!hostend) {
  15402. return 0;
  15403. }
  15404. portbegin = strchr(hostbegin, ':');
  15405. if ((!portbegin) || (portbegin > hostend)) {
  15406. port = abs_uri_protocols[i].default_port;
  15407. request_domain_len = (size_t)(hostend - hostbegin);
  15408. } else {
  15409. port = strtoul(portbegin + 1, &portend, 10);
  15410. if ((portend != hostend) || (port <= 0)
  15411. || !is_valid_port(port)) {
  15412. return 0;
  15413. }
  15414. request_domain_len = (size_t)(portbegin - hostbegin);
  15415. }
  15416. /* protocol found, port set */
  15417. break;
  15418. }
  15419. }
  15420. if (!port) {
  15421. /* port remains 0 if the protocol is not found */
  15422. return 0;
  15423. }
  15424. /* Check if the request is directed to a different server. */
  15425. /* First check if the port is the same. */
  15426. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15427. /* Request is directed to a different port */
  15428. return 0;
  15429. }
  15430. /* Finally check if the server corresponds to the authentication
  15431. * domain of the server (the server domain).
  15432. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15433. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15434. * but do not allow substrings (like
  15435. * http://notmydomain.com/path/file.ext
  15436. * or http://mydomain.com.fake/path/file.ext).
  15437. */
  15438. if (auth_domain_check_enabled) {
  15439. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15440. server_domain_len = strlen(server_domain);
  15441. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15442. return 0;
  15443. }
  15444. if ((request_domain_len == server_domain_len)
  15445. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15446. /* Request is directed to this server - full name match. */
  15447. } else {
  15448. if (request_domain_len < (server_domain_len + 2)) {
  15449. /* Request is directed to another server: The server name
  15450. * is longer than the request name.
  15451. * Drop this case here to avoid overflows in the
  15452. * following checks. */
  15453. return 0;
  15454. }
  15455. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15456. /* Request is directed to another server: It could be a
  15457. * substring
  15458. * like notmyserver.com */
  15459. return 0;
  15460. }
  15461. if (0
  15462. != memcmp(server_domain,
  15463. hostbegin + request_domain_len - server_domain_len,
  15464. server_domain_len)) {
  15465. /* Request is directed to another server:
  15466. * The server name is different. */
  15467. return 0;
  15468. }
  15469. }
  15470. }
  15471. return hostend;
  15472. }
  15473. static int
  15474. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15475. {
  15476. if (ebuf_len > 0) {
  15477. ebuf[0] = '\0';
  15478. }
  15479. *err = 0;
  15480. reset_per_request_attributes(conn);
  15481. if (!conn) {
  15482. mg_snprintf(conn,
  15483. NULL, /* No truncation check for ebuf */
  15484. ebuf,
  15485. ebuf_len,
  15486. "%s",
  15487. "Internal error");
  15488. *err = 500;
  15489. return 0;
  15490. }
  15491. /* Set the time the request was received. This value should be used for
  15492. * timeouts. */
  15493. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15494. conn->request_len =
  15495. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15496. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15497. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15498. mg_snprintf(conn,
  15499. NULL, /* No truncation check for ebuf */
  15500. ebuf,
  15501. ebuf_len,
  15502. "%s",
  15503. "Invalid message size");
  15504. *err = 500;
  15505. return 0;
  15506. }
  15507. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15508. mg_snprintf(conn,
  15509. NULL, /* No truncation check for ebuf */
  15510. ebuf,
  15511. ebuf_len,
  15512. "%s",
  15513. "Message too large");
  15514. *err = 413;
  15515. return 0;
  15516. }
  15517. if (conn->request_len <= 0) {
  15518. if (conn->data_len > 0) {
  15519. mg_snprintf(conn,
  15520. NULL, /* No truncation check for ebuf */
  15521. ebuf,
  15522. ebuf_len,
  15523. "%s",
  15524. "Malformed message");
  15525. *err = 400;
  15526. } else {
  15527. /* Server did not recv anything -> just close the connection */
  15528. conn->must_close = 1;
  15529. mg_snprintf(conn,
  15530. NULL, /* No truncation check for ebuf */
  15531. ebuf,
  15532. ebuf_len,
  15533. "%s",
  15534. "No data received");
  15535. *err = 0;
  15536. }
  15537. return 0;
  15538. }
  15539. return 1;
  15540. }
  15541. static int
  15542. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15543. {
  15544. const char *cl;
  15545. conn->connection_type =
  15546. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15547. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15548. return 0;
  15549. }
  15550. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15551. <= 0) {
  15552. mg_snprintf(conn,
  15553. NULL, /* No truncation check for ebuf */
  15554. ebuf,
  15555. ebuf_len,
  15556. "%s",
  15557. "Bad request");
  15558. *err = 400;
  15559. return 0;
  15560. }
  15561. /* Message is a valid request */
  15562. if (!switch_domain_context(conn)) {
  15563. mg_snprintf(conn,
  15564. NULL, /* No truncation check for ebuf */
  15565. ebuf,
  15566. ebuf_len,
  15567. "%s",
  15568. "Bad request: Host mismatch");
  15569. *err = 400;
  15570. return 0;
  15571. }
  15572. if (((cl = get_header(conn->request_info.http_headers,
  15573. conn->request_info.num_headers,
  15574. "Transfer-Encoding"))
  15575. != NULL)
  15576. && mg_strcasecmp(cl, "identity")) {
  15577. if (mg_strcasecmp(cl, "chunked")) {
  15578. mg_snprintf(conn,
  15579. NULL, /* No truncation check for ebuf */
  15580. ebuf,
  15581. ebuf_len,
  15582. "%s",
  15583. "Bad request");
  15584. *err = 400;
  15585. return 0;
  15586. }
  15587. conn->is_chunked = 1;
  15588. conn->content_len = 0; /* not yet read */
  15589. } else if ((cl = get_header(conn->request_info.http_headers,
  15590. conn->request_info.num_headers,
  15591. "Content-Length"))
  15592. != NULL) {
  15593. /* Request has content length set */
  15594. char *endptr = NULL;
  15595. conn->content_len = strtoll(cl, &endptr, 10);
  15596. if ((endptr == cl) || (conn->content_len < 0)) {
  15597. mg_snprintf(conn,
  15598. NULL, /* No truncation check for ebuf */
  15599. ebuf,
  15600. ebuf_len,
  15601. "%s",
  15602. "Bad request");
  15603. *err = 411;
  15604. return 0;
  15605. }
  15606. /* Publish the content length back to the request info. */
  15607. conn->request_info.content_length = conn->content_len;
  15608. } else {
  15609. /* There is no exception, see RFC7230. */
  15610. conn->content_len = 0;
  15611. }
  15612. return 1;
  15613. }
  15614. /* conn is assumed to be valid in this internal function */
  15615. static int
  15616. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15617. {
  15618. const char *cl;
  15619. conn->connection_type =
  15620. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15621. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15622. return 0;
  15623. }
  15624. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15625. <= 0) {
  15626. mg_snprintf(conn,
  15627. NULL, /* No truncation check for ebuf */
  15628. ebuf,
  15629. ebuf_len,
  15630. "%s",
  15631. "Bad response");
  15632. *err = 400;
  15633. return 0;
  15634. }
  15635. /* Message is a valid response */
  15636. if (((cl = get_header(conn->response_info.http_headers,
  15637. conn->response_info.num_headers,
  15638. "Transfer-Encoding"))
  15639. != NULL)
  15640. && mg_strcasecmp(cl, "identity")) {
  15641. if (mg_strcasecmp(cl, "chunked")) {
  15642. mg_snprintf(conn,
  15643. NULL, /* No truncation check for ebuf */
  15644. ebuf,
  15645. ebuf_len,
  15646. "%s",
  15647. "Bad request");
  15648. *err = 400;
  15649. return 0;
  15650. }
  15651. conn->is_chunked = 1;
  15652. conn->content_len = 0; /* not yet read */
  15653. } else if ((cl = get_header(conn->response_info.http_headers,
  15654. conn->response_info.num_headers,
  15655. "Content-Length"))
  15656. != NULL) {
  15657. char *endptr = NULL;
  15658. conn->content_len = strtoll(cl, &endptr, 10);
  15659. if ((endptr == cl) || (conn->content_len < 0)) {
  15660. mg_snprintf(conn,
  15661. NULL, /* No truncation check for ebuf */
  15662. ebuf,
  15663. ebuf_len,
  15664. "%s",
  15665. "Bad request");
  15666. *err = 411;
  15667. return 0;
  15668. }
  15669. /* Publish the content length back to the response info. */
  15670. conn->response_info.content_length = conn->content_len;
  15671. /* TODO: check if it is still used in response_info */
  15672. conn->request_info.content_length = conn->content_len;
  15673. /* TODO: we should also consider HEAD method */
  15674. if (conn->response_info.status_code == 304) {
  15675. conn->content_len = 0;
  15676. }
  15677. } else {
  15678. /* TODO: we should also consider HEAD method */
  15679. if (((conn->response_info.status_code >= 100)
  15680. && (conn->response_info.status_code <= 199))
  15681. || (conn->response_info.status_code == 204)
  15682. || (conn->response_info.status_code == 304)) {
  15683. conn->content_len = 0;
  15684. } else {
  15685. conn->content_len = -1; /* unknown content length */
  15686. }
  15687. }
  15688. return 1;
  15689. }
  15690. int
  15691. mg_get_response(struct mg_connection *conn,
  15692. char *ebuf,
  15693. size_t ebuf_len,
  15694. int timeout)
  15695. {
  15696. int err, ret;
  15697. char txt[32]; /* will not overflow */
  15698. char *save_timeout;
  15699. char *new_timeout;
  15700. if (ebuf_len > 0) {
  15701. ebuf[0] = '\0';
  15702. }
  15703. if (!conn) {
  15704. mg_snprintf(conn,
  15705. NULL, /* No truncation check for ebuf */
  15706. ebuf,
  15707. ebuf_len,
  15708. "%s",
  15709. "Parameter error");
  15710. return -1;
  15711. }
  15712. /* Reset the previous responses */
  15713. conn->data_len = 0;
  15714. /* Implementation of API function for HTTP clients */
  15715. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15716. if (timeout >= 0) {
  15717. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15718. new_timeout = txt;
  15719. } else {
  15720. new_timeout = NULL;
  15721. }
  15722. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15723. ret = get_response(conn, ebuf, ebuf_len, &err);
  15724. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15725. #if defined(MG_LEGACY_INTERFACE)
  15726. /* TODO: 1) uri is deprecated;
  15727. * 2) here, ri.uri is the http response code */
  15728. conn->request_info.uri = conn->request_info.request_uri;
  15729. #endif
  15730. conn->request_info.local_uri = conn->request_info.request_uri;
  15731. /* TODO (mid): Define proper return values - maybe return length?
  15732. * For the first test use <0 for error and >0 for OK */
  15733. return (ret == 0) ? -1 : +1;
  15734. }
  15735. struct mg_connection *
  15736. mg_download(const char *host,
  15737. int port,
  15738. int use_ssl,
  15739. char *ebuf,
  15740. size_t ebuf_len,
  15741. const char *fmt,
  15742. ...)
  15743. {
  15744. struct mg_connection *conn;
  15745. va_list ap;
  15746. int i;
  15747. int reqerr;
  15748. if (ebuf_len > 0) {
  15749. ebuf[0] = '\0';
  15750. }
  15751. va_start(ap, fmt);
  15752. /* open a connection */
  15753. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15754. if (conn != NULL) {
  15755. i = mg_vprintf(conn, fmt, ap);
  15756. if (i <= 0) {
  15757. mg_snprintf(conn,
  15758. NULL, /* No truncation check for ebuf */
  15759. ebuf,
  15760. ebuf_len,
  15761. "%s",
  15762. "Error sending request");
  15763. } else {
  15764. /* make sure the buffer is clear */
  15765. conn->data_len = 0;
  15766. get_response(conn, ebuf, ebuf_len, &reqerr);
  15767. #if defined(MG_LEGACY_INTERFACE)
  15768. /* TODO: 1) uri is deprecated;
  15769. * 2) here, ri.uri is the http response code */
  15770. conn->request_info.uri = conn->request_info.request_uri;
  15771. #endif
  15772. conn->request_info.local_uri = conn->request_info.request_uri;
  15773. }
  15774. }
  15775. /* if an error occurred, close the connection */
  15776. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15777. mg_close_connection(conn);
  15778. conn = NULL;
  15779. }
  15780. va_end(ap);
  15781. return conn;
  15782. }
  15783. struct websocket_client_thread_data {
  15784. struct mg_connection *conn;
  15785. mg_websocket_data_handler data_handler;
  15786. mg_websocket_close_handler close_handler;
  15787. void *callback_data;
  15788. };
  15789. #if defined(USE_WEBSOCKET)
  15790. #if defined(_WIN32)
  15791. static unsigned __stdcall websocket_client_thread(void *data)
  15792. #else
  15793. static void *
  15794. websocket_client_thread(void *data)
  15795. #endif
  15796. {
  15797. struct websocket_client_thread_data *cdata =
  15798. (struct websocket_client_thread_data *)data;
  15799. void *user_thread_ptr = NULL;
  15800. #if !defined(_WIN32)
  15801. struct sigaction sa;
  15802. /* Ignore SIGPIPE */
  15803. memset(&sa, 0, sizeof(sa));
  15804. sa.sa_handler = SIG_IGN;
  15805. sigaction(SIGPIPE, &sa, NULL);
  15806. #endif
  15807. mg_set_thread_name("ws-clnt");
  15808. if (cdata->conn->phys_ctx) {
  15809. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15810. /* 3 indicates a websocket client thread */
  15811. /* TODO: check if conn->phys_ctx can be set */
  15812. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15813. cdata->conn->phys_ctx, 3);
  15814. }
  15815. }
  15816. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15817. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15818. if (cdata->close_handler != NULL) {
  15819. cdata->close_handler(cdata->conn, cdata->callback_data);
  15820. }
  15821. /* The websocket_client context has only this thread. If it runs out,
  15822. set the stop_flag to 2 (= "stopped"). */
  15823. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15824. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15825. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15826. 3,
  15827. user_thread_ptr);
  15828. }
  15829. mg_free((void *)cdata);
  15830. #if defined(_WIN32)
  15831. return 0;
  15832. #else
  15833. return NULL;
  15834. #endif
  15835. }
  15836. #endif
  15837. static struct mg_connection *
  15838. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15839. int use_ssl,
  15840. char *error_buffer,
  15841. size_t error_buffer_size,
  15842. const char *path,
  15843. const char *origin,
  15844. const char *extensions,
  15845. mg_websocket_data_handler data_func,
  15846. mg_websocket_close_handler close_func,
  15847. void *user_data)
  15848. {
  15849. struct mg_connection *conn = NULL;
  15850. #if defined(USE_WEBSOCKET)
  15851. struct websocket_client_thread_data *thread_data;
  15852. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15853. const char *host = client_options->host;
  15854. int i;
  15855. #if defined(__clang__)
  15856. #pragma clang diagnostic push
  15857. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15858. #endif
  15859. /* Establish the client connection and request upgrade */
  15860. conn = mg_connect_client_impl(client_options,
  15861. use_ssl,
  15862. error_buffer,
  15863. error_buffer_size);
  15864. /* Connection object will be null if something goes wrong */
  15865. if (conn == NULL) {
  15866. /* error_buffer should be already filled ... */
  15867. if (!error_buffer[0]) {
  15868. /* ... if not add an error message */
  15869. mg_snprintf(conn,
  15870. NULL, /* No truncation check for ebuf */
  15871. error_buffer,
  15872. error_buffer_size,
  15873. "Unexpected error");
  15874. }
  15875. return NULL;
  15876. }
  15877. if (origin != NULL) {
  15878. if (extensions != NULL) {
  15879. i = mg_printf(conn,
  15880. "GET %s HTTP/1.1\r\n"
  15881. "Host: %s\r\n"
  15882. "Upgrade: websocket\r\n"
  15883. "Connection: Upgrade\r\n"
  15884. "Sec-WebSocket-Key: %s\r\n"
  15885. "Sec-WebSocket-Version: 13\r\n"
  15886. "Sec-WebSocket-Extensions: %s\r\n"
  15887. "Origin: %s\r\n"
  15888. "\r\n",
  15889. path,
  15890. host,
  15891. magic,
  15892. extensions,
  15893. origin);
  15894. } else {
  15895. i = mg_printf(conn,
  15896. "GET %s HTTP/1.1\r\n"
  15897. "Host: %s\r\n"
  15898. "Upgrade: websocket\r\n"
  15899. "Connection: Upgrade\r\n"
  15900. "Sec-WebSocket-Key: %s\r\n"
  15901. "Sec-WebSocket-Version: 13\r\n"
  15902. "Origin: %s\r\n"
  15903. "\r\n",
  15904. path,
  15905. host,
  15906. magic,
  15907. origin);
  15908. }
  15909. } else {
  15910. if (extensions != NULL) {
  15911. i = mg_printf(conn,
  15912. "GET %s HTTP/1.1\r\n"
  15913. "Host: %s\r\n"
  15914. "Upgrade: websocket\r\n"
  15915. "Connection: Upgrade\r\n"
  15916. "Sec-WebSocket-Key: %s\r\n"
  15917. "Sec-WebSocket-Version: 13\r\n"
  15918. "Sec-WebSocket-Extensions: %s\r\n"
  15919. "\r\n",
  15920. path,
  15921. host,
  15922. magic,
  15923. extensions);
  15924. } else {
  15925. i = mg_printf(conn,
  15926. "GET %s HTTP/1.1\r\n"
  15927. "Host: %s\r\n"
  15928. "Upgrade: websocket\r\n"
  15929. "Connection: Upgrade\r\n"
  15930. "Sec-WebSocket-Key: %s\r\n"
  15931. "Sec-WebSocket-Version: 13\r\n"
  15932. "\r\n",
  15933. path,
  15934. host,
  15935. magic);
  15936. }
  15937. }
  15938. if (i <= 0) {
  15939. mg_snprintf(conn,
  15940. NULL, /* No truncation check for ebuf */
  15941. error_buffer,
  15942. error_buffer_size,
  15943. "%s",
  15944. "Error sending request");
  15945. mg_close_connection(conn);
  15946. return NULL;
  15947. }
  15948. conn->data_len = 0;
  15949. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15950. mg_close_connection(conn);
  15951. return NULL;
  15952. }
  15953. conn->request_info.local_uri = conn->request_info.request_uri;
  15954. #if defined(__clang__)
  15955. #pragma clang diagnostic pop
  15956. #endif
  15957. if (conn->response_info.status_code != 101) {
  15958. /* We sent an "upgrade" request. For a correct websocket
  15959. * protocol handshake, we expect a "101 Continue" response.
  15960. * Otherwise it is a protocol violation. Maybe the HTTP
  15961. * Server does not know websockets. */
  15962. if (!*error_buffer) {
  15963. /* set an error, if not yet set */
  15964. mg_snprintf(conn,
  15965. NULL, /* No truncation check for ebuf */
  15966. error_buffer,
  15967. error_buffer_size,
  15968. "Unexpected server reply");
  15969. }
  15970. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15971. mg_close_connection(conn);
  15972. return NULL;
  15973. }
  15974. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15975. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15976. if (!thread_data) {
  15977. DEBUG_TRACE("%s\r\n", "Out of memory");
  15978. mg_close_connection(conn);
  15979. return NULL;
  15980. }
  15981. thread_data->conn = conn;
  15982. thread_data->data_handler = data_func;
  15983. thread_data->close_handler = close_func;
  15984. thread_data->callback_data = user_data;
  15985. conn->phys_ctx->worker_threadids =
  15986. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15987. if (!conn->phys_ctx->worker_threadids) {
  15988. DEBUG_TRACE("%s\r\n", "Out of memory");
  15989. mg_free(thread_data);
  15990. mg_close_connection(conn);
  15991. return NULL;
  15992. }
  15993. /* Now upgrade to ws/wss client context */
  15994. conn->phys_ctx->user_data = user_data;
  15995. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15996. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15997. /* Start a thread to read the websocket client connection
  15998. * This thread will automatically stop when mg_disconnect is
  15999. * called on the client connection */
  16000. if (mg_start_thread_with_id(websocket_client_thread,
  16001. thread_data,
  16002. conn->phys_ctx->worker_threadids)
  16003. != 0) {
  16004. conn->phys_ctx->cfg_worker_threads = 0;
  16005. mg_free(thread_data);
  16006. mg_close_connection(conn);
  16007. conn = NULL;
  16008. DEBUG_TRACE("%s",
  16009. "Websocket client connect thread could not be started\r\n");
  16010. }
  16011. #else
  16012. /* Appease "unused parameter" warnings */
  16013. (void)client_options;
  16014. (void)use_ssl;
  16015. (void)error_buffer;
  16016. (void)error_buffer_size;
  16017. (void)path;
  16018. (void)origin;
  16019. (void)user_data;
  16020. (void)data_func;
  16021. (void)close_func;
  16022. #endif
  16023. return conn;
  16024. }
  16025. struct mg_connection *
  16026. mg_connect_websocket_client(const char *host,
  16027. int port,
  16028. int use_ssl,
  16029. char *error_buffer,
  16030. size_t error_buffer_size,
  16031. const char *path,
  16032. const char *origin,
  16033. mg_websocket_data_handler data_func,
  16034. mg_websocket_close_handler close_func,
  16035. void *user_data)
  16036. {
  16037. struct mg_client_options client_options;
  16038. memset(&client_options, 0, sizeof(client_options));
  16039. client_options.host = host;
  16040. client_options.port = port;
  16041. return mg_connect_websocket_client_impl(&client_options,
  16042. use_ssl,
  16043. error_buffer,
  16044. error_buffer_size,
  16045. path,
  16046. origin,
  16047. NULL,
  16048. data_func,
  16049. close_func,
  16050. user_data);
  16051. }
  16052. struct mg_connection *
  16053. mg_connect_websocket_client_secure(
  16054. const struct mg_client_options *client_options,
  16055. char *error_buffer,
  16056. size_t error_buffer_size,
  16057. const char *path,
  16058. const char *origin,
  16059. mg_websocket_data_handler data_func,
  16060. mg_websocket_close_handler close_func,
  16061. void *user_data)
  16062. {
  16063. if (!client_options) {
  16064. return NULL;
  16065. }
  16066. return mg_connect_websocket_client_impl(client_options,
  16067. 1,
  16068. error_buffer,
  16069. error_buffer_size,
  16070. path,
  16071. origin,
  16072. NULL,
  16073. data_func,
  16074. close_func,
  16075. user_data);
  16076. }
  16077. struct mg_connection *
  16078. mg_connect_websocket_client_extensions(const char *host,
  16079. int port,
  16080. int use_ssl,
  16081. char *error_buffer,
  16082. size_t error_buffer_size,
  16083. const char *path,
  16084. const char *origin,
  16085. const char *extensions,
  16086. mg_websocket_data_handler data_func,
  16087. mg_websocket_close_handler close_func,
  16088. void *user_data)
  16089. {
  16090. struct mg_client_options client_options;
  16091. memset(&client_options, 0, sizeof(client_options));
  16092. client_options.host = host;
  16093. client_options.port = port;
  16094. return mg_connect_websocket_client_impl(&client_options,
  16095. use_ssl,
  16096. error_buffer,
  16097. error_buffer_size,
  16098. path,
  16099. origin,
  16100. extensions,
  16101. data_func,
  16102. close_func,
  16103. user_data);
  16104. }
  16105. struct mg_connection *
  16106. mg_connect_websocket_client_secure_extensions(
  16107. const struct mg_client_options *client_options,
  16108. char *error_buffer,
  16109. size_t error_buffer_size,
  16110. const char *path,
  16111. const char *origin,
  16112. const char *extensions,
  16113. mg_websocket_data_handler data_func,
  16114. mg_websocket_close_handler close_func,
  16115. void *user_data)
  16116. {
  16117. if (!client_options) {
  16118. return NULL;
  16119. }
  16120. return mg_connect_websocket_client_impl(client_options,
  16121. 1,
  16122. error_buffer,
  16123. error_buffer_size,
  16124. path,
  16125. origin,
  16126. extensions,
  16127. data_func,
  16128. close_func,
  16129. user_data);
  16130. }
  16131. /* Prepare connection data structure */
  16132. static void
  16133. init_connection(struct mg_connection *conn)
  16134. {
  16135. /* Is keep alive allowed by the server */
  16136. int keep_alive_enabled =
  16137. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16138. if (!keep_alive_enabled) {
  16139. conn->must_close = 1;
  16140. }
  16141. /* Important: on new connection, reset the receiving buffer. Credit
  16142. * goes to crule42. */
  16143. conn->data_len = 0;
  16144. conn->handled_requests = 0;
  16145. conn->connection_type = CONNECTION_TYPE_INVALID;
  16146. mg_set_user_connection_data(conn, NULL);
  16147. #if defined(USE_SERVER_STATS)
  16148. conn->conn_state = 2; /* init */
  16149. #endif
  16150. /* call the init_connection callback if assigned */
  16151. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16152. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16153. void *conn_data = NULL;
  16154. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16155. mg_set_user_connection_data(conn, conn_data);
  16156. }
  16157. }
  16158. }
  16159. /* Process a connection - may handle multiple requests
  16160. * using the same connection.
  16161. * Must be called with a valid connection (conn and
  16162. * conn->phys_ctx must be valid).
  16163. */
  16164. static void
  16165. process_new_connection(struct mg_connection *conn)
  16166. {
  16167. struct mg_request_info *ri = &conn->request_info;
  16168. int keep_alive, discard_len;
  16169. char ebuf[100];
  16170. const char *hostend;
  16171. int reqerr, uri_type;
  16172. #if defined(USE_SERVER_STATS)
  16173. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16174. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16175. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16176. #endif
  16177. DEBUG_TRACE("Start processing connection from %s",
  16178. conn->request_info.remote_addr);
  16179. /* Loop over multiple requests sent using the same connection
  16180. * (while "keep alive"). */
  16181. do {
  16182. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16183. conn->handled_requests + 1);
  16184. #if defined(USE_SERVER_STATS)
  16185. conn->conn_state = 3; /* ready */
  16186. #endif
  16187. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16188. /* The request sent by the client could not be understood by
  16189. * the server, or it was incomplete or a timeout. Send an
  16190. * error message and close the connection. */
  16191. if (reqerr > 0) {
  16192. DEBUG_ASSERT(ebuf[0] != '\0');
  16193. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16194. }
  16195. } else if (strcmp(ri->http_version, "1.0")
  16196. && strcmp(ri->http_version, "1.1")) {
  16197. /* HTTP/2 is not allowed here */
  16198. mg_snprintf(conn,
  16199. NULL, /* No truncation check for ebuf */
  16200. ebuf,
  16201. sizeof(ebuf),
  16202. "Bad HTTP version: [%s]",
  16203. ri->http_version);
  16204. mg_send_http_error(conn, 505, "%s", ebuf);
  16205. }
  16206. if (ebuf[0] == '\0') {
  16207. uri_type = get_uri_type(conn->request_info.request_uri);
  16208. switch (uri_type) {
  16209. case 1:
  16210. /* Asterisk */
  16211. conn->request_info.local_uri = 0;
  16212. /* TODO: Deal with '*'. */
  16213. break;
  16214. case 2:
  16215. /* relative uri */
  16216. conn->request_info.local_uri = conn->request_info.request_uri;
  16217. break;
  16218. case 3:
  16219. case 4:
  16220. /* absolute uri (with/without port) */
  16221. hostend = get_rel_url_at_current_server(
  16222. conn->request_info.request_uri, conn);
  16223. if (hostend) {
  16224. conn->request_info.local_uri = hostend;
  16225. } else {
  16226. conn->request_info.local_uri = NULL;
  16227. }
  16228. break;
  16229. default:
  16230. mg_snprintf(conn,
  16231. NULL, /* No truncation check for ebuf */
  16232. ebuf,
  16233. sizeof(ebuf),
  16234. "Invalid URI");
  16235. mg_send_http_error(conn, 400, "%s", ebuf);
  16236. conn->request_info.local_uri = NULL;
  16237. break;
  16238. }
  16239. #if defined(MG_LEGACY_INTERFACE)
  16240. /* Legacy before split into local_uri and request_uri */
  16241. conn->request_info.uri = conn->request_info.local_uri;
  16242. #endif
  16243. }
  16244. if (ebuf[0] != '\0') {
  16245. conn->protocol_type = -1;
  16246. } else {
  16247. /* HTTP/1 allows protocol upgrade */
  16248. conn->protocol_type = should_switch_to_protocol(conn);
  16249. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16250. /* This will occur, if a HTTP/1.1 request should be upgraded
  16251. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16252. * Since most (all?) major browsers only support HTTP/2 using
  16253. * ALPN, this is hard to test and very low priority.
  16254. * Deactivate it (at least for now).
  16255. */
  16256. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16257. }
  16258. }
  16259. DEBUG_TRACE("http: %s, error: %s",
  16260. (ri->http_version ? ri->http_version : "none"),
  16261. (ebuf[0] ? ebuf : "none"));
  16262. if (ebuf[0] == '\0') {
  16263. if (conn->request_info.local_uri) {
  16264. /* handle request to local server */
  16265. #if defined(USE_SERVER_STATS)
  16266. conn->conn_state = 4; /* processing */
  16267. #endif
  16268. handle_request(conn);
  16269. #if defined(USE_SERVER_STATS)
  16270. conn->conn_state = 5; /* processed */
  16271. mg_atomic_add64(&(conn->phys_ctx->total_data_read),
  16272. conn->consumed_content);
  16273. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  16274. conn->num_bytes_sent);
  16275. #endif
  16276. DEBUG_TRACE("%s", "handle_request done");
  16277. if (conn->phys_ctx->callbacks.end_request != NULL) {
  16278. conn->phys_ctx->callbacks.end_request(conn,
  16279. conn->status_code);
  16280. DEBUG_TRACE("%s", "end_request callback done");
  16281. }
  16282. log_access(conn);
  16283. } else {
  16284. /* TODO: handle non-local request (PROXY) */
  16285. conn->must_close = 1;
  16286. }
  16287. } else {
  16288. conn->must_close = 1;
  16289. }
  16290. /* Response complete. Free header buffer */
  16291. free_buffered_response_header_list(conn);
  16292. if (ri->remote_user != NULL) {
  16293. mg_free((void *)ri->remote_user);
  16294. /* Important! When having connections with and without auth
  16295. * would cause double free and then crash */
  16296. ri->remote_user = NULL;
  16297. }
  16298. /* NOTE(lsm): order is important here. should_keep_alive() call
  16299. * is using parsed request, which will be invalid after
  16300. * memmove's below.
  16301. * Therefore, memorize should_keep_alive() result now for later
  16302. * use in loop exit condition. */
  16303. /* Enable it only if this request is completely discardable. */
  16304. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16305. && should_keep_alive(conn) && (conn->content_len >= 0)
  16306. && (conn->request_len > 0)
  16307. && ((conn->is_chunked == 4)
  16308. || (!conn->is_chunked
  16309. && ((conn->consumed_content == conn->content_len)
  16310. || ((conn->request_len + conn->content_len)
  16311. <= conn->data_len))))
  16312. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16313. if (keep_alive) {
  16314. /* Discard all buffered data for this request */
  16315. discard_len =
  16316. ((conn->request_len + conn->content_len) < conn->data_len)
  16317. ? (int)(conn->request_len + conn->content_len)
  16318. : conn->data_len;
  16319. conn->data_len -= discard_len;
  16320. if (conn->data_len > 0) {
  16321. DEBUG_TRACE("discard_len = %d", discard_len);
  16322. memmove(conn->buf,
  16323. conn->buf + discard_len,
  16324. (size_t)conn->data_len);
  16325. }
  16326. }
  16327. DEBUG_ASSERT(conn->data_len >= 0);
  16328. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16329. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16330. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16331. (long int)conn->data_len,
  16332. (long int)conn->buf_size);
  16333. break;
  16334. }
  16335. conn->handled_requests++;
  16336. } while (keep_alive);
  16337. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16338. conn->request_info.remote_addr,
  16339. difftime(time(NULL), conn->conn_birth_time));
  16340. close_connection(conn);
  16341. #if defined(USE_SERVER_STATS)
  16342. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16343. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16344. #endif
  16345. }
  16346. #if defined(ALTERNATIVE_QUEUE)
  16347. static void
  16348. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16349. {
  16350. unsigned int i;
  16351. while (!ctx->stop_flag) {
  16352. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16353. /* find a free worker slot and signal it */
  16354. if (ctx->client_socks[i].in_use == 2) {
  16355. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16356. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16357. ctx->client_socks[i] = *sp;
  16358. ctx->client_socks[i].in_use = 1;
  16359. /* socket has been moved to the consumer */
  16360. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16361. (void)event_signal(ctx->client_wait_events[i]);
  16362. return;
  16363. }
  16364. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16365. }
  16366. }
  16367. /* queue is full */
  16368. mg_sleep(1);
  16369. }
  16370. /* must consume */
  16371. set_blocking_mode(sp->sock);
  16372. closesocket(sp->sock);
  16373. }
  16374. static int
  16375. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16376. {
  16377. DEBUG_TRACE("%s", "going idle");
  16378. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16379. ctx->client_socks[thread_index].in_use = 2;
  16380. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16381. event_wait(ctx->client_wait_events[thread_index]);
  16382. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16383. *sp = ctx->client_socks[thread_index];
  16384. if (ctx->stop_flag) {
  16385. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16386. if (sp->in_use == 1) {
  16387. /* must consume */
  16388. set_blocking_mode(sp->sock);
  16389. closesocket(sp->sock);
  16390. }
  16391. return 0;
  16392. }
  16393. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16394. if (sp->in_use == 1) {
  16395. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16396. return 1;
  16397. }
  16398. /* must not reach here */
  16399. DEBUG_ASSERT(0);
  16400. return 0;
  16401. }
  16402. #else /* ALTERNATIVE_QUEUE */
  16403. /* Worker threads take accepted socket from the queue */
  16404. static int
  16405. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16406. {
  16407. (void)thread_index;
  16408. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16409. DEBUG_TRACE("%s", "going idle");
  16410. /* If the queue is empty, wait. We're idle at this point. */
  16411. while ((ctx->sq_head == ctx->sq_tail)
  16412. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16413. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16414. }
  16415. /* If we're stopping, sq_head may be equal to sq_tail. */
  16416. if (ctx->sq_head > ctx->sq_tail) {
  16417. /* Copy socket from the queue and increment tail */
  16418. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16419. ctx->sq_tail++;
  16420. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16421. /* Wrap pointers if needed */
  16422. while (ctx->sq_tail > ctx->sq_size) {
  16423. ctx->sq_tail -= ctx->sq_size;
  16424. ctx->sq_head -= ctx->sq_size;
  16425. }
  16426. }
  16427. (void)pthread_cond_signal(&ctx->sq_empty);
  16428. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16429. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16430. }
  16431. /* Master thread adds accepted socket to a queue */
  16432. static void
  16433. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16434. {
  16435. int queue_filled;
  16436. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16437. queue_filled = ctx->sq_head - ctx->sq_tail;
  16438. /* If the queue is full, wait */
  16439. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16440. && (queue_filled >= ctx->sq_size)) {
  16441. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16442. #if defined(USE_SERVER_STATS)
  16443. if (queue_filled > ctx->sq_max_fill) {
  16444. ctx->sq_max_fill = queue_filled;
  16445. }
  16446. #endif
  16447. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16448. ctx->sq_blocked = 0; /* Not blocked now */
  16449. queue_filled = ctx->sq_head - ctx->sq_tail;
  16450. }
  16451. if (queue_filled < ctx->sq_size) {
  16452. /* Copy socket to the queue and increment head */
  16453. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16454. ctx->sq_head++;
  16455. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16456. }
  16457. queue_filled = ctx->sq_head - ctx->sq_tail;
  16458. #if defined(USE_SERVER_STATS)
  16459. if (queue_filled > ctx->sq_max_fill) {
  16460. ctx->sq_max_fill = queue_filled;
  16461. }
  16462. #endif
  16463. (void)pthread_cond_signal(&ctx->sq_full);
  16464. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16465. }
  16466. #endif /* ALTERNATIVE_QUEUE */
  16467. static void
  16468. worker_thread_run(struct mg_connection *conn)
  16469. {
  16470. struct mg_context *ctx = conn->phys_ctx;
  16471. int thread_index;
  16472. struct mg_workerTLS tls;
  16473. mg_set_thread_name("worker");
  16474. tls.is_master = 0;
  16475. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16476. #if defined(_WIN32)
  16477. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16478. #endif
  16479. /* Initialize thread local storage before calling any callback */
  16480. pthread_setspecific(sTlsKey, &tls);
  16481. /* Check if there is a user callback */
  16482. if (ctx->callbacks.init_thread) {
  16483. /* call init_thread for a worker thread (type 1), and store the
  16484. * return value */
  16485. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16486. } else {
  16487. /* No callback: set user pointer to NULL */
  16488. tls.user_ptr = NULL;
  16489. }
  16490. /* Connection structure has been pre-allocated */
  16491. thread_index = (int)(conn - ctx->worker_connections);
  16492. if ((thread_index < 0)
  16493. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16494. mg_cry_ctx_internal(ctx,
  16495. "Internal error: Invalid worker index %i",
  16496. thread_index);
  16497. return;
  16498. }
  16499. /* Request buffers are not pre-allocated. They are private to the
  16500. * request and do not contain any state information that might be
  16501. * of interest to anyone observing a server status. */
  16502. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16503. if (conn->buf == NULL) {
  16504. mg_cry_ctx_internal(
  16505. ctx,
  16506. "Out of memory: Cannot allocate buffer for worker %i",
  16507. thread_index);
  16508. return;
  16509. }
  16510. conn->buf_size = (int)ctx->max_request_size;
  16511. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16512. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16513. conn->request_info.user_data = ctx->user_data;
  16514. /* Allocate a mutex for this connection to allow communication both
  16515. * within the request handler and from elsewhere in the application
  16516. */
  16517. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16518. mg_free(conn->buf);
  16519. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16520. return;
  16521. }
  16522. #if defined(USE_SERVER_STATS)
  16523. conn->conn_state = 1; /* not consumed */
  16524. #endif
  16525. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16526. * signal sq_empty condvar to wake up the master waiting in
  16527. * produce_socket() */
  16528. while (consume_socket(ctx, &conn->client, thread_index)) {
  16529. /* New connections must start with new protocol negotiation */
  16530. tls.alpn_proto = NULL;
  16531. #if defined(USE_SERVER_STATS)
  16532. conn->conn_close_time = 0;
  16533. #endif
  16534. conn->conn_birth_time = time(NULL);
  16535. /* Fill in IP, port info early so even if SSL setup below fails,
  16536. * error handler would have the corresponding info.
  16537. * Thanks to Johannes Winkelmann for the patch.
  16538. */
  16539. conn->request_info.remote_port =
  16540. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16541. conn->request_info.server_port =
  16542. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16543. sockaddr_to_string(conn->request_info.remote_addr,
  16544. sizeof(conn->request_info.remote_addr),
  16545. &conn->client.rsa);
  16546. DEBUG_TRACE("Start processing connection from %s",
  16547. conn->request_info.remote_addr);
  16548. conn->request_info.is_ssl = conn->client.is_ssl;
  16549. if (conn->client.is_ssl) {
  16550. #if !defined(NO_SSL)
  16551. /* HTTPS connection */
  16552. if (sslize(conn, SSL_accept, NULL)) {
  16553. /* conn->dom_ctx is set in get_request */
  16554. /* Get SSL client certificate information (if set) */
  16555. struct mg_client_cert client_cert;
  16556. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16557. conn->request_info.client_cert = &client_cert;
  16558. }
  16559. /* process HTTPS connection */
  16560. #if defined(USE_HTTP2)
  16561. if ((tls.alpn_proto != NULL)
  16562. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16563. /* process HTTPS/2 connection */
  16564. init_connection(conn);
  16565. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16566. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16567. conn->content_len =
  16568. -1; /* content length is not predefined */
  16569. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16570. process_new_http2_connection(conn);
  16571. } else
  16572. #endif
  16573. {
  16574. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16575. init_connection(conn);
  16576. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16577. /* Start with HTTP, WS will be an "upgrade" request later */
  16578. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16579. process_new_connection(conn);
  16580. }
  16581. /* Free client certificate info */
  16582. if (conn->request_info.client_cert) {
  16583. mg_free((void *)(conn->request_info.client_cert->subject));
  16584. mg_free((void *)(conn->request_info.client_cert->issuer));
  16585. mg_free((void *)(conn->request_info.client_cert->serial));
  16586. mg_free((void *)(conn->request_info.client_cert->finger));
  16587. /* Free certificate memory */
  16588. X509_free(
  16589. (X509 *)conn->request_info.client_cert->peer_cert);
  16590. conn->request_info.client_cert->peer_cert = 0;
  16591. conn->request_info.client_cert->subject = 0;
  16592. conn->request_info.client_cert->issuer = 0;
  16593. conn->request_info.client_cert->serial = 0;
  16594. conn->request_info.client_cert->finger = 0;
  16595. conn->request_info.client_cert = 0;
  16596. }
  16597. } else {
  16598. /* make sure the connection is cleaned up on SSL failure */
  16599. close_connection(conn);
  16600. }
  16601. #endif
  16602. } else {
  16603. /* process HTTP connection */
  16604. init_connection(conn);
  16605. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16606. /* Start with HTTP, WS will be an "upgrade" request later */
  16607. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16608. process_new_connection(conn);
  16609. }
  16610. DEBUG_TRACE("%s", "Connection closed");
  16611. #if defined(USE_SERVER_STATS)
  16612. conn->conn_close_time = time(NULL);
  16613. #endif
  16614. }
  16615. /* Call exit thread user callback */
  16616. if (ctx->callbacks.exit_thread) {
  16617. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16618. }
  16619. /* delete thread local storage objects */
  16620. pthread_setspecific(sTlsKey, NULL);
  16621. #if defined(_WIN32)
  16622. CloseHandle(tls.pthread_cond_helper_mutex);
  16623. #endif
  16624. pthread_mutex_destroy(&conn->mutex);
  16625. /* Free the request buffer. */
  16626. conn->buf_size = 0;
  16627. mg_free(conn->buf);
  16628. conn->buf = NULL;
  16629. #if defined(USE_SERVER_STATS)
  16630. conn->conn_state = 9; /* done */
  16631. #endif
  16632. DEBUG_TRACE("%s", "exiting");
  16633. }
  16634. /* Threads have different return types on Windows and Unix. */
  16635. #if defined(_WIN32)
  16636. static unsigned __stdcall worker_thread(void *thread_func_param)
  16637. {
  16638. worker_thread_run((struct mg_connection *)thread_func_param);
  16639. return 0;
  16640. }
  16641. #else
  16642. static void *
  16643. worker_thread(void *thread_func_param)
  16644. {
  16645. #if !defined(__ZEPHYR__)
  16646. struct sigaction sa;
  16647. /* Ignore SIGPIPE */
  16648. memset(&sa, 0, sizeof(sa));
  16649. sa.sa_handler = SIG_IGN;
  16650. sigaction(SIGPIPE, &sa, NULL);
  16651. #endif
  16652. worker_thread_run((struct mg_connection *)thread_func_param);
  16653. return NULL;
  16654. }
  16655. #endif /* _WIN32 */
  16656. /* This is an internal function, thus all arguments are expected to be
  16657. * valid - a NULL check is not required. */
  16658. static void
  16659. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16660. {
  16661. struct socket so;
  16662. char src_addr[IP_ADDR_STR_LEN];
  16663. socklen_t len = sizeof(so.rsa);
  16664. #if !defined(__ZEPHYR__)
  16665. int on = 1;
  16666. #endif
  16667. memset(&so, 0, sizeof(so));
  16668. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16669. == INVALID_SOCKET) {
  16670. } else if (check_acl(ctx, &so.rsa) != 1) {
  16671. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16672. mg_cry_ctx_internal(ctx,
  16673. "%s: %s is not allowed to connect",
  16674. __func__,
  16675. src_addr);
  16676. closesocket(so.sock);
  16677. } else {
  16678. /* Put so socket structure into the queue */
  16679. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16680. set_close_on_exec(so.sock, NULL, ctx);
  16681. so.is_ssl = listener->is_ssl;
  16682. so.ssl_redir = listener->ssl_redir;
  16683. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16684. mg_cry_ctx_internal(ctx,
  16685. "%s: getsockname() failed: %s",
  16686. __func__,
  16687. strerror(ERRNO));
  16688. }
  16689. #if !defined(__ZEPHYR__)
  16690. if ((so.lsa.sa.sa_family == AF_INET)
  16691. || (so.lsa.sa.sa_family == AF_INET6)) {
  16692. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16693. * This is needed because if HTTP-level keep-alive
  16694. * is enabled, and client resets the connection, server won't get
  16695. * TCP FIN or RST and will keep the connection open forever. With
  16696. * TCP keep-alive, next keep-alive handshake will figure out that
  16697. * the client is down and will close the server end.
  16698. * Thanks to Igor Klopov who suggested the patch. */
  16699. if (setsockopt(so.sock,
  16700. SOL_SOCKET,
  16701. SO_KEEPALIVE,
  16702. (SOCK_OPT_TYPE)&on,
  16703. sizeof(on))
  16704. != 0) {
  16705. mg_cry_ctx_internal(
  16706. ctx,
  16707. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16708. __func__,
  16709. strerror(ERRNO));
  16710. }
  16711. }
  16712. #endif
  16713. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16714. * to effectively fill up the underlying IP packet payload and
  16715. * reduce the overhead of sending lots of small buffers. However
  16716. * this hurts the server's throughput (ie. operations per second)
  16717. * when HTTP 1.1 persistent connections are used and the responses
  16718. * are relatively small (eg. less than 1400 bytes).
  16719. */
  16720. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16721. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16722. if (set_tcp_nodelay(&so, 1) != 0) {
  16723. mg_cry_ctx_internal(
  16724. ctx,
  16725. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16726. __func__,
  16727. strerror(ERRNO));
  16728. }
  16729. }
  16730. /* The "non blocking" property should already be
  16731. * inherited from the parent socket. Set it for
  16732. * non-compliant socket implementations. */
  16733. set_non_blocking_mode(so.sock);
  16734. so.in_use = 0;
  16735. produce_socket(ctx, &so);
  16736. }
  16737. }
  16738. static void
  16739. master_thread_run(struct mg_context *ctx)
  16740. {
  16741. struct mg_workerTLS tls;
  16742. struct mg_pollfd *pfd;
  16743. unsigned int i;
  16744. unsigned int workerthreadcount;
  16745. if (!ctx) {
  16746. return;
  16747. }
  16748. mg_set_thread_name("master");
  16749. /* Increase priority of the master thread */
  16750. #if defined(_WIN32)
  16751. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16752. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16753. int min_prio = sched_get_priority_min(SCHED_RR);
  16754. int max_prio = sched_get_priority_max(SCHED_RR);
  16755. if ((min_prio >= 0) && (max_prio >= 0)
  16756. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16757. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16758. struct sched_param sched_param = {0};
  16759. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16760. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16761. }
  16762. #endif
  16763. /* Initialize thread local storage */
  16764. #if defined(_WIN32)
  16765. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16766. #endif
  16767. tls.is_master = 1;
  16768. pthread_setspecific(sTlsKey, &tls);
  16769. if (ctx->callbacks.init_thread) {
  16770. /* Callback for the master thread (type 0) */
  16771. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16772. } else {
  16773. tls.user_ptr = NULL;
  16774. }
  16775. /* Lua background script "start" event */
  16776. #if defined(USE_LUA)
  16777. if (ctx->lua_background_state) {
  16778. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16779. /* call "start()" in Lua */
  16780. lua_getglobal(lstate, "start");
  16781. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16782. }
  16783. #endif
  16784. /* Server starts *now* */
  16785. ctx->start_time = time(NULL);
  16786. /* Server accept loop */
  16787. pfd = ctx->listening_socket_fds;
  16788. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16789. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16790. pfd[i].fd = ctx->listening_sockets[i].sock;
  16791. pfd[i].events = POLLIN;
  16792. }
  16793. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16794. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16795. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16796. * successful poll, and POLLIN is defined as
  16797. * (POLLRDNORM | POLLRDBAND)
  16798. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16799. * pfd[i].revents == POLLIN. */
  16800. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16801. && (pfd[i].revents & POLLIN)) {
  16802. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16803. }
  16804. }
  16805. }
  16806. }
  16807. /* Here stop_flag is 1 - Initiate shutdown. */
  16808. DEBUG_TRACE("%s", "stopping workers");
  16809. /* Stop signal received: somebody called mg_stop. Quit. */
  16810. close_all_listening_sockets(ctx);
  16811. /* Wakeup workers that are waiting for connections to handle. */
  16812. #if defined(ALTERNATIVE_QUEUE)
  16813. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16814. event_signal(ctx->client_wait_events[i]);
  16815. }
  16816. #else
  16817. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16818. pthread_cond_broadcast(&ctx->sq_full);
  16819. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16820. #endif
  16821. /* Join all worker threads to avoid leaking threads. */
  16822. workerthreadcount = ctx->cfg_worker_threads;
  16823. for (i = 0; i < workerthreadcount; i++) {
  16824. if (ctx->worker_threadids[i] != 0) {
  16825. mg_join_thread(ctx->worker_threadids[i]);
  16826. }
  16827. }
  16828. #if defined(USE_LUA)
  16829. /* Free Lua state of lua background task */
  16830. if (ctx->lua_background_state) {
  16831. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16832. /* call "stop()" in Lua */
  16833. lua_getglobal(lstate, "stop");
  16834. (void)lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16835. lua_close(lstate);
  16836. ctx->lua_background_state = 0;
  16837. }
  16838. #endif
  16839. DEBUG_TRACE("%s", "exiting");
  16840. /* call exit thread callback */
  16841. if (ctx->callbacks.exit_thread) {
  16842. /* Callback for the master thread (type 0) */
  16843. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16844. }
  16845. #if defined(_WIN32)
  16846. CloseHandle(tls.pthread_cond_helper_mutex);
  16847. #endif
  16848. pthread_setspecific(sTlsKey, NULL);
  16849. /* Signal mg_stop() that we're done.
  16850. * WARNING: This must be the very last thing this
  16851. * thread does, as ctx becomes invalid after this line. */
  16852. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16853. }
  16854. /* Threads have different return types on Windows and Unix. */
  16855. #if defined(_WIN32)
  16856. static unsigned __stdcall master_thread(void *thread_func_param)
  16857. {
  16858. master_thread_run((struct mg_context *)thread_func_param);
  16859. return 0;
  16860. }
  16861. #else
  16862. static void *
  16863. master_thread(void *thread_func_param)
  16864. {
  16865. #if !defined(__ZEPHYR__)
  16866. struct sigaction sa;
  16867. /* Ignore SIGPIPE */
  16868. memset(&sa, 0, sizeof(sa));
  16869. sa.sa_handler = SIG_IGN;
  16870. sigaction(SIGPIPE, &sa, NULL);
  16871. #endif
  16872. master_thread_run((struct mg_context *)thread_func_param);
  16873. return NULL;
  16874. }
  16875. #endif /* _WIN32 */
  16876. static void
  16877. free_context(struct mg_context *ctx)
  16878. {
  16879. int i;
  16880. struct mg_handler_info *tmp_rh;
  16881. if (ctx == NULL) {
  16882. return;
  16883. }
  16884. /* Call user callback */
  16885. if (ctx->callbacks.exit_context) {
  16886. ctx->callbacks.exit_context(ctx);
  16887. }
  16888. /* All threads exited, no sync is needed. Destroy thread mutex and
  16889. * condvars
  16890. */
  16891. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16892. #if defined(ALTERNATIVE_QUEUE)
  16893. mg_free(ctx->client_socks);
  16894. if (ctx->client_wait_events != NULL) {
  16895. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16896. event_destroy(ctx->client_wait_events[i]);
  16897. }
  16898. mg_free(ctx->client_wait_events);
  16899. }
  16900. #else
  16901. (void)pthread_cond_destroy(&ctx->sq_empty);
  16902. (void)pthread_cond_destroy(&ctx->sq_full);
  16903. mg_free(ctx->squeue);
  16904. #endif
  16905. /* Destroy other context global data structures mutex */
  16906. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16907. /* Deallocate config parameters */
  16908. for (i = 0; i < NUM_OPTIONS; i++) {
  16909. if (ctx->dd.config[i] != NULL) {
  16910. #if defined(_MSC_VER)
  16911. #pragma warning(suppress : 6001)
  16912. #endif
  16913. mg_free(ctx->dd.config[i]);
  16914. }
  16915. }
  16916. /* Deallocate request handlers */
  16917. while (ctx->dd.handlers) {
  16918. tmp_rh = ctx->dd.handlers;
  16919. ctx->dd.handlers = tmp_rh->next;
  16920. mg_free(tmp_rh->uri);
  16921. mg_free(tmp_rh);
  16922. }
  16923. #if !defined(NO_SSL)
  16924. /* Deallocate SSL context */
  16925. if (ctx->dd.ssl_ctx != NULL) {
  16926. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16927. int callback_ret =
  16928. (ctx->callbacks.external_ssl_ctx == NULL)
  16929. ? 0
  16930. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16931. if (callback_ret == 0) {
  16932. SSL_CTX_free(ctx->dd.ssl_ctx);
  16933. }
  16934. /* else: ignore error and ommit SSL_CTX_free in case
  16935. * callback_ret is 1 */
  16936. }
  16937. #endif /* !NO_SSL */
  16938. /* Deallocate worker thread ID array */
  16939. mg_free(ctx->worker_threadids);
  16940. /* Deallocate worker thread ID array */
  16941. mg_free(ctx->worker_connections);
  16942. /* deallocate system name string */
  16943. mg_free(ctx->systemName);
  16944. /* Deallocate context itself */
  16945. mg_free(ctx);
  16946. }
  16947. void
  16948. mg_stop(struct mg_context *ctx)
  16949. {
  16950. pthread_t mt;
  16951. if (!ctx) {
  16952. return;
  16953. }
  16954. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16955. * two threads is not allowed. */
  16956. mt = ctx->masterthreadid;
  16957. if (mt == 0) {
  16958. return;
  16959. }
  16960. ctx->masterthreadid = 0;
  16961. /* Set stop flag, so all threads know they have to exit. */
  16962. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16963. /* Join timer thread */
  16964. #if defined(USE_TIMERS)
  16965. timers_exit(ctx);
  16966. #endif
  16967. /* Wait until everything has stopped. */
  16968. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16969. (void)mg_sleep(10);
  16970. }
  16971. /* Wait to stop master thread */
  16972. mg_join_thread(mt);
  16973. /* Close remaining Lua states */
  16974. #if defined(USE_LUA)
  16975. lua_ctx_exit(ctx);
  16976. #endif
  16977. /* Free memory */
  16978. free_context(ctx);
  16979. }
  16980. static void
  16981. get_system_name(char **sysName)
  16982. {
  16983. #if defined(_WIN32)
  16984. #if defined(_WIN32_WCE)
  16985. *sysName = mg_strdup("WinCE");
  16986. #else
  16987. char name[128];
  16988. DWORD dwVersion = 0;
  16989. DWORD dwMajorVersion = 0;
  16990. DWORD dwMinorVersion = 0;
  16991. DWORD dwBuild = 0;
  16992. BOOL wowRet, isWoW = FALSE;
  16993. #if defined(_MSC_VER)
  16994. #pragma warning(push)
  16995. /* GetVersion was declared deprecated */
  16996. #pragma warning(disable : 4996)
  16997. #endif
  16998. dwVersion = GetVersion();
  16999. #if defined(_MSC_VER)
  17000. #pragma warning(pop)
  17001. #endif
  17002. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17003. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17004. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17005. (void)dwBuild;
  17006. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17007. sprintf(name,
  17008. "Windows %u.%u%s",
  17009. (unsigned)dwMajorVersion,
  17010. (unsigned)dwMinorVersion,
  17011. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17012. *sysName = mg_strdup(name);
  17013. #endif
  17014. #elif defined(__ZEPHYR__)
  17015. *sysName = mg_strdup("Zephyr OS");
  17016. #else
  17017. struct utsname name;
  17018. memset(&name, 0, sizeof(name));
  17019. uname(&name);
  17020. *sysName = mg_strdup(name.sysname);
  17021. #endif
  17022. }
  17023. static void
  17024. legacy_init(const char **options)
  17025. {
  17026. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17027. if (options) {
  17028. const char **run_options = options;
  17029. const char *optname = config_options[LISTENING_PORTS].name;
  17030. /* Try to find the "listening_ports" option */
  17031. while (*run_options) {
  17032. if (!strcmp(*run_options, optname)) {
  17033. ports_option = run_options[1];
  17034. }
  17035. run_options += 2;
  17036. }
  17037. }
  17038. if (is_ssl_port_used(ports_option)) {
  17039. /* Initialize with SSL support */
  17040. mg_init_library(MG_FEATURES_TLS);
  17041. } else {
  17042. /* Initialize without SSL support */
  17043. mg_init_library(MG_FEATURES_DEFAULT);
  17044. }
  17045. }
  17046. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  17047. static
  17048. #endif
  17049. struct mg_context *
  17050. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17051. {
  17052. struct mg_context *ctx;
  17053. const char *name, *value, *default_value;
  17054. int idx, ok, workerthreadcount;
  17055. unsigned int i;
  17056. int itmp;
  17057. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17058. const char **options =
  17059. ((init != NULL) ? (init->configuration_options) : (NULL));
  17060. struct mg_workerTLS tls;
  17061. if (error != NULL) {
  17062. error->code = 0;
  17063. if (error->text_buffer_size > 0) {
  17064. *error->text = 0;
  17065. }
  17066. }
  17067. if (mg_init_library_called == 0) {
  17068. /* Legacy INIT, if mg_start is called without mg_init_library.
  17069. * Note: This will cause a memory leak when unloading the library.
  17070. */
  17071. legacy_init(options);
  17072. }
  17073. if (mg_init_library_called == 0) {
  17074. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17075. mg_snprintf(NULL,
  17076. NULL, /* No truncation check for error buffers */
  17077. error->text,
  17078. error->text_buffer_size,
  17079. "%s",
  17080. "Library uninitialized");
  17081. }
  17082. return NULL;
  17083. }
  17084. /* Allocate context and initialize reasonable general case defaults. */
  17085. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17086. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17087. mg_snprintf(NULL,
  17088. NULL, /* No truncation check for error buffers */
  17089. error->text,
  17090. error->text_buffer_size,
  17091. "%s",
  17092. "Out of memory");
  17093. }
  17094. return NULL;
  17095. }
  17096. /* Random number generator will initialize at the first call */
  17097. ctx->dd.auth_nonce_mask =
  17098. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17099. /* Save started thread index to reuse in other external API calls
  17100. * For the sake of thread synchronization all non-civetweb threads
  17101. * can be considered as single external thread */
  17102. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17103. tls.is_master = -1; /* Thread calling mg_start */
  17104. tls.thread_idx = ctx->starter_thread_idx;
  17105. #if defined(_WIN32)
  17106. tls.pthread_cond_helper_mutex = NULL;
  17107. #endif
  17108. pthread_setspecific(sTlsKey, &tls);
  17109. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17110. #if !defined(ALTERNATIVE_QUEUE)
  17111. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17112. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17113. ctx->sq_blocked = 0;
  17114. #endif
  17115. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17116. if (!ok) {
  17117. const char *err_msg =
  17118. "Cannot initialize thread synchronization objects";
  17119. /* Fatal error - abort start. However, this situation should never
  17120. * occur in practice. */
  17121. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17122. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17123. mg_snprintf(NULL,
  17124. NULL, /* No truncation check for error buffers */
  17125. error->text,
  17126. error->text_buffer_size,
  17127. "%s",
  17128. err_msg);
  17129. }
  17130. mg_free(ctx);
  17131. pthread_setspecific(sTlsKey, NULL);
  17132. return NULL;
  17133. }
  17134. if ((init != NULL) && (init->callbacks != NULL)) {
  17135. /* Set all callbacks except exit_context. */
  17136. ctx->callbacks = *init->callbacks;
  17137. exit_callback = init->callbacks->exit_context;
  17138. /* The exit callback is activated once the context is successfully
  17139. * created. It should not be called, if an incomplete context object
  17140. * is deleted during a failed initialization. */
  17141. ctx->callbacks.exit_context = 0;
  17142. }
  17143. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17144. ctx->dd.handlers = NULL;
  17145. ctx->dd.next = NULL;
  17146. #if defined(USE_LUA)
  17147. lua_ctx_init(ctx);
  17148. #endif
  17149. /* Store options */
  17150. while (options && (name = *options++) != NULL) {
  17151. if ((idx = get_option_index(name)) == -1) {
  17152. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17153. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17154. mg_snprintf(NULL,
  17155. NULL, /* No truncation check for error buffers */
  17156. error->text,
  17157. error->text_buffer_size,
  17158. "Invalid configuration option: %s",
  17159. name);
  17160. }
  17161. free_context(ctx);
  17162. pthread_setspecific(sTlsKey, NULL);
  17163. return NULL;
  17164. } else if ((value = *options++) == NULL) {
  17165. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17166. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17167. mg_snprintf(NULL,
  17168. NULL, /* No truncation check for error buffers */
  17169. error->text,
  17170. error->text_buffer_size,
  17171. "Invalid configuration option value: %s",
  17172. name);
  17173. }
  17174. free_context(ctx);
  17175. pthread_setspecific(sTlsKey, NULL);
  17176. return NULL;
  17177. }
  17178. if (ctx->dd.config[idx] != NULL) {
  17179. /* A duplicate configuration option is not an error - the last
  17180. * option value will be used. */
  17181. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17182. mg_free(ctx->dd.config[idx]);
  17183. }
  17184. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17185. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17186. }
  17187. /* Set default value if needed */
  17188. for (i = 0; config_options[i].name != NULL; i++) {
  17189. default_value = config_options[i].default_value;
  17190. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17191. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17192. }
  17193. }
  17194. /* Request size option */
  17195. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17196. if (itmp < 1024) {
  17197. mg_cry_ctx_internal(ctx,
  17198. "%s too small",
  17199. config_options[MAX_REQUEST_SIZE].name);
  17200. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17201. mg_snprintf(NULL,
  17202. NULL, /* No truncation check for error buffers */
  17203. error->text,
  17204. error->text_buffer_size,
  17205. "Invalid configuration option value: %s",
  17206. config_options[MAX_REQUEST_SIZE].name);
  17207. }
  17208. free_context(ctx);
  17209. pthread_setspecific(sTlsKey, NULL);
  17210. return NULL;
  17211. }
  17212. ctx->max_request_size = (unsigned)itmp;
  17213. /* Queue length */
  17214. #if !defined(ALTERNATIVE_QUEUE)
  17215. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17216. if (itmp < 1) {
  17217. mg_cry_ctx_internal(ctx,
  17218. "%s too small",
  17219. config_options[CONNECTION_QUEUE_SIZE].name);
  17220. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17221. mg_snprintf(NULL,
  17222. NULL, /* No truncation check for error buffers */
  17223. error->text,
  17224. error->text_buffer_size,
  17225. "Invalid configuration option value: %s",
  17226. config_options[CONNECTION_QUEUE_SIZE].name);
  17227. }
  17228. free_context(ctx);
  17229. pthread_setspecific(sTlsKey, NULL);
  17230. return NULL;
  17231. }
  17232. ctx->squeue =
  17233. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17234. if (ctx->squeue == NULL) {
  17235. mg_cry_ctx_internal(ctx,
  17236. "Out of memory: Cannot allocate %s",
  17237. config_options[CONNECTION_QUEUE_SIZE].name);
  17238. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17239. mg_snprintf(NULL,
  17240. NULL, /* No truncation check for error buffers */
  17241. error->text,
  17242. error->text_buffer_size,
  17243. "Out of memory: Cannot allocate %s",
  17244. config_options[CONNECTION_QUEUE_SIZE].name);
  17245. }
  17246. free_context(ctx);
  17247. pthread_setspecific(sTlsKey, NULL);
  17248. return NULL;
  17249. }
  17250. ctx->sq_size = itmp;
  17251. #endif
  17252. /* Worker thread count option */
  17253. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17254. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17255. if (workerthreadcount <= 0) {
  17256. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17257. } else {
  17258. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17259. }
  17260. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17261. mg_snprintf(NULL,
  17262. NULL, /* No truncation check for error buffers */
  17263. error->text,
  17264. error->text_buffer_size,
  17265. "Invalid configuration option value: %s",
  17266. config_options[NUM_THREADS].name);
  17267. }
  17268. free_context(ctx);
  17269. pthread_setspecific(sTlsKey, NULL);
  17270. return NULL;
  17271. }
  17272. /* Document root */
  17273. #if defined(NO_FILES)
  17274. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17275. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17276. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17277. mg_snprintf(NULL,
  17278. NULL, /* No truncation check for error buffers */
  17279. error->text,
  17280. error->text_buffer_size,
  17281. "Invalid configuration option value: %s",
  17282. config_options[DOCUMENT_ROOT].name);
  17283. }
  17284. free_context(ctx);
  17285. pthread_setspecific(sTlsKey, NULL);
  17286. return NULL;
  17287. }
  17288. #endif
  17289. get_system_name(&ctx->systemName);
  17290. #if defined(USE_LUA)
  17291. /* If a Lua background script has been configured, start it. */
  17292. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17293. char ebuf[256];
  17294. struct vec opt_vec;
  17295. struct vec eq_vec;
  17296. const char *sparams;
  17297. /* Create a Lua state, load all standard libraries and the mg table */
  17298. lua_State *state = mg_lua_context_script_prepare(
  17299. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17300. if (!state) {
  17301. mg_cry_ctx_internal(ctx,
  17302. "lua_background_script load error: %s",
  17303. ebuf);
  17304. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17305. mg_snprintf(NULL,
  17306. NULL, /* No truncation check for error buffers */
  17307. error->text,
  17308. error->text_buffer_size,
  17309. "Error in script %s: %s",
  17310. config_options[DOCUMENT_ROOT].name,
  17311. ebuf);
  17312. }
  17313. free_context(ctx);
  17314. pthread_setspecific(sTlsKey, NULL);
  17315. return NULL;
  17316. }
  17317. /* Add a table with parameters into mg.params */
  17318. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17319. if (sparams && sparams[0]) {
  17320. lua_getglobal(state, "mg");
  17321. lua_pushstring(state, "params");
  17322. lua_newtable(state);
  17323. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17324. != NULL) {
  17325. reg_llstring(
  17326. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17327. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17328. break;
  17329. }
  17330. lua_rawset(state, -3);
  17331. lua_pop(state, 1);
  17332. }
  17333. /* Call script */
  17334. state = mg_lua_context_script_run(state,
  17335. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17336. ctx,
  17337. ebuf,
  17338. sizeof(ebuf));
  17339. if (!state) {
  17340. mg_cry_ctx_internal(ctx,
  17341. "lua_background_script start error: %s",
  17342. ebuf);
  17343. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17344. mg_snprintf(NULL,
  17345. NULL, /* No truncation check for error buffers */
  17346. error->text,
  17347. error->text_buffer_size,
  17348. "Error in script %s: %s",
  17349. config_options[DOCUMENT_ROOT].name,
  17350. ebuf);
  17351. }
  17352. free_context(ctx);
  17353. pthread_setspecific(sTlsKey, NULL);
  17354. return NULL;
  17355. }
  17356. /* state remains valid */
  17357. ctx->lua_background_state = (void *)state;
  17358. } else {
  17359. ctx->lua_background_state = 0;
  17360. }
  17361. #endif
  17362. /* Step by step initialization of ctx - depending on build options */
  17363. #if !defined(NO_FILESYSTEMS)
  17364. if (!set_gpass_option(ctx, NULL)) {
  17365. const char *err_msg = "Invalid global password file";
  17366. /* Fatal error - abort start. */
  17367. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17368. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17369. mg_snprintf(NULL,
  17370. NULL, /* No truncation check for error buffers */
  17371. error->text,
  17372. error->text_buffer_size,
  17373. "%s",
  17374. err_msg);
  17375. }
  17376. free_context(ctx);
  17377. pthread_setspecific(sTlsKey, NULL);
  17378. return NULL;
  17379. }
  17380. #endif
  17381. #if !defined(NO_SSL)
  17382. if (!init_ssl_ctx(ctx, NULL)) {
  17383. const char *err_msg = "Error initializing SSL context";
  17384. /* Fatal error - abort start. */
  17385. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17386. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17387. mg_snprintf(NULL,
  17388. NULL, /* No truncation check for error buffers */
  17389. error->text,
  17390. error->text_buffer_size,
  17391. "%s",
  17392. err_msg);
  17393. }
  17394. free_context(ctx);
  17395. pthread_setspecific(sTlsKey, NULL);
  17396. return NULL;
  17397. }
  17398. #endif
  17399. if (!set_ports_option(ctx)) {
  17400. const char *err_msg = "Failed to setup server ports";
  17401. /* Fatal error - abort start. */
  17402. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17403. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17404. mg_snprintf(NULL,
  17405. NULL, /* No truncation check for error buffers */
  17406. error->text,
  17407. error->text_buffer_size,
  17408. "%s",
  17409. err_msg);
  17410. }
  17411. free_context(ctx);
  17412. pthread_setspecific(sTlsKey, NULL);
  17413. return NULL;
  17414. }
  17415. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17416. if (!set_uid_option(ctx)) {
  17417. const char *err_msg = "Failed to run as configured user";
  17418. /* Fatal error - abort start. */
  17419. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17420. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17421. mg_snprintf(NULL,
  17422. NULL, /* No truncation check for error buffers */
  17423. error->text,
  17424. error->text_buffer_size,
  17425. "%s",
  17426. err_msg);
  17427. }
  17428. free_context(ctx);
  17429. pthread_setspecific(sTlsKey, NULL);
  17430. return NULL;
  17431. }
  17432. #endif
  17433. if (!set_acl_option(ctx)) {
  17434. const char *err_msg = "Failed to setup access control list";
  17435. /* Fatal error - abort start. */
  17436. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17437. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17438. mg_snprintf(NULL,
  17439. NULL, /* No truncation check for error buffers */
  17440. error->text,
  17441. error->text_buffer_size,
  17442. "%s",
  17443. err_msg);
  17444. }
  17445. free_context(ctx);
  17446. pthread_setspecific(sTlsKey, NULL);
  17447. return NULL;
  17448. }
  17449. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17450. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17451. sizeof(pthread_t),
  17452. ctx);
  17453. if (ctx->worker_threadids == NULL) {
  17454. const char *err_msg = "Not enough memory for worker thread ID array";
  17455. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17456. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17457. mg_snprintf(NULL,
  17458. NULL, /* No truncation check for error buffers */
  17459. error->text,
  17460. error->text_buffer_size,
  17461. "%s",
  17462. err_msg);
  17463. }
  17464. free_context(ctx);
  17465. pthread_setspecific(sTlsKey, NULL);
  17466. return NULL;
  17467. }
  17468. ctx->worker_connections =
  17469. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17470. sizeof(struct mg_connection),
  17471. ctx);
  17472. if (ctx->worker_connections == NULL) {
  17473. const char *err_msg =
  17474. "Not enough memory for worker thread connection array";
  17475. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17476. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17477. mg_snprintf(NULL,
  17478. NULL, /* No truncation check for error buffers */
  17479. error->text,
  17480. error->text_buffer_size,
  17481. "%s",
  17482. err_msg);
  17483. }
  17484. free_context(ctx);
  17485. pthread_setspecific(sTlsKey, NULL);
  17486. return NULL;
  17487. }
  17488. #if defined(ALTERNATIVE_QUEUE)
  17489. ctx->client_wait_events =
  17490. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17491. sizeof(ctx->client_wait_events[0]),
  17492. ctx);
  17493. if (ctx->client_wait_events == NULL) {
  17494. const char *err_msg = "Not enough memory for worker event array";
  17495. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17496. mg_free(ctx->worker_threadids);
  17497. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17498. mg_snprintf(NULL,
  17499. NULL, /* No truncation check for error buffers */
  17500. error->text,
  17501. error->text_buffer_size,
  17502. "%s",
  17503. err_msg);
  17504. }
  17505. free_context(ctx);
  17506. pthread_setspecific(sTlsKey, NULL);
  17507. return NULL;
  17508. }
  17509. ctx->client_socks =
  17510. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17511. sizeof(ctx->client_socks[0]),
  17512. ctx);
  17513. if (ctx->client_socks == NULL) {
  17514. const char *err_msg = "Not enough memory for worker socket array";
  17515. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17516. mg_free(ctx->client_wait_events);
  17517. mg_free(ctx->worker_threadids);
  17518. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17519. mg_snprintf(NULL,
  17520. NULL, /* No truncation check for error buffers */
  17521. error->text,
  17522. error->text_buffer_size,
  17523. "%s",
  17524. err_msg);
  17525. }
  17526. free_context(ctx);
  17527. pthread_setspecific(sTlsKey, NULL);
  17528. return NULL;
  17529. }
  17530. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17531. ctx->client_wait_events[i] = event_create();
  17532. if (ctx->client_wait_events[i] == 0) {
  17533. const char *err_msg = "Error creating worker event %i";
  17534. mg_cry_ctx_internal(ctx, err_msg, i);
  17535. while (i > 0) {
  17536. i--;
  17537. event_destroy(ctx->client_wait_events[i]);
  17538. }
  17539. mg_free(ctx->client_socks);
  17540. mg_free(ctx->client_wait_events);
  17541. mg_free(ctx->worker_threadids);
  17542. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17543. mg_snprintf(NULL,
  17544. NULL, /* No truncation check for error buffers */
  17545. error->text,
  17546. error->text_buffer_size,
  17547. err_msg,
  17548. i);
  17549. }
  17550. free_context(ctx);
  17551. pthread_setspecific(sTlsKey, NULL);
  17552. return NULL;
  17553. }
  17554. }
  17555. #endif
  17556. #if defined(USE_TIMERS)
  17557. if (timers_init(ctx) != 0) {
  17558. const char *err_msg = "Error creating timers";
  17559. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17560. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17561. mg_snprintf(NULL,
  17562. NULL, /* No truncation check for error buffers */
  17563. error->text,
  17564. error->text_buffer_size,
  17565. "%s",
  17566. err_msg);
  17567. }
  17568. free_context(ctx);
  17569. pthread_setspecific(sTlsKey, NULL);
  17570. return NULL;
  17571. }
  17572. #endif
  17573. /* Context has been created - init user libraries */
  17574. if (ctx->callbacks.init_context) {
  17575. ctx->callbacks.init_context(ctx);
  17576. }
  17577. /* From now, the context is successfully created.
  17578. * When it is destroyed, the exit callback should be called. */
  17579. ctx->callbacks.exit_context = exit_callback;
  17580. ctx->context_type = CONTEXT_SERVER; /* server context */
  17581. /* Start worker threads */
  17582. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17583. /* worker_thread sets up the other fields */
  17584. ctx->worker_connections[i].phys_ctx = ctx;
  17585. if (mg_start_thread_with_id(worker_thread,
  17586. &ctx->worker_connections[i],
  17587. &ctx->worker_threadids[i])
  17588. != 0) {
  17589. long error_no = (long)ERRNO;
  17590. /* thread was not created */
  17591. if (i > 0) {
  17592. /* If the second, third, ... thread cannot be created, set a
  17593. * warning, but keep running. */
  17594. mg_cry_ctx_internal(ctx,
  17595. "Cannot start worker thread %i: error %ld",
  17596. i + 1,
  17597. error_no);
  17598. /* If the server initialization should stop here, all
  17599. * threads that have already been created must be stopped
  17600. * first, before any free_context(ctx) call.
  17601. */
  17602. } else {
  17603. /* If the first worker thread cannot be created, stop
  17604. * initialization and free the entire server context. */
  17605. mg_cry_ctx_internal(ctx,
  17606. "Cannot create threads: error %ld",
  17607. error_no);
  17608. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17609. mg_snprintf(
  17610. NULL,
  17611. NULL, /* No truncation check for error buffers */
  17612. error->text,
  17613. error->text_buffer_size,
  17614. "Cannot create first worker thread: error %ld",
  17615. error_no);
  17616. }
  17617. free_context(ctx);
  17618. pthread_setspecific(sTlsKey, NULL);
  17619. return NULL;
  17620. }
  17621. break;
  17622. }
  17623. }
  17624. /* Start master (listening) thread */
  17625. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17626. pthread_setspecific(sTlsKey, NULL);
  17627. return ctx;
  17628. }
  17629. struct mg_context *
  17630. mg_start(const struct mg_callbacks *callbacks,
  17631. void *user_data,
  17632. const char **options)
  17633. {
  17634. struct mg_init_data init = {0};
  17635. init.callbacks = callbacks;
  17636. init.user_data = user_data;
  17637. init.configuration_options = options;
  17638. return mg_start2(&init, NULL);
  17639. }
  17640. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17641. /* Add an additional domain to an already running web server. */
  17642. int
  17643. mg_start_domain2(struct mg_context *ctx,
  17644. const char **options,
  17645. struct mg_error_data *error)
  17646. {
  17647. const char *name;
  17648. const char *value;
  17649. const char *default_value;
  17650. struct mg_domain_context *new_dom;
  17651. struct mg_domain_context *dom;
  17652. int idx, i;
  17653. if (error != NULL) {
  17654. error->code = 0;
  17655. if (error->text_buffer_size > 0) {
  17656. *error->text = 0;
  17657. }
  17658. }
  17659. if ((ctx == NULL) || (options == NULL)) {
  17660. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17661. mg_snprintf(NULL,
  17662. NULL, /* No truncation check for error buffers */
  17663. error->text,
  17664. error->text_buffer_size,
  17665. "%s",
  17666. "Invalid parameters");
  17667. }
  17668. return -1;
  17669. }
  17670. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17671. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17672. mg_snprintf(NULL,
  17673. NULL, /* No truncation check for error buffers */
  17674. error->text,
  17675. error->text_buffer_size,
  17676. "%s",
  17677. "Server already stopped");
  17678. }
  17679. return -1;
  17680. }
  17681. new_dom = (struct mg_domain_context *)
  17682. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17683. if (!new_dom) {
  17684. /* Out of memory */
  17685. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17686. mg_snprintf(NULL,
  17687. NULL, /* No truncation check for error buffers */
  17688. error->text,
  17689. error->text_buffer_size,
  17690. "%s",
  17691. "Out or memory");
  17692. }
  17693. return -6;
  17694. }
  17695. /* Store options - TODO: unite duplicate code */
  17696. while (options && (name = *options++) != NULL) {
  17697. if ((idx = get_option_index(name)) == -1) {
  17698. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17699. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17700. mg_snprintf(NULL,
  17701. NULL, /* No truncation check for error buffers */
  17702. error->text,
  17703. error->text_buffer_size,
  17704. "Invalid option: %s",
  17705. name);
  17706. }
  17707. mg_free(new_dom);
  17708. return -2;
  17709. } else if ((value = *options++) == NULL) {
  17710. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17711. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17712. mg_snprintf(NULL,
  17713. NULL, /* No truncation check for error buffers */
  17714. error->text,
  17715. error->text_buffer_size,
  17716. "Invalid option value: %s",
  17717. name);
  17718. }
  17719. mg_free(new_dom);
  17720. return -2;
  17721. }
  17722. if (new_dom->config[idx] != NULL) {
  17723. /* Duplicate option: Later values overwrite earlier ones. */
  17724. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17725. mg_free(new_dom->config[idx]);
  17726. }
  17727. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17728. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17729. }
  17730. /* Authentication domain is mandatory */
  17731. /* TODO: Maybe use a new option hostname? */
  17732. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17733. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17734. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17735. mg_snprintf(NULL,
  17736. NULL, /* No truncation check for error buffers */
  17737. error->text,
  17738. error->text_buffer_size,
  17739. "Mandatory option %s missing",
  17740. config_options[AUTHENTICATION_DOMAIN].name);
  17741. }
  17742. mg_free(new_dom);
  17743. return -4;
  17744. }
  17745. /* Set default value if needed. Take the config value from
  17746. * ctx as a default value. */
  17747. for (i = 0; config_options[i].name != NULL; i++) {
  17748. default_value = ctx->dd.config[i];
  17749. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17750. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17751. }
  17752. }
  17753. new_dom->handlers = NULL;
  17754. new_dom->next = NULL;
  17755. new_dom->nonce_count = 0;
  17756. new_dom->auth_nonce_mask =
  17757. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17758. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17759. new_dom->shared_lua_websockets = NULL;
  17760. #endif
  17761. #if !defined(NO_SSL)
  17762. if (!init_ssl_ctx(ctx, new_dom)) {
  17763. /* Init SSL failed */
  17764. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17765. mg_snprintf(NULL,
  17766. NULL, /* No truncation check for error buffers */
  17767. error->text,
  17768. error->text_buffer_size,
  17769. "%s",
  17770. "Initializing SSL context failed");
  17771. }
  17772. mg_free(new_dom);
  17773. return -3;
  17774. }
  17775. #endif
  17776. /* Add element to linked list. */
  17777. mg_lock_context(ctx);
  17778. idx = 0;
  17779. dom = &(ctx->dd);
  17780. for (;;) {
  17781. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17782. dom->config[AUTHENTICATION_DOMAIN])) {
  17783. /* Domain collision */
  17784. mg_cry_ctx_internal(ctx,
  17785. "domain %s already in use",
  17786. new_dom->config[AUTHENTICATION_DOMAIN]);
  17787. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17788. mg_snprintf(NULL,
  17789. NULL, /* No truncation check for error buffers */
  17790. error->text,
  17791. error->text_buffer_size,
  17792. "Domain %s specified by %s is already in use",
  17793. new_dom->config[AUTHENTICATION_DOMAIN],
  17794. config_options[AUTHENTICATION_DOMAIN].name);
  17795. }
  17796. mg_free(new_dom);
  17797. mg_unlock_context(ctx);
  17798. return -5;
  17799. }
  17800. /* Count number of domains */
  17801. idx++;
  17802. if (dom->next == NULL) {
  17803. dom->next = new_dom;
  17804. break;
  17805. }
  17806. dom = dom->next;
  17807. }
  17808. mg_unlock_context(ctx);
  17809. /* Return domain number */
  17810. return idx;
  17811. }
  17812. int
  17813. mg_start_domain(struct mg_context *ctx, const char **options)
  17814. {
  17815. return mg_start_domain2(ctx, options, NULL);
  17816. }
  17817. #endif
  17818. /* Feature check API function */
  17819. unsigned
  17820. mg_check_feature(unsigned feature)
  17821. {
  17822. static const unsigned feature_set = 0
  17823. /* Set bits for available features according to API documentation.
  17824. * This bit mask is created at compile time, according to the active
  17825. * preprocessor defines. It is a single const value at runtime. */
  17826. #if !defined(NO_FILES)
  17827. | MG_FEATURES_FILES
  17828. #endif
  17829. #if !defined(NO_SSL)
  17830. | MG_FEATURES_SSL
  17831. #endif
  17832. #if !defined(NO_CGI)
  17833. | MG_FEATURES_CGI
  17834. #endif
  17835. #if defined(USE_IPV6)
  17836. | MG_FEATURES_IPV6
  17837. #endif
  17838. #if defined(USE_WEBSOCKET)
  17839. | MG_FEATURES_WEBSOCKET
  17840. #endif
  17841. #if defined(USE_LUA)
  17842. | MG_FEATURES_LUA
  17843. #endif
  17844. #if defined(USE_DUKTAPE)
  17845. | MG_FEATURES_SSJS
  17846. #endif
  17847. #if !defined(NO_CACHING)
  17848. | MG_FEATURES_CACHE
  17849. #endif
  17850. #if defined(USE_SERVER_STATS)
  17851. | MG_FEATURES_STATS
  17852. #endif
  17853. #if defined(USE_ZLIB)
  17854. | MG_FEATURES_COMPRESSION
  17855. #endif
  17856. #if defined(USE_HTTP2)
  17857. | MG_FEATURES_HTTP2
  17858. #endif
  17859. #if defined(USE_X_DOM_SOCKET)
  17860. | MG_FEATURES_X_DOMAIN_SOCKET
  17861. #endif
  17862. /* Set some extra bits not defined in the API documentation.
  17863. * These bits may change without further notice. */
  17864. #if defined(MG_LEGACY_INTERFACE)
  17865. | 0x80000000u
  17866. #endif
  17867. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17868. | 0x40000000u
  17869. #endif
  17870. #if !defined(NO_RESPONSE_BUFFERING)
  17871. | 0x20000000u
  17872. #endif
  17873. #if defined(MEMORY_DEBUGGING)
  17874. | 0x10000000u
  17875. #endif
  17876. ;
  17877. return (feature & feature_set);
  17878. }
  17879. static size_t
  17880. mg_str_append(char **dst, char *end, const char *src)
  17881. {
  17882. size_t len = strlen(src);
  17883. if (*dst != end) {
  17884. /* Append src if enough space, or close dst. */
  17885. if ((size_t)(end - *dst) > len) {
  17886. strcpy(*dst, src);
  17887. *dst += len;
  17888. } else {
  17889. *dst = end;
  17890. }
  17891. }
  17892. return len;
  17893. }
  17894. /* Get system information. It can be printed or stored by the caller.
  17895. * Return the size of available information. */
  17896. int
  17897. mg_get_system_info(char *buffer, int buflen)
  17898. {
  17899. char *end, *append_eoobj = NULL, block[256];
  17900. size_t system_info_length = 0;
  17901. #if defined(_WIN32)
  17902. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17903. #else
  17904. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17905. #endif
  17906. if ((buffer == NULL) || (buflen < 1)) {
  17907. buflen = 0;
  17908. end = buffer;
  17909. } else {
  17910. *buffer = 0;
  17911. end = buffer + buflen;
  17912. }
  17913. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17914. /* has enough space to append eoobj */
  17915. append_eoobj = buffer;
  17916. if (end) {
  17917. end -= sizeof(eoobj) - 1;
  17918. }
  17919. }
  17920. system_info_length += mg_str_append(&buffer, end, "{");
  17921. /* Server version */
  17922. {
  17923. const char *version = mg_version();
  17924. mg_snprintf(NULL,
  17925. NULL,
  17926. block,
  17927. sizeof(block),
  17928. "%s\"version\" : \"%s\"",
  17929. eol,
  17930. version);
  17931. system_info_length += mg_str_append(&buffer, end, block);
  17932. }
  17933. /* System info */
  17934. {
  17935. #if defined(_WIN32)
  17936. DWORD dwVersion = 0;
  17937. DWORD dwMajorVersion = 0;
  17938. DWORD dwMinorVersion = 0;
  17939. SYSTEM_INFO si;
  17940. GetSystemInfo(&si);
  17941. #if defined(_MSC_VER)
  17942. #pragma warning(push)
  17943. /* GetVersion was declared deprecated */
  17944. #pragma warning(disable : 4996)
  17945. #endif
  17946. dwVersion = GetVersion();
  17947. #if defined(_MSC_VER)
  17948. #pragma warning(pop)
  17949. #endif
  17950. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17951. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17952. mg_snprintf(NULL,
  17953. NULL,
  17954. block,
  17955. sizeof(block),
  17956. ",%s\"os\" : \"Windows %u.%u\"",
  17957. eol,
  17958. (unsigned)dwMajorVersion,
  17959. (unsigned)dwMinorVersion);
  17960. system_info_length += mg_str_append(&buffer, end, block);
  17961. mg_snprintf(NULL,
  17962. NULL,
  17963. block,
  17964. sizeof(block),
  17965. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17966. eol,
  17967. (unsigned)si.wProcessorArchitecture,
  17968. (unsigned)si.dwNumberOfProcessors,
  17969. (unsigned)si.dwActiveProcessorMask);
  17970. system_info_length += mg_str_append(&buffer, end, block);
  17971. #elif defined(__ZEPHYR__)
  17972. mg_snprintf(NULL,
  17973. NULL,
  17974. block,
  17975. sizeof(block),
  17976. ",%s\"os\" : \"%s %s\"",
  17977. eol,
  17978. "Zephyr OS",
  17979. ZEPHYR_VERSION);
  17980. system_info_length += mg_str_append(&buffer, end, block);
  17981. #else
  17982. struct utsname name;
  17983. memset(&name, 0, sizeof(name));
  17984. uname(&name);
  17985. mg_snprintf(NULL,
  17986. NULL,
  17987. block,
  17988. sizeof(block),
  17989. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17990. eol,
  17991. name.sysname,
  17992. name.version,
  17993. name.release,
  17994. name.machine);
  17995. system_info_length += mg_str_append(&buffer, end, block);
  17996. #endif
  17997. }
  17998. /* Features */
  17999. {
  18000. mg_snprintf(NULL,
  18001. NULL,
  18002. block,
  18003. sizeof(block),
  18004. ",%s\"features\" : %lu"
  18005. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18006. eol,
  18007. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18008. eol,
  18009. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18010. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18011. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18012. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18013. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18014. : "",
  18015. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18016. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18017. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18018. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18019. system_info_length += mg_str_append(&buffer, end, block);
  18020. #if defined(USE_LUA)
  18021. mg_snprintf(NULL,
  18022. NULL,
  18023. block,
  18024. sizeof(block),
  18025. ",%s\"lua_version\" : \"%u (%s)\"",
  18026. eol,
  18027. (unsigned)LUA_VERSION_NUM,
  18028. LUA_RELEASE);
  18029. system_info_length += mg_str_append(&buffer, end, block);
  18030. #endif
  18031. #if defined(USE_DUKTAPE)
  18032. mg_snprintf(NULL,
  18033. NULL,
  18034. block,
  18035. sizeof(block),
  18036. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18037. eol,
  18038. (unsigned)DUK_VERSION / 10000,
  18039. ((unsigned)DUK_VERSION / 100) % 100,
  18040. (unsigned)DUK_VERSION % 100);
  18041. system_info_length += mg_str_append(&buffer, end, block);
  18042. #endif
  18043. }
  18044. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18045. {
  18046. #if defined(BUILD_DATE)
  18047. const char *bd = BUILD_DATE;
  18048. #else
  18049. #if defined(GCC_DIAGNOSTIC)
  18050. #if GCC_VERSION >= 40900
  18051. #pragma GCC diagnostic push
  18052. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18053. * does not work in some versions. If "BUILD_DATE" is defined to some
  18054. * string, it is used instead of __DATE__. */
  18055. #pragma GCC diagnostic ignored "-Wdate-time"
  18056. #endif
  18057. #endif
  18058. const char *bd = __DATE__;
  18059. #if defined(GCC_DIAGNOSTIC)
  18060. #if GCC_VERSION >= 40900
  18061. #pragma GCC diagnostic pop
  18062. #endif
  18063. #endif
  18064. #endif
  18065. mg_snprintf(
  18066. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18067. system_info_length += mg_str_append(&buffer, end, block);
  18068. }
  18069. /* Compiler information */
  18070. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18071. {
  18072. #if defined(_MSC_VER)
  18073. mg_snprintf(NULL,
  18074. NULL,
  18075. block,
  18076. sizeof(block),
  18077. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18078. eol,
  18079. (unsigned)_MSC_VER,
  18080. (unsigned)_MSC_FULL_VER);
  18081. system_info_length += mg_str_append(&buffer, end, block);
  18082. #elif defined(__MINGW64__)
  18083. mg_snprintf(NULL,
  18084. NULL,
  18085. block,
  18086. sizeof(block),
  18087. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18088. eol,
  18089. (unsigned)__MINGW64_VERSION_MAJOR,
  18090. (unsigned)__MINGW64_VERSION_MINOR);
  18091. system_info_length += mg_str_append(&buffer, end, block);
  18092. mg_snprintf(NULL,
  18093. NULL,
  18094. block,
  18095. sizeof(block),
  18096. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18097. eol,
  18098. (unsigned)__MINGW32_MAJOR_VERSION,
  18099. (unsigned)__MINGW32_MINOR_VERSION);
  18100. system_info_length += mg_str_append(&buffer, end, block);
  18101. #elif defined(__MINGW32__)
  18102. mg_snprintf(NULL,
  18103. NULL,
  18104. block,
  18105. sizeof(block),
  18106. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18107. eol,
  18108. (unsigned)__MINGW32_MAJOR_VERSION,
  18109. (unsigned)__MINGW32_MINOR_VERSION);
  18110. system_info_length += mg_str_append(&buffer, end, block);
  18111. #elif defined(__clang__)
  18112. mg_snprintf(NULL,
  18113. NULL,
  18114. block,
  18115. sizeof(block),
  18116. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18117. eol,
  18118. __clang_major__,
  18119. __clang_minor__,
  18120. __clang_patchlevel__,
  18121. __clang_version__);
  18122. system_info_length += mg_str_append(&buffer, end, block);
  18123. #elif defined(__GNUC__)
  18124. mg_snprintf(NULL,
  18125. NULL,
  18126. block,
  18127. sizeof(block),
  18128. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18129. eol,
  18130. (unsigned)__GNUC__,
  18131. (unsigned)__GNUC_MINOR__,
  18132. (unsigned)__GNUC_PATCHLEVEL__);
  18133. system_info_length += mg_str_append(&buffer, end, block);
  18134. #elif defined(__INTEL_COMPILER)
  18135. mg_snprintf(NULL,
  18136. NULL,
  18137. block,
  18138. sizeof(block),
  18139. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18140. eol,
  18141. (unsigned)__INTEL_COMPILER);
  18142. system_info_length += mg_str_append(&buffer, end, block);
  18143. #elif defined(__BORLANDC__)
  18144. mg_snprintf(NULL,
  18145. NULL,
  18146. block,
  18147. sizeof(block),
  18148. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18149. eol,
  18150. (unsigned)__BORLANDC__);
  18151. system_info_length += mg_str_append(&buffer, end, block);
  18152. #elif defined(__SUNPRO_C)
  18153. mg_snprintf(NULL,
  18154. NULL,
  18155. block,
  18156. sizeof(block),
  18157. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18158. eol,
  18159. (unsigned)__SUNPRO_C);
  18160. system_info_length += mg_str_append(&buffer, end, block);
  18161. #else
  18162. mg_snprintf(NULL,
  18163. NULL,
  18164. block,
  18165. sizeof(block),
  18166. ",%s\"compiler\" : \"other\"",
  18167. eol);
  18168. system_info_length += mg_str_append(&buffer, end, block);
  18169. #endif
  18170. }
  18171. /* Determine 32/64 bit data mode.
  18172. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18173. {
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18179. "char:%u/%u, "
  18180. "ptr:%u, size:%u, time:%u\"",
  18181. eol,
  18182. (unsigned)sizeof(short),
  18183. (unsigned)sizeof(int),
  18184. (unsigned)sizeof(long),
  18185. (unsigned)sizeof(long long),
  18186. (unsigned)sizeof(float),
  18187. (unsigned)sizeof(double),
  18188. (unsigned)sizeof(long double),
  18189. (unsigned)sizeof(char),
  18190. (unsigned)sizeof(wchar_t),
  18191. (unsigned)sizeof(void *),
  18192. (unsigned)sizeof(size_t),
  18193. (unsigned)sizeof(time_t));
  18194. system_info_length += mg_str_append(&buffer, end, block);
  18195. }
  18196. /* Terminate string */
  18197. if (append_eoobj) {
  18198. strcat(append_eoobj, eoobj);
  18199. }
  18200. system_info_length += sizeof(eoobj) - 1;
  18201. return (int)system_info_length;
  18202. }
  18203. /* Get context information. It can be printed or stored by the caller.
  18204. * Return the size of available information. */
  18205. int
  18206. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18207. {
  18208. #if defined(USE_SERVER_STATS)
  18209. char *end, *append_eoobj = NULL, block[256];
  18210. size_t context_info_length = 0;
  18211. #if defined(_WIN32)
  18212. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18213. #else
  18214. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18215. #endif
  18216. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18217. if ((buffer == NULL) || (buflen < 1)) {
  18218. buflen = 0;
  18219. end = buffer;
  18220. } else {
  18221. *buffer = 0;
  18222. end = buffer + buflen;
  18223. }
  18224. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18225. /* has enough space to append eoobj */
  18226. append_eoobj = buffer;
  18227. end -= sizeof(eoobj) - 1;
  18228. }
  18229. context_info_length += mg_str_append(&buffer, end, "{");
  18230. if (ms) { /* <-- should be always true */
  18231. /* Memory information */
  18232. int blockCount = (int)ms->blockCount;
  18233. int64_t totalMemUsed = ms->totalMemUsed;
  18234. int64_t maxMemUsed = ms->maxMemUsed;
  18235. if (totalMemUsed > maxMemUsed) {
  18236. maxMemUsed = totalMemUsed;
  18237. }
  18238. mg_snprintf(NULL,
  18239. NULL,
  18240. block,
  18241. sizeof(block),
  18242. "%s\"memory\" : {%s"
  18243. "\"blocks\" : %i,%s"
  18244. "\"used\" : %" INT64_FMT ",%s"
  18245. "\"maxUsed\" : %" INT64_FMT "%s"
  18246. "}",
  18247. eol,
  18248. eol,
  18249. blockCount,
  18250. eol,
  18251. totalMemUsed,
  18252. eol,
  18253. maxMemUsed,
  18254. eol);
  18255. context_info_length += mg_str_append(&buffer, end, block);
  18256. }
  18257. if (ctx) {
  18258. /* Declare all variables at begin of the block, to comply
  18259. * with old C standards. */
  18260. char start_time_str[64] = {0};
  18261. char now_str[64] = {0};
  18262. time_t start_time = ctx->start_time;
  18263. time_t now = time(NULL);
  18264. int64_t total_data_read, total_data_written;
  18265. int active_connections = (int)ctx->active_connections;
  18266. int max_active_connections = (int)ctx->max_active_connections;
  18267. int total_connections = (int)ctx->total_connections;
  18268. if (active_connections > max_active_connections) {
  18269. max_active_connections = active_connections;
  18270. }
  18271. if (active_connections > total_connections) {
  18272. total_connections = active_connections;
  18273. }
  18274. /* Connections information */
  18275. mg_snprintf(NULL,
  18276. NULL,
  18277. block,
  18278. sizeof(block),
  18279. ",%s\"connections\" : {%s"
  18280. "\"active\" : %i,%s"
  18281. "\"maxActive\" : %i,%s"
  18282. "\"total\" : %i%s"
  18283. "}",
  18284. eol,
  18285. eol,
  18286. active_connections,
  18287. eol,
  18288. max_active_connections,
  18289. eol,
  18290. total_connections,
  18291. eol);
  18292. context_info_length += mg_str_append(&buffer, end, block);
  18293. /* Queue information */
  18294. #if !defined(ALTERNATIVE_QUEUE)
  18295. mg_snprintf(NULL,
  18296. NULL,
  18297. block,
  18298. sizeof(block),
  18299. ",%s\"queue\" : {%s"
  18300. "\"length\" : %i,%s"
  18301. "\"filled\" : %i,%s"
  18302. "\"maxFilled\" : %i,%s"
  18303. "\"full\" : %s%s"
  18304. "}",
  18305. eol,
  18306. eol,
  18307. ctx->sq_size,
  18308. eol,
  18309. ctx->sq_head - ctx->sq_tail,
  18310. eol,
  18311. ctx->sq_max_fill,
  18312. eol,
  18313. (ctx->sq_blocked ? "true" : "false"),
  18314. eol);
  18315. context_info_length += mg_str_append(&buffer, end, block);
  18316. #endif
  18317. /* Requests information */
  18318. mg_snprintf(NULL,
  18319. NULL,
  18320. block,
  18321. sizeof(block),
  18322. ",%s\"requests\" : {%s"
  18323. "\"total\" : %lu%s"
  18324. "}",
  18325. eol,
  18326. eol,
  18327. (unsigned long)ctx->total_requests,
  18328. eol);
  18329. context_info_length += mg_str_append(&buffer, end, block);
  18330. /* Data information */
  18331. total_data_read =
  18332. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18333. total_data_written =
  18334. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18335. mg_snprintf(NULL,
  18336. NULL,
  18337. block,
  18338. sizeof(block),
  18339. ",%s\"data\" : {%s"
  18340. "\"read\" : %" INT64_FMT ",%s"
  18341. "\"written\" : %" INT64_FMT "%s"
  18342. "}",
  18343. eol,
  18344. eol,
  18345. total_data_read,
  18346. eol,
  18347. total_data_written,
  18348. eol);
  18349. context_info_length += mg_str_append(&buffer, end, block);
  18350. /* Execution time information */
  18351. gmt_time_string(start_time_str,
  18352. sizeof(start_time_str) - 1,
  18353. &start_time);
  18354. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18355. mg_snprintf(NULL,
  18356. NULL,
  18357. block,
  18358. sizeof(block),
  18359. ",%s\"time\" : {%s"
  18360. "\"uptime\" : %.0f,%s"
  18361. "\"start\" : \"%s\",%s"
  18362. "\"now\" : \"%s\"%s"
  18363. "}",
  18364. eol,
  18365. eol,
  18366. difftime(now, start_time),
  18367. eol,
  18368. start_time_str,
  18369. eol,
  18370. now_str,
  18371. eol);
  18372. context_info_length += mg_str_append(&buffer, end, block);
  18373. }
  18374. /* Terminate string */
  18375. if (append_eoobj) {
  18376. strcat(append_eoobj, eoobj);
  18377. }
  18378. context_info_length += sizeof(eoobj) - 1;
  18379. return (int)context_info_length;
  18380. #else
  18381. (void)ctx;
  18382. if ((buffer != NULL) && (buflen > 0)) {
  18383. *buffer = 0;
  18384. }
  18385. return 0;
  18386. #endif
  18387. }
  18388. void
  18389. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18390. {
  18391. /* https://github.com/civetweb/civetweb/issues/727 */
  18392. if (conn != NULL) {
  18393. conn->must_close = 1;
  18394. }
  18395. }
  18396. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18397. /* Get connection information. It can be printed or stored by the caller.
  18398. * Return the size of available information. */
  18399. int
  18400. mg_get_connection_info(const struct mg_context *ctx,
  18401. int idx,
  18402. char *buffer,
  18403. int buflen)
  18404. {
  18405. const struct mg_connection *conn;
  18406. const struct mg_request_info *ri;
  18407. char *end, *append_eoobj = NULL, block[256];
  18408. size_t connection_info_length = 0;
  18409. int state = 0;
  18410. const char *state_str = "unknown";
  18411. #if defined(_WIN32)
  18412. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18413. #else
  18414. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18415. #endif
  18416. if ((buffer == NULL) || (buflen < 1)) {
  18417. buflen = 0;
  18418. end = buffer;
  18419. } else {
  18420. *buffer = 0;
  18421. end = buffer + buflen;
  18422. }
  18423. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18424. /* has enough space to append eoobj */
  18425. append_eoobj = buffer;
  18426. end -= sizeof(eoobj) - 1;
  18427. }
  18428. if ((ctx == NULL) || (idx < 0)) {
  18429. /* Parameter error */
  18430. return 0;
  18431. }
  18432. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18433. /* Out of range */
  18434. return 0;
  18435. }
  18436. /* Take connection [idx]. This connection is not locked in
  18437. * any way, so some other thread might use it. */
  18438. conn = (ctx->worker_connections) + idx;
  18439. /* Initialize output string */
  18440. connection_info_length += mg_str_append(&buffer, end, "{");
  18441. /* Init variables */
  18442. ri = &(conn->request_info);
  18443. #if defined(USE_SERVER_STATS)
  18444. state = conn->conn_state;
  18445. /* State as string */
  18446. switch (state) {
  18447. case 0:
  18448. state_str = "undefined";
  18449. break;
  18450. case 1:
  18451. state_str = "not used";
  18452. break;
  18453. case 2:
  18454. state_str = "init";
  18455. break;
  18456. case 3:
  18457. state_str = "ready";
  18458. break;
  18459. case 4:
  18460. state_str = "processing";
  18461. break;
  18462. case 5:
  18463. state_str = "processed";
  18464. break;
  18465. case 6:
  18466. state_str = "to close";
  18467. break;
  18468. case 7:
  18469. state_str = "closing";
  18470. break;
  18471. case 8:
  18472. state_str = "closed";
  18473. break;
  18474. case 9:
  18475. state_str = "done";
  18476. break;
  18477. }
  18478. #endif
  18479. /* Connection info */
  18480. if ((state >= 3) && (state < 9)) {
  18481. mg_snprintf(NULL,
  18482. NULL,
  18483. block,
  18484. sizeof(block),
  18485. "%s\"connection\" : {%s"
  18486. "\"remote\" : {%s"
  18487. "\"protocol\" : \"%s\",%s"
  18488. "\"addr\" : \"%s\",%s"
  18489. "\"port\" : %u%s"
  18490. "},%s"
  18491. "\"handled_requests\" : %u%s"
  18492. "}",
  18493. eol,
  18494. eol,
  18495. eol,
  18496. get_proto_name(conn),
  18497. eol,
  18498. ri->remote_addr,
  18499. eol,
  18500. ri->remote_port,
  18501. eol,
  18502. eol,
  18503. conn->handled_requests,
  18504. eol);
  18505. connection_info_length += mg_str_append(&buffer, end, block);
  18506. }
  18507. /* Request info */
  18508. if ((state >= 4) && (state < 6)) {
  18509. mg_snprintf(NULL,
  18510. NULL,
  18511. block,
  18512. sizeof(block),
  18513. "%s%s\"request_info\" : {%s"
  18514. "\"method\" : \"%s\",%s"
  18515. "\"uri\" : \"%s\",%s"
  18516. "\"query\" : %s%s%s%s"
  18517. "}",
  18518. (connection_info_length > 1 ? "," : ""),
  18519. eol,
  18520. eol,
  18521. ri->request_method,
  18522. eol,
  18523. ri->request_uri,
  18524. eol,
  18525. ri->query_string ? "\"" : "",
  18526. ri->query_string ? ri->query_string : "null",
  18527. ri->query_string ? "\"" : "",
  18528. eol);
  18529. connection_info_length += mg_str_append(&buffer, end, block);
  18530. }
  18531. /* Execution time information */
  18532. if ((state >= 2) && (state < 9)) {
  18533. char start_time_str[64] = {0};
  18534. char close_time_str[64] = {0};
  18535. time_t start_time = conn->conn_birth_time;
  18536. time_t close_time = 0;
  18537. double time_diff;
  18538. gmt_time_string(start_time_str,
  18539. sizeof(start_time_str) - 1,
  18540. &start_time);
  18541. #if defined(USE_SERVER_STATS)
  18542. close_time = conn->conn_close_time;
  18543. #endif
  18544. if (close_time != 0) {
  18545. time_diff = difftime(close_time, start_time);
  18546. gmt_time_string(close_time_str,
  18547. sizeof(close_time_str) - 1,
  18548. &close_time);
  18549. } else {
  18550. time_t now = time(NULL);
  18551. time_diff = difftime(now, start_time);
  18552. close_time_str[0] = 0; /* or use "now" ? */
  18553. }
  18554. mg_snprintf(NULL,
  18555. NULL,
  18556. block,
  18557. sizeof(block),
  18558. "%s%s\"time\" : {%s"
  18559. "\"uptime\" : %.0f,%s"
  18560. "\"start\" : \"%s\",%s"
  18561. "\"closed\" : \"%s\"%s"
  18562. "}",
  18563. (connection_info_length > 1 ? "," : ""),
  18564. eol,
  18565. eol,
  18566. time_diff,
  18567. eol,
  18568. start_time_str,
  18569. eol,
  18570. close_time_str,
  18571. eol);
  18572. connection_info_length += mg_str_append(&buffer, end, block);
  18573. }
  18574. /* Remote user name */
  18575. if ((ri->remote_user) && (state < 9)) {
  18576. mg_snprintf(NULL,
  18577. NULL,
  18578. block,
  18579. sizeof(block),
  18580. "%s%s\"user\" : {%s"
  18581. "\"name\" : \"%s\",%s"
  18582. "}",
  18583. (connection_info_length > 1 ? "," : ""),
  18584. eol,
  18585. eol,
  18586. ri->remote_user,
  18587. eol);
  18588. connection_info_length += mg_str_append(&buffer, end, block);
  18589. }
  18590. /* Data block */
  18591. if (state >= 3) {
  18592. mg_snprintf(NULL,
  18593. NULL,
  18594. block,
  18595. sizeof(block),
  18596. "%s%s\"data\" : {%s"
  18597. "\"read\" : %" INT64_FMT ",%s"
  18598. "\"written\" : %" INT64_FMT "%s"
  18599. "}",
  18600. (connection_info_length > 1 ? "," : ""),
  18601. eol,
  18602. eol,
  18603. conn->consumed_content,
  18604. eol,
  18605. conn->num_bytes_sent,
  18606. eol);
  18607. connection_info_length += mg_str_append(&buffer, end, block);
  18608. }
  18609. /* State */
  18610. mg_snprintf(NULL,
  18611. NULL,
  18612. block,
  18613. sizeof(block),
  18614. "%s%s\"state\" : \"%s\"",
  18615. (connection_info_length > 1 ? "," : ""),
  18616. eol,
  18617. state_str);
  18618. connection_info_length += mg_str_append(&buffer, end, block);
  18619. /* Terminate string */
  18620. if (append_eoobj) {
  18621. strcat(append_eoobj, eoobj);
  18622. }
  18623. connection_info_length += sizeof(eoobj) - 1;
  18624. return (int)connection_info_length;
  18625. }
  18626. #endif
  18627. /* Initialize this library. This function does not need to be thread safe.
  18628. */
  18629. unsigned
  18630. mg_init_library(unsigned features)
  18631. {
  18632. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18633. unsigned features_inited = features_to_init;
  18634. if (mg_init_library_called <= 0) {
  18635. /* Not initialized yet */
  18636. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18637. return 0;
  18638. }
  18639. }
  18640. mg_global_lock();
  18641. if (mg_init_library_called <= 0) {
  18642. #if defined(_WIN32)
  18643. int file_mutex_init = 1;
  18644. int wsa = 1;
  18645. #else
  18646. int mutexattr_init = 1;
  18647. #endif
  18648. int failed = 1;
  18649. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18650. if (key_create == 0) {
  18651. #if defined(_WIN32)
  18652. file_mutex_init =
  18653. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18654. if (file_mutex_init == 0) {
  18655. /* Start WinSock */
  18656. WSADATA data;
  18657. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18658. }
  18659. #else
  18660. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18661. if (mutexattr_init == 0) {
  18662. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18663. PTHREAD_MUTEX_RECURSIVE);
  18664. }
  18665. #endif
  18666. }
  18667. if (failed) {
  18668. #if defined(_WIN32)
  18669. if (wsa == 0) {
  18670. (void)WSACleanup();
  18671. }
  18672. if (file_mutex_init == 0) {
  18673. (void)pthread_mutex_destroy(&global_log_file_lock);
  18674. }
  18675. #else
  18676. if (mutexattr_init == 0) {
  18677. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18678. }
  18679. #endif
  18680. if (key_create == 0) {
  18681. (void)pthread_key_delete(sTlsKey);
  18682. }
  18683. mg_global_unlock();
  18684. (void)pthread_mutex_destroy(&global_lock_mutex);
  18685. return 0;
  18686. }
  18687. #if defined(USE_LUA)
  18688. lua_init_optional_libraries();
  18689. #endif
  18690. }
  18691. mg_global_unlock();
  18692. #if !defined(NO_SSL)
  18693. if (features_to_init & MG_FEATURES_SSL) {
  18694. if (!mg_ssl_initialized) {
  18695. char ebuf[128];
  18696. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  18697. mg_ssl_initialized = 1;
  18698. } else {
  18699. (void)ebuf;
  18700. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18701. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18702. }
  18703. } else {
  18704. /* ssl already initialized */
  18705. }
  18706. }
  18707. #endif
  18708. mg_global_lock();
  18709. if (mg_init_library_called <= 0) {
  18710. mg_init_library_called = 1;
  18711. } else {
  18712. mg_init_library_called++;
  18713. }
  18714. mg_global_unlock();
  18715. return features_inited;
  18716. }
  18717. /* Un-initialize this library. */
  18718. unsigned
  18719. mg_exit_library(void)
  18720. {
  18721. if (mg_init_library_called <= 0) {
  18722. return 0;
  18723. }
  18724. mg_global_lock();
  18725. mg_init_library_called--;
  18726. if (mg_init_library_called == 0) {
  18727. #if !defined(NO_SSL)
  18728. if (mg_ssl_initialized) {
  18729. uninitialize_ssl();
  18730. mg_ssl_initialized = 0;
  18731. }
  18732. #endif
  18733. #if defined(_WIN32)
  18734. (void)WSACleanup();
  18735. (void)pthread_mutex_destroy(&global_log_file_lock);
  18736. #else
  18737. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18738. #endif
  18739. (void)pthread_key_delete(sTlsKey);
  18740. #if defined(USE_LUA)
  18741. lua_exit_optional_libraries();
  18742. #endif
  18743. mg_global_unlock();
  18744. (void)pthread_mutex_destroy(&global_lock_mutex);
  18745. return 1;
  18746. }
  18747. mg_global_unlock();
  18748. return 1;
  18749. }
  18750. /* End of civetweb.c */