civetweb.c 591 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258
  1. /* Copyright (c) 2013-2021 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. #include <stdlib.h>
  220. #define DEBUG_ASSERT(cond) \
  221. do { \
  222. if (!(cond)) { \
  223. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  224. exit(2); /* Exit with error */ \
  225. } \
  226. } while (0)
  227. #else
  228. #define DEBUG_ASSERT(cond)
  229. #endif /* DEBUG */
  230. #endif
  231. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  232. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  233. __attribute__((no_instrument_function));
  234. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void
  237. __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. {
  239. if ((void *)this_fn != (void *)printf) {
  240. printf("E %p %p\n", this_fn, call_site);
  241. }
  242. }
  243. void
  244. __cyg_profile_func_exit(void *this_fn, void *call_site)
  245. {
  246. if ((void *)this_fn != (void *)printf) {
  247. printf("X %p %p\n", this_fn, call_site);
  248. }
  249. }
  250. #endif
  251. #if !defined(IGNORE_UNUSED_RESULT)
  252. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  253. #endif
  254. #if defined(__GNUC__) || defined(__MINGW32__)
  255. /* GCC unused function attribute seems fundamentally broken.
  256. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  257. * OR UNUSED" for individual functions failed.
  258. * Either the compiler creates an "unused-function" warning if a
  259. * function is not marked with __attribute__((unused)).
  260. * On the other hand, if the function is marked with this attribute,
  261. * but is used, the compiler raises a completely idiotic
  262. * "used-but-marked-unused" warning - and
  263. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  264. * raises error: unknown option after "#pragma GCC diagnostic".
  265. * Disable this warning completely, until the GCC guys sober up
  266. * again.
  267. */
  268. #pragma GCC diagnostic ignored "-Wunused-function"
  269. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  270. #else
  271. #define FUNCTION_MAY_BE_UNUSED
  272. #endif
  273. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  274. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  275. #include <errno.h>
  276. #include <fcntl.h>
  277. #include <signal.h>
  278. #include <stdlib.h>
  279. #include <sys/stat.h>
  280. #include <sys/types.h>
  281. #endif /* !_WIN32_WCE */
  282. #if defined(__clang__)
  283. /* When using -Weverything, clang does not accept it's own headers
  284. * in a release build configuration. Disable what is too much in
  285. * -Weverything. */
  286. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  287. #endif
  288. #if defined(__GNUC__) || defined(__MINGW32__)
  289. /* Who on earth came to the conclusion, using __DATE__ should rise
  290. * an "expansion of date or time macro is not reproducible"
  291. * warning. That's exactly what was intended by using this macro.
  292. * Just disable this nonsense warning. */
  293. /* And disabling them does not work either:
  294. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  295. * #pragma clang diagnostic ignored "-Wdate-time"
  296. * So we just have to disable ALL warnings for some lines
  297. * of code.
  298. * This seems to be a known GCC bug, not resolved since 2012:
  299. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  300. */
  301. #endif
  302. #if defined(__MACH__) /* Apple OSX section */
  303. #if defined(__clang__)
  304. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  305. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  306. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  307. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  308. #endif
  309. #endif
  310. #ifndef CLOCK_MONOTONIC
  311. #define CLOCK_MONOTONIC (1)
  312. #endif
  313. #ifndef CLOCK_REALTIME
  314. #define CLOCK_REALTIME (2)
  315. #endif
  316. #include <mach/clock.h>
  317. #include <mach/mach.h>
  318. #include <mach/mach_time.h>
  319. #include <sys/errno.h>
  320. #include <sys/time.h>
  321. /* clock_gettime is not implemented on OSX prior to 10.12 */
  322. static int
  323. _civet_clock_gettime(int clk_id, struct timespec *t)
  324. {
  325. memset(t, 0, sizeof(*t));
  326. if (clk_id == CLOCK_REALTIME) {
  327. struct timeval now;
  328. int rv = gettimeofday(&now, NULL);
  329. if (rv) {
  330. return rv;
  331. }
  332. t->tv_sec = now.tv_sec;
  333. t->tv_nsec = now.tv_usec * 1000;
  334. return 0;
  335. } else if (clk_id == CLOCK_MONOTONIC) {
  336. static uint64_t clock_start_time = 0;
  337. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  338. uint64_t now = mach_absolute_time();
  339. if (clock_start_time == 0) {
  340. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  341. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  342. /* appease "unused variable" warning for release builds */
  343. (void)mach_status;
  344. clock_start_time = now;
  345. }
  346. now = (uint64_t)((double)(now - clock_start_time)
  347. * (double)timebase_ifo.numer
  348. / (double)timebase_ifo.denom);
  349. t->tv_sec = now / 1000000000;
  350. t->tv_nsec = now % 1000000000;
  351. return 0;
  352. }
  353. return -1; /* EINVAL - Clock ID is unknown */
  354. }
  355. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  356. #if defined(__CLOCK_AVAILABILITY)
  357. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  358. * declared but it may be NULL at runtime. So we need to check before using
  359. * it. */
  360. static int
  361. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  362. {
  363. if (clock_gettime) {
  364. return clock_gettime(clk_id, t);
  365. }
  366. return _civet_clock_gettime(clk_id, t);
  367. }
  368. #define clock_gettime _civet_safe_clock_gettime
  369. #else
  370. #define clock_gettime _civet_clock_gettime
  371. #endif
  372. #endif
  373. #if !defined(_WIN32)
  374. /* Unix might return different error codes indicating to try again.
  375. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  376. * decades ago, but better check both and let the compile optimize it. */
  377. #define ERROR_TRY_AGAIN(err) \
  378. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  379. #endif
  380. #if defined(USE_ZLIB)
  381. #include "zconf.h"
  382. #include "zlib.h"
  383. #endif
  384. /********************************************************************/
  385. /* CivetWeb configuration defines */
  386. /********************************************************************/
  387. /* Maximum number of threads that can be configured.
  388. * The number of threads actually created depends on the "num_threads"
  389. * configuration parameter, but this is the upper limit. */
  390. #if !defined(MAX_WORKER_THREADS)
  391. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  392. #endif
  393. /* Timeout interval for select/poll calls.
  394. * The timeouts depend on "*_timeout_ms" configuration values, but long
  395. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  396. * This reduces the time required to stop the server. */
  397. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  398. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  399. #endif
  400. /* Do not try to compress files smaller than this limit. */
  401. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  402. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  403. #endif
  404. #if !defined(PASSWORDS_FILE_NAME)
  405. #define PASSWORDS_FILE_NAME ".htpasswd"
  406. #endif
  407. /* Initial buffer size for all CGI environment variables. In case there is
  408. * not enough space, another block is allocated. */
  409. #if !defined(CGI_ENVIRONMENT_SIZE)
  410. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  411. #endif
  412. /* Maximum number of environment variables. */
  413. #if !defined(MAX_CGI_ENVIR_VARS)
  414. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  415. #endif
  416. /* General purpose buffer size. */
  417. #if !defined(MG_BUF_LEN) /* in bytes */
  418. #define MG_BUF_LEN (1024 * 8)
  419. #endif
  420. /********************************************************************/
  421. /* Helper makros */
  422. #if !defined(ARRAY_SIZE)
  423. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  424. #endif
  425. #include <stdint.h>
  426. /* Standard defines */
  427. #if !defined(INT64_MAX)
  428. #define INT64_MAX (9223372036854775807)
  429. #endif
  430. #define SHUTDOWN_RD (0)
  431. #define SHUTDOWN_WR (1)
  432. #define SHUTDOWN_BOTH (2)
  433. mg_static_assert(MAX_WORKER_THREADS >= 1,
  434. "worker threads must be a positive number");
  435. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  436. "size_t data type size check");
  437. #if defined(_WIN32) /* WINDOWS include block */
  438. #include <malloc.h> /* *alloc( */
  439. #include <stdlib.h> /* *alloc( */
  440. #include <time.h> /* struct timespec */
  441. #include <windows.h>
  442. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  443. #include <ws2tcpip.h>
  444. typedef const char *SOCK_OPT_TYPE;
  445. /* For a detailed description of these *_PATH_MAX defines, see
  446. * https://github.com/civetweb/civetweb/issues/937. */
  447. /* UTF8_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 UTF8_PATH_MAX (3 * 260)
  450. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  451. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  452. #define UTF16_PATH_MAX (260)
  453. #if !defined(_IN_PORT_T)
  454. #if !defined(in_port_t)
  455. #define in_port_t u_short
  456. #endif
  457. #endif
  458. #if defined(_WIN32_WCE)
  459. #error "WinCE support has ended"
  460. #endif
  461. #include <direct.h>
  462. #include <io.h>
  463. #include <process.h>
  464. #define MAKEUQUAD(lo, hi) \
  465. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  466. #define RATE_DIFF (10000000) /* 100 nsecs */
  467. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  468. #define SYS2UNIX_TIME(lo, hi) \
  469. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  470. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  471. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  472. * Also use _strtoui64 on modern M$ compilers */
  473. #if defined(_MSC_VER)
  474. #if (_MSC_VER < 1300)
  475. #define STRX(x) #x
  476. #define STR(x) STRX(x)
  477. #define __func__ __FILE__ ":" STR(__LINE__)
  478. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  479. #define strtoll(x, y, z) (_atoi64(x))
  480. #else
  481. #define __func__ __FUNCTION__
  482. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  483. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  484. #endif
  485. #endif /* _MSC_VER */
  486. /* mg_qsort */
  487. #if defined(_MSC_VER)
  488. /* Windoes uses qsort_s instead of qsort_r */
  489. #define mg_qsort(base, num, with, comp, arg) \
  490. qsort_s(base, \
  491. num, \
  492. with, \
  493. (int(__cdecl *)(void *, const void *, const void *))comp, \
  494. arg)
  495. #elif defined(__linux__)
  496. #define mg_qsort(base, num, with, comp, arg) \
  497. qsort_r(base, num, with, comp, arg) #else
  498. #define mg_qsort(base, num, with, comp, arg)
  499. #endif
  500. #define ERRNO ((int)(GetLastError()))
  501. #define NO_SOCKLEN_T
  502. #if defined(_WIN64) || defined(__MINGW64__)
  503. #if !defined(SSL_LIB)
  504. #if defined(OPENSSL_API_3_0)
  505. #define SSL_LIB "libssl-3-x64.dll"
  506. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  507. #endif
  508. #if defined(OPENSSL_API_1_1)
  509. #define SSL_LIB "libssl-1_1-x64.dll"
  510. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  511. #endif /* OPENSSL_API_1_1 */
  512. #if defined(OPENSSL_API_1_0)
  513. #define SSL_LIB "ssleay64.dll"
  514. #define CRYPTO_LIB "libeay64.dll"
  515. #endif /* OPENSSL_API_1_0 */
  516. #endif
  517. #else /* defined(_WIN64) || defined(__MINGW64__) */
  518. #if !defined(SSL_LIB)
  519. #if defined(OPENSSL_API_3_0)
  520. #define SSL_LIB "libssl-3.dll"
  521. #define CRYPTO_LIB "libcrypto-3.dll"
  522. #endif
  523. #if defined(OPENSSL_API_1_1)
  524. #define SSL_LIB "libssl-1_1.dll"
  525. #define CRYPTO_LIB "libcrypto-1_1.dll"
  526. #endif /* OPENSSL_API_1_1 */
  527. #if defined(OPENSSL_API_1_0)
  528. #define SSL_LIB "ssleay32.dll"
  529. #define CRYPTO_LIB "libeay32.dll"
  530. #endif /* OPENSSL_API_1_0 */
  531. #endif /* SSL_LIB */
  532. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  533. #define O_NONBLOCK (0)
  534. #if !defined(W_OK)
  535. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  536. #endif
  537. #define _POSIX_
  538. #define INT64_FMT "I64d"
  539. #define UINT64_FMT "I64u"
  540. #define WINCDECL __cdecl
  541. #define vsnprintf_impl _vsnprintf
  542. #define access _access
  543. #define mg_sleep(x) (Sleep(x))
  544. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  545. #if !defined(popen)
  546. #define popen(x, y) (_popen(x, y))
  547. #endif
  548. #if !defined(pclose)
  549. #define pclose(x) (_pclose(x))
  550. #endif
  551. #define close(x) (_close(x))
  552. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  553. #define RTLD_LAZY (0)
  554. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  555. #define fdopen(x, y) (_fdopen((x), (y)))
  556. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  557. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  558. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  559. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  560. #define sleep(x) (Sleep((x)*1000))
  561. #define rmdir(x) (_rmdir(x))
  562. #if defined(_WIN64) || !defined(__MINGW32__)
  563. /* Only MinGW 32 bit is missing this function */
  564. #define timegm(x) (_mkgmtime(x))
  565. #else
  566. time_t timegm(struct tm *tm);
  567. #define NEED_TIMEGM
  568. #endif
  569. #if !defined(fileno)
  570. #define fileno(x) (_fileno(x))
  571. #endif /* !fileno MINGW #defines fileno */
  572. typedef struct {
  573. CRITICAL_SECTION sec; /* Immovable */
  574. } pthread_mutex_t;
  575. typedef DWORD pthread_key_t;
  576. typedef HANDLE pthread_t;
  577. typedef struct {
  578. pthread_mutex_t threadIdSec;
  579. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  580. } pthread_cond_t;
  581. #if !defined(__clockid_t_defined)
  582. typedef DWORD clockid_t;
  583. #endif
  584. #if !defined(CLOCK_MONOTONIC)
  585. #define CLOCK_MONOTONIC (1)
  586. #endif
  587. #if !defined(CLOCK_REALTIME)
  588. #define CLOCK_REALTIME (2)
  589. #endif
  590. #if !defined(CLOCK_THREAD)
  591. #define CLOCK_THREAD (3)
  592. #endif
  593. #if !defined(CLOCK_PROCESS)
  594. #define CLOCK_PROCESS (4)
  595. #endif
  596. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  597. #define _TIMESPEC_DEFINED
  598. #endif
  599. #if !defined(_TIMESPEC_DEFINED)
  600. struct timespec {
  601. time_t tv_sec; /* seconds */
  602. long tv_nsec; /* nanoseconds */
  603. };
  604. #endif
  605. #if !defined(WIN_PTHREADS_TIME_H)
  606. #define MUST_IMPLEMENT_CLOCK_GETTIME
  607. #endif
  608. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  609. #define clock_gettime mg_clock_gettime
  610. static int
  611. clock_gettime(clockid_t clk_id, struct timespec *tp)
  612. {
  613. FILETIME ft;
  614. ULARGE_INTEGER li, li2;
  615. BOOL ok = FALSE;
  616. double d;
  617. static double perfcnt_per_sec = 0.0;
  618. static BOOL initialized = FALSE;
  619. if (!initialized) {
  620. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  621. perfcnt_per_sec = 1.0 / li.QuadPart;
  622. initialized = TRUE;
  623. }
  624. if (tp) {
  625. memset(tp, 0, sizeof(*tp));
  626. if (clk_id == CLOCK_REALTIME) {
  627. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  628. GetSystemTimeAsFileTime(&ft);
  629. li.LowPart = ft.dwLowDateTime;
  630. li.HighPart = ft.dwHighDateTime;
  631. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  632. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  633. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  634. ok = TRUE;
  635. /* END: CLOCK_REALTIME */
  636. } else if (clk_id == CLOCK_MONOTONIC) {
  637. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  638. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  639. d = li.QuadPart * perfcnt_per_sec;
  640. tp->tv_sec = (time_t)d;
  641. d -= (double)tp->tv_sec;
  642. tp->tv_nsec = (long)(d * 1.0E9);
  643. ok = TRUE;
  644. /* END: CLOCK_MONOTONIC */
  645. } else if (clk_id == CLOCK_THREAD) {
  646. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  647. FILETIME t_create, t_exit, t_kernel, t_user;
  648. if (GetThreadTimes(GetCurrentThread(),
  649. &t_create,
  650. &t_exit,
  651. &t_kernel,
  652. &t_user)) {
  653. li.LowPart = t_user.dwLowDateTime;
  654. li.HighPart = t_user.dwHighDateTime;
  655. li2.LowPart = t_kernel.dwLowDateTime;
  656. li2.HighPart = t_kernel.dwHighDateTime;
  657. li.QuadPart += li2.QuadPart;
  658. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  659. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  660. ok = TRUE;
  661. }
  662. /* END: CLOCK_THREAD */
  663. } else if (clk_id == CLOCK_PROCESS) {
  664. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  665. FILETIME t_create, t_exit, t_kernel, t_user;
  666. if (GetProcessTimes(GetCurrentProcess(),
  667. &t_create,
  668. &t_exit,
  669. &t_kernel,
  670. &t_user)) {
  671. li.LowPart = t_user.dwLowDateTime;
  672. li.HighPart = t_user.dwHighDateTime;
  673. li2.LowPart = t_kernel.dwLowDateTime;
  674. li2.HighPart = t_kernel.dwHighDateTime;
  675. li.QuadPart += li2.QuadPart;
  676. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  677. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  678. ok = TRUE;
  679. }
  680. /* END: CLOCK_PROCESS */
  681. } else {
  682. /* BEGIN: unknown clock */
  683. /* ok = FALSE; already set by init */
  684. /* END: unknown clock */
  685. }
  686. }
  687. return ok ? 0 : -1;
  688. }
  689. #endif
  690. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  691. static int pthread_mutex_lock(pthread_mutex_t *);
  692. static int pthread_mutex_unlock(pthread_mutex_t *);
  693. static void path_to_unicode(const struct mg_connection *conn,
  694. const char *path,
  695. wchar_t *wbuf,
  696. size_t wbuf_len);
  697. /* All file operations need to be rewritten to solve #246. */
  698. struct mg_file;
  699. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  700. /* POSIX dirent interface */
  701. struct dirent {
  702. char d_name[UTF8_PATH_MAX];
  703. };
  704. typedef struct DIR {
  705. HANDLE handle;
  706. WIN32_FIND_DATAW info;
  707. struct dirent result;
  708. } DIR;
  709. #if defined(HAVE_POLL)
  710. #define mg_pollfd pollfd
  711. #else
  712. struct mg_pollfd {
  713. SOCKET fd;
  714. short events;
  715. short revents;
  716. };
  717. #endif
  718. /* Mark required libraries */
  719. #if defined(_MSC_VER)
  720. #pragma comment(lib, "Ws2_32.lib")
  721. #endif
  722. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  723. #include <inttypes.h>
  724. /* Linux & co. internally use UTF8 */
  725. #define UTF8_PATH_MAX (PATH_MAX)
  726. typedef const void *SOCK_OPT_TYPE;
  727. #if defined(ANDROID)
  728. typedef unsigned short int in_port_t;
  729. #endif
  730. #if !defined(__ZEPHYR__)
  731. #include <arpa/inet.h>
  732. #include <ctype.h>
  733. #include <dirent.h>
  734. #include <grp.h>
  735. #include <limits.h>
  736. #include <netdb.h>
  737. #include <netinet/in.h>
  738. #include <netinet/tcp.h>
  739. #include <pthread.h>
  740. #include <pwd.h>
  741. #include <stdarg.h>
  742. #include <stddef.h>
  743. #include <stdio.h>
  744. #include <stdlib.h>
  745. #include <string.h>
  746. #include <sys/poll.h>
  747. #include <sys/socket.h>
  748. #include <sys/time.h>
  749. #include <sys/utsname.h>
  750. #include <sys/wait.h>
  751. #include <time.h>
  752. #include <unistd.h>
  753. #if defined(USE_X_DOM_SOCKET)
  754. #include <sys/un.h>
  755. #endif
  756. #endif
  757. #define vsnprintf_impl vsnprintf
  758. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  759. #include <dlfcn.h>
  760. #endif
  761. #if defined(__MACH__)
  762. #define SSL_LIB "libssl.dylib"
  763. #define CRYPTO_LIB "libcrypto.dylib"
  764. #else
  765. #if !defined(SSL_LIB)
  766. #define SSL_LIB "libssl.so"
  767. #endif
  768. #if !defined(CRYPTO_LIB)
  769. #define CRYPTO_LIB "libcrypto.so"
  770. #endif
  771. #endif
  772. #if !defined(O_BINARY)
  773. #define O_BINARY (0)
  774. #endif /* O_BINARY */
  775. #define closesocket(a) (close(a))
  776. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  777. #define mg_remove(conn, x) (remove(x))
  778. #define mg_sleep(x) (usleep((x)*1000))
  779. #define mg_opendir(conn, x) (opendir(x))
  780. #define mg_closedir(x) (closedir(x))
  781. #define mg_readdir(x) (readdir(x))
  782. #define ERRNO (errno)
  783. #define INVALID_SOCKET (-1)
  784. #define INT64_FMT PRId64
  785. #define UINT64_FMT PRIu64
  786. typedef int SOCKET;
  787. #define WINCDECL
  788. #if defined(__hpux)
  789. /* HPUX 11 does not have monotonic, fall back to realtime */
  790. #if !defined(CLOCK_MONOTONIC)
  791. #define CLOCK_MONOTONIC CLOCK_REALTIME
  792. #endif
  793. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  794. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  795. * the prototypes use int* rather than socklen_t* which matches the
  796. * actual library expectation. When called with the wrong size arg
  797. * accept() returns a zero client inet addr and check_acl() always
  798. * fails. Since socklen_t is widely used below, just force replace
  799. * their typedef with int. - DTL
  800. */
  801. #define socklen_t int
  802. #endif /* hpux */
  803. #define mg_pollfd pollfd
  804. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  805. /* In case our C library is missing "timegm", provide an implementation */
  806. #if defined(NEED_TIMEGM)
  807. static inline int
  808. is_leap(int y)
  809. {
  810. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  811. }
  812. static inline int
  813. count_leap(int y)
  814. {
  815. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  816. }
  817. time_t
  818. timegm(struct tm *tm)
  819. {
  820. static const unsigned short ydays[] = {
  821. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  822. int year = tm->tm_year + 1900;
  823. int mon = tm->tm_mon;
  824. int mday = tm->tm_mday - 1;
  825. int hour = tm->tm_hour;
  826. int min = tm->tm_min;
  827. int sec = tm->tm_sec;
  828. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  829. || (mday >= ydays[mon + 1] - ydays[mon]
  830. + (mon == 1 && is_leap(year) ? 1 : 0))
  831. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  832. return -1;
  833. time_t res = year - 1970;
  834. res *= 365;
  835. res += mday;
  836. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  837. res += count_leap(year);
  838. res *= 24;
  839. res += hour;
  840. res *= 60;
  841. res += min;
  842. res *= 60;
  843. res += sec;
  844. return res;
  845. }
  846. #endif /* NEED_TIMEGM */
  847. /* va_copy should always be a macro, C99 and C++11 - DTL */
  848. #if !defined(va_copy)
  849. #define va_copy(x, y) ((x) = (y))
  850. #endif
  851. #if defined(_WIN32)
  852. /* Create substitutes for POSIX functions in Win32. */
  853. #if defined(GCC_DIAGNOSTIC)
  854. /* Show no warning in case system functions are not used. */
  855. #pragma GCC diagnostic push
  856. #pragma GCC diagnostic ignored "-Wunused-function"
  857. #endif
  858. static pthread_mutex_t global_log_file_lock;
  859. FUNCTION_MAY_BE_UNUSED
  860. static DWORD
  861. pthread_self(void)
  862. {
  863. return GetCurrentThreadId();
  864. }
  865. FUNCTION_MAY_BE_UNUSED
  866. static int
  867. pthread_key_create(
  868. pthread_key_t *key,
  869. void (*_ignored)(void *) /* destructor not supported for Windows */
  870. )
  871. {
  872. (void)_ignored;
  873. if ((key != 0)) {
  874. *key = TlsAlloc();
  875. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  876. }
  877. return -2;
  878. }
  879. FUNCTION_MAY_BE_UNUSED
  880. static int
  881. pthread_key_delete(pthread_key_t key)
  882. {
  883. return TlsFree(key) ? 0 : 1;
  884. }
  885. FUNCTION_MAY_BE_UNUSED
  886. static int
  887. pthread_setspecific(pthread_key_t key, void *value)
  888. {
  889. return TlsSetValue(key, value) ? 0 : 1;
  890. }
  891. FUNCTION_MAY_BE_UNUSED
  892. static void *
  893. pthread_getspecific(pthread_key_t key)
  894. {
  895. return TlsGetValue(key);
  896. }
  897. #if defined(GCC_DIAGNOSTIC)
  898. /* Enable unused function warning again */
  899. #pragma GCC diagnostic pop
  900. #endif
  901. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  902. #else
  903. static pthread_mutexattr_t pthread_mutex_attr;
  904. #endif /* _WIN32 */
  905. #if defined(GCC_DIAGNOSTIC)
  906. /* Show no warning in case system functions are not used. */
  907. #pragma GCC diagnostic push
  908. #pragma GCC diagnostic ignored "-Wunused-function"
  909. #endif /* defined(GCC_DIAGNOSTIC) */
  910. #if defined(__clang__)
  911. /* Show no warning in case system functions are not used. */
  912. #pragma clang diagnostic push
  913. #pragma clang diagnostic ignored "-Wunused-function"
  914. #endif
  915. static pthread_mutex_t global_lock_mutex;
  916. FUNCTION_MAY_BE_UNUSED
  917. static void
  918. mg_global_lock(void)
  919. {
  920. (void)pthread_mutex_lock(&global_lock_mutex);
  921. }
  922. FUNCTION_MAY_BE_UNUSED
  923. static void
  924. mg_global_unlock(void)
  925. {
  926. (void)pthread_mutex_unlock(&global_lock_mutex);
  927. }
  928. #if defined(_WIN64)
  929. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  930. #elif defined(_WIN32)
  931. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  932. #endif
  933. /* Atomic functions working on ptrdiff_t ("signed size_t").
  934. * Operations: Increment, Decrement, Add, Maximum.
  935. * Up to size_t, they do not an atomic "load" operation.
  936. */
  937. FUNCTION_MAY_BE_UNUSED
  938. static ptrdiff_t
  939. mg_atomic_inc(volatile ptrdiff_t *addr)
  940. {
  941. ptrdiff_t ret;
  942. #if defined(_WIN64) && !defined(NO_ATOMICS)
  943. ret = InterlockedIncrement64(addr);
  944. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  945. ret = InterlockedIncrement(addr);
  946. #elif defined(__GNUC__) \
  947. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  948. && !defined(NO_ATOMICS)
  949. ret = __sync_add_and_fetch(addr, 1);
  950. #else
  951. mg_global_lock();
  952. ret = (++(*addr));
  953. mg_global_unlock();
  954. #endif
  955. return ret;
  956. }
  957. FUNCTION_MAY_BE_UNUSED
  958. static ptrdiff_t
  959. mg_atomic_dec(volatile ptrdiff_t *addr)
  960. {
  961. ptrdiff_t ret;
  962. #if defined(_WIN64) && !defined(NO_ATOMICS)
  963. ret = InterlockedDecrement64(addr);
  964. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  965. ret = InterlockedDecrement(addr);
  966. #elif defined(__GNUC__) \
  967. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  968. && !defined(NO_ATOMICS)
  969. ret = __sync_sub_and_fetch(addr, 1);
  970. #else
  971. mg_global_lock();
  972. ret = (--(*addr));
  973. mg_global_unlock();
  974. #endif
  975. return ret;
  976. }
  977. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  978. static ptrdiff_t
  979. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  980. {
  981. ptrdiff_t ret;
  982. #if defined(_WIN64) && !defined(NO_ATOMICS)
  983. ret = InterlockedAdd64(addr, value);
  984. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  985. ret = InterlockedExchangeAdd(addr, value) + value;
  986. #elif defined(__GNUC__) \
  987. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  988. && !defined(NO_ATOMICS)
  989. ret = __sync_add_and_fetch(addr, value);
  990. #else
  991. mg_global_lock();
  992. *addr += value;
  993. ret = (*addr);
  994. mg_global_unlock();
  995. #endif
  996. return ret;
  997. }
  998. FUNCTION_MAY_BE_UNUSED
  999. static ptrdiff_t
  1000. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1001. ptrdiff_t oldval,
  1002. ptrdiff_t newval)
  1003. {
  1004. ptrdiff_t ret;
  1005. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1006. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1007. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1008. ret = InterlockedCompareExchange(addr, newval, oldval);
  1009. #elif defined(__GNUC__) \
  1010. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1011. && !defined(NO_ATOMICS)
  1012. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1013. #else
  1014. mg_global_lock();
  1015. ret = *addr;
  1016. if ((ret != newval) && (ret == oldval)) {
  1017. *addr = newval;
  1018. }
  1019. mg_global_unlock();
  1020. #endif
  1021. return ret;
  1022. }
  1023. static void
  1024. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1025. {
  1026. register ptrdiff_t tmp = *addr;
  1027. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1028. while (tmp < value) {
  1029. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1030. }
  1031. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1032. while (tmp < value) {
  1033. tmp = InterlockedCompareExchange(addr, value, tmp);
  1034. }
  1035. #elif defined(__GNUC__) \
  1036. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1037. && !defined(NO_ATOMICS)
  1038. while (tmp < value) {
  1039. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1040. }
  1041. #else
  1042. mg_global_lock();
  1043. if (*addr < value) {
  1044. *addr = value;
  1045. }
  1046. mg_global_unlock();
  1047. #endif
  1048. }
  1049. static int64_t
  1050. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1051. {
  1052. int64_t ret;
  1053. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1054. ret = InterlockedAdd64(addr, value);
  1055. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1056. ret = InterlockedExchangeAdd64(addr, value) + value;
  1057. #elif defined(__GNUC__) \
  1058. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1059. && !defined(NO_ATOMICS)
  1060. ret = __sync_add_and_fetch(addr, value);
  1061. #else
  1062. mg_global_lock();
  1063. *addr += value;
  1064. ret = (*addr);
  1065. mg_global_unlock();
  1066. #endif
  1067. return ret;
  1068. }
  1069. #endif
  1070. #if defined(GCC_DIAGNOSTIC)
  1071. /* Show no warning in case system functions are not used. */
  1072. #pragma GCC diagnostic pop
  1073. #endif /* defined(GCC_DIAGNOSTIC) */
  1074. #if defined(__clang__)
  1075. /* Show no warning in case system functions are not used. */
  1076. #pragma clang diagnostic pop
  1077. #endif
  1078. #if defined(USE_SERVER_STATS)
  1079. struct mg_memory_stat {
  1080. volatile ptrdiff_t totalMemUsed;
  1081. volatile ptrdiff_t maxMemUsed;
  1082. volatile ptrdiff_t blockCount;
  1083. };
  1084. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1085. static void *
  1086. mg_malloc_ex(size_t size,
  1087. struct mg_context *ctx,
  1088. const char *file,
  1089. unsigned line)
  1090. {
  1091. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1092. void *memory = 0;
  1093. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1094. #if defined(MEMORY_DEBUGGING)
  1095. char mallocStr[256];
  1096. #else
  1097. (void)file;
  1098. (void)line;
  1099. #endif
  1100. if (data) {
  1101. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1102. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1103. mg_atomic_inc(&mstat->blockCount);
  1104. ((uintptr_t *)data)[0] = size;
  1105. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1106. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1107. }
  1108. #if defined(MEMORY_DEBUGGING)
  1109. sprintf(mallocStr,
  1110. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1111. memory,
  1112. (unsigned long)size,
  1113. (unsigned long)mstat->totalMemUsed,
  1114. (unsigned long)mstat->blockCount,
  1115. file,
  1116. line);
  1117. DEBUG_TRACE("%s", mallocStr);
  1118. #endif
  1119. return memory;
  1120. }
  1121. static void *
  1122. mg_calloc_ex(size_t count,
  1123. size_t size,
  1124. struct mg_context *ctx,
  1125. const char *file,
  1126. unsigned line)
  1127. {
  1128. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1129. if (data) {
  1130. memset(data, 0, size * count);
  1131. }
  1132. return data;
  1133. }
  1134. static void
  1135. mg_free_ex(void *memory, const char *file, unsigned line)
  1136. {
  1137. #if defined(MEMORY_DEBUGGING)
  1138. char mallocStr[256];
  1139. #else
  1140. (void)file;
  1141. (void)line;
  1142. #endif
  1143. if (memory) {
  1144. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1145. uintptr_t size = ((uintptr_t *)data)[0];
  1146. struct mg_memory_stat *mstat =
  1147. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1148. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1149. mg_atomic_dec(&mstat->blockCount);
  1150. #if defined(MEMORY_DEBUGGING)
  1151. sprintf(mallocStr,
  1152. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1153. memory,
  1154. (unsigned long)size,
  1155. (unsigned long)mstat->totalMemUsed,
  1156. (unsigned long)mstat->blockCount,
  1157. file,
  1158. line);
  1159. DEBUG_TRACE("%s", mallocStr);
  1160. #endif
  1161. free(data);
  1162. }
  1163. }
  1164. static void *
  1165. mg_realloc_ex(void *memory,
  1166. size_t newsize,
  1167. struct mg_context *ctx,
  1168. const char *file,
  1169. unsigned line)
  1170. {
  1171. void *data;
  1172. void *_realloc;
  1173. uintptr_t oldsize;
  1174. #if defined(MEMORY_DEBUGGING)
  1175. char mallocStr[256];
  1176. #else
  1177. (void)file;
  1178. (void)line;
  1179. #endif
  1180. if (newsize) {
  1181. if (memory) {
  1182. /* Reallocate existing block */
  1183. struct mg_memory_stat *mstat;
  1184. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1185. oldsize = ((uintptr_t *)data)[0];
  1186. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1187. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1188. if (_realloc) {
  1189. data = _realloc;
  1190. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1191. #if defined(MEMORY_DEBUGGING)
  1192. sprintf(mallocStr,
  1193. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1194. memory,
  1195. (unsigned long)oldsize,
  1196. (unsigned long)mstat->totalMemUsed,
  1197. (unsigned long)mstat->blockCount,
  1198. file,
  1199. line);
  1200. DEBUG_TRACE("%s", mallocStr);
  1201. #endif
  1202. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1203. #if defined(MEMORY_DEBUGGING)
  1204. sprintf(mallocStr,
  1205. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1206. memory,
  1207. (unsigned long)newsize,
  1208. (unsigned long)mstat->totalMemUsed,
  1209. (unsigned long)mstat->blockCount,
  1210. file,
  1211. line);
  1212. DEBUG_TRACE("%s", mallocStr);
  1213. #endif
  1214. *(uintptr_t *)data = newsize;
  1215. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1216. } else {
  1217. #if defined(MEMORY_DEBUGGING)
  1218. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1219. #endif
  1220. return _realloc;
  1221. }
  1222. } else {
  1223. /* Allocate new block */
  1224. data = mg_malloc_ex(newsize, ctx, file, line);
  1225. }
  1226. } else {
  1227. /* Free existing block */
  1228. data = 0;
  1229. mg_free_ex(memory, file, line);
  1230. }
  1231. return data;
  1232. }
  1233. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1234. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1235. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1236. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1237. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1238. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1239. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1240. #else /* USE_SERVER_STATS */
  1241. static __inline void *
  1242. mg_malloc(size_t a)
  1243. {
  1244. return malloc(a);
  1245. }
  1246. static __inline void *
  1247. mg_calloc(size_t a, size_t b)
  1248. {
  1249. return calloc(a, b);
  1250. }
  1251. static __inline void *
  1252. mg_realloc(void *a, size_t b)
  1253. {
  1254. return realloc(a, b);
  1255. }
  1256. static __inline void
  1257. mg_free(void *a)
  1258. {
  1259. free(a);
  1260. }
  1261. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1262. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1263. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1264. #define mg_free_ctx(a, c) mg_free(a)
  1265. #endif /* USE_SERVER_STATS */
  1266. static void mg_vsnprintf(const struct mg_connection *conn,
  1267. int *truncated,
  1268. char *buf,
  1269. size_t buflen,
  1270. const char *fmt,
  1271. va_list ap);
  1272. static void mg_snprintf(const struct mg_connection *conn,
  1273. int *truncated,
  1274. char *buf,
  1275. size_t buflen,
  1276. PRINTF_FORMAT_STRING(const char *fmt),
  1277. ...) PRINTF_ARGS(5, 6);
  1278. /* This following lines are just meant as a reminder to use the mg-functions
  1279. * for memory management */
  1280. #if defined(malloc)
  1281. #undef malloc
  1282. #endif
  1283. #if defined(calloc)
  1284. #undef calloc
  1285. #endif
  1286. #if defined(realloc)
  1287. #undef realloc
  1288. #endif
  1289. #if defined(free)
  1290. #undef free
  1291. #endif
  1292. #if defined(snprintf)
  1293. #undef snprintf
  1294. #endif
  1295. #if defined(vsnprintf)
  1296. #undef vsnprintf
  1297. #endif
  1298. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1299. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1300. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1301. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1302. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1303. #if defined(_WIN32)
  1304. /* vsnprintf must not be used in any system,
  1305. * but this define only works well for Windows. */
  1306. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1307. #endif
  1308. /* mg_init_library counter */
  1309. static int mg_init_library_called = 0;
  1310. #if !defined(NO_SSL)
  1311. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1312. || defined(OPENSSL_API_3_0)
  1313. static int mg_openssl_initialized = 0;
  1314. #endif
  1315. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1316. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1317. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1318. #endif
  1319. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1320. && defined(OPENSSL_API_3_0)
  1321. #error "Multiple OPENSSL_API versions defined"
  1322. #endif
  1323. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1324. || defined(OPENSSL_API_3_0)) \
  1325. && defined(USE_MBEDTLS)
  1326. #error "Multiple SSL libraries defined"
  1327. #endif
  1328. #endif
  1329. static pthread_key_t sTlsKey; /* Thread local storage index */
  1330. static volatile ptrdiff_t thread_idx_max = 0;
  1331. #if defined(MG_LEGACY_INTERFACE)
  1332. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1333. #endif
  1334. struct mg_workerTLS {
  1335. int is_master;
  1336. unsigned long thread_idx;
  1337. void *user_ptr;
  1338. #if defined(_WIN32)
  1339. HANDLE pthread_cond_helper_mutex;
  1340. struct mg_workerTLS *next_waiting_thread;
  1341. #endif
  1342. const char *alpn_proto;
  1343. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1344. char txtbuf[4];
  1345. #endif
  1346. };
  1347. #if defined(GCC_DIAGNOSTIC)
  1348. /* Show no warning in case system functions are not used. */
  1349. #pragma GCC diagnostic push
  1350. #pragma GCC diagnostic ignored "-Wunused-function"
  1351. #endif /* defined(GCC_DIAGNOSTIC) */
  1352. #if defined(__clang__)
  1353. /* Show no warning in case system functions are not used. */
  1354. #pragma clang diagnostic push
  1355. #pragma clang diagnostic ignored "-Wunused-function"
  1356. #endif
  1357. /* Get a unique thread ID as unsigned long, independent from the data type
  1358. * of thread IDs defined by the operating system API.
  1359. * If two calls to mg_current_thread_id return the same value, they calls
  1360. * are done from the same thread. If they return different values, they are
  1361. * done from different threads. (Provided this function is used in the same
  1362. * process context and threads are not repeatedly created and deleted, but
  1363. * CivetWeb does not do that).
  1364. * This function must match the signature required for SSL id callbacks:
  1365. * CRYPTO_set_id_callback
  1366. */
  1367. FUNCTION_MAY_BE_UNUSED
  1368. static unsigned long
  1369. mg_current_thread_id(void)
  1370. {
  1371. #if defined(_WIN32)
  1372. return GetCurrentThreadId();
  1373. #else
  1374. #if defined(__clang__)
  1375. #pragma clang diagnostic push
  1376. #pragma clang diagnostic ignored "-Wunreachable-code"
  1377. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1378. * or not, so one of the two conditions will be unreachable by construction.
  1379. * Unfortunately the C standard does not define a way to check this at
  1380. * compile time, since the #if preprocessor conditions can not use the
  1381. * sizeof operator as an argument. */
  1382. #endif
  1383. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1384. /* This is the problematic case for CRYPTO_set_id_callback:
  1385. * The OS pthread_t can not be cast to unsigned long. */
  1386. struct mg_workerTLS *tls =
  1387. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1388. if (tls == NULL) {
  1389. /* SSL called from an unknown thread: Create some thread index.
  1390. */
  1391. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1392. tls->is_master = -2; /* -2 means "3rd party thread" */
  1393. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1394. pthread_setspecific(sTlsKey, tls);
  1395. }
  1396. return tls->thread_idx;
  1397. } else {
  1398. /* pthread_t may be any data type, so a simple cast to unsigned long
  1399. * can rise a warning/error, depending on the platform.
  1400. * Here memcpy is used as an anything-to-anything cast. */
  1401. unsigned long ret = 0;
  1402. pthread_t t = pthread_self();
  1403. memcpy(&ret, &t, sizeof(pthread_t));
  1404. return ret;
  1405. }
  1406. #if defined(__clang__)
  1407. #pragma clang diagnostic pop
  1408. #endif
  1409. #endif
  1410. }
  1411. FUNCTION_MAY_BE_UNUSED
  1412. static uint64_t
  1413. mg_get_current_time_ns(void)
  1414. {
  1415. struct timespec tsnow;
  1416. clock_gettime(CLOCK_REALTIME, &tsnow);
  1417. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1418. }
  1419. #if defined(GCC_DIAGNOSTIC)
  1420. /* Show no warning in case system functions are not used. */
  1421. #pragma GCC diagnostic pop
  1422. #endif /* defined(GCC_DIAGNOSTIC) */
  1423. #if defined(__clang__)
  1424. /* Show no warning in case system functions are not used. */
  1425. #pragma clang diagnostic pop
  1426. #endif
  1427. #if defined(NEED_DEBUG_TRACE_FUNC)
  1428. static void
  1429. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1430. {
  1431. va_list args;
  1432. struct timespec tsnow;
  1433. /* Get some operating system independent thread id */
  1434. unsigned long thread_id = mg_current_thread_id();
  1435. clock_gettime(CLOCK_REALTIME, &tsnow);
  1436. flockfile(DEBUG_TRACE_STREAM);
  1437. fprintf(DEBUG_TRACE_STREAM,
  1438. "*** %lu.%09lu %lu %s:%u: ",
  1439. (unsigned long)tsnow.tv_sec,
  1440. (unsigned long)tsnow.tv_nsec,
  1441. thread_id,
  1442. func,
  1443. line);
  1444. va_start(args, fmt);
  1445. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1446. va_end(args);
  1447. putc('\n', DEBUG_TRACE_STREAM);
  1448. fflush(DEBUG_TRACE_STREAM);
  1449. funlockfile(DEBUG_TRACE_STREAM);
  1450. }
  1451. #endif /* NEED_DEBUG_TRACE_FUNC */
  1452. #define MD5_STATIC static
  1453. #include "md5.inl"
  1454. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1455. #if defined(NO_SOCKLEN_T)
  1456. typedef int socklen_t;
  1457. #endif /* NO_SOCKLEN_T */
  1458. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1459. #if !defined(MSG_NOSIGNAL)
  1460. #define MSG_NOSIGNAL (0)
  1461. #endif
  1462. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1463. #if defined(USE_MBEDTLS)
  1464. /* mbedTLS */
  1465. #include "mod_mbedtls.inl"
  1466. #elif defined(NO_SSL)
  1467. /* no SSL */
  1468. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1469. typedef struct SSL_CTX SSL_CTX;
  1470. #elif defined(NO_SSL_DL)
  1471. /* OpenSSL without dynamic loading */
  1472. #include <openssl/bn.h>
  1473. #include <openssl/conf.h>
  1474. #include <openssl/crypto.h>
  1475. #include <openssl/dh.h>
  1476. #include <openssl/engine.h>
  1477. #include <openssl/err.h>
  1478. #include <openssl/opensslv.h>
  1479. #include <openssl/pem.h>
  1480. #include <openssl/ssl.h>
  1481. #include <openssl/tls1.h>
  1482. #include <openssl/x509.h>
  1483. #if defined(WOLFSSL_VERSION)
  1484. /* Additional defines for WolfSSL, see
  1485. * https://github.com/civetweb/civetweb/issues/583 */
  1486. #include "wolfssl_extras.inl"
  1487. #endif
  1488. #if defined(OPENSSL_IS_BORINGSSL)
  1489. /* From boringssl/src/include/openssl/mem.h:
  1490. *
  1491. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1492. * However, that was written in a time before Valgrind and ASAN. Since we now
  1493. * have those tools, the OpenSSL allocation functions are simply macros around
  1494. * the standard memory functions.
  1495. *
  1496. * #define OPENSSL_free free */
  1497. #define free free
  1498. // disable for boringssl
  1499. #define CONF_modules_unload(a) ((void)0)
  1500. #define ENGINE_cleanup() ((void)0)
  1501. #endif
  1502. /* If OpenSSL headers are included, automatically select the API version */
  1503. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1504. #if !defined(OPENSSL_API_3_0)
  1505. #define OPENSSL_API_3_0
  1506. #endif
  1507. #define OPENSSL_REMOVE_THREAD_STATE()
  1508. #else
  1509. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1510. #if !defined(OPENSSL_API_1_1)
  1511. #define OPENSSL_API_1_1
  1512. #endif
  1513. #define OPENSSL_REMOVE_THREAD_STATE()
  1514. #else
  1515. #if !defined(OPENSSL_API_1_0)
  1516. #define OPENSSL_API_1_0
  1517. #endif
  1518. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1519. #endif
  1520. #endif
  1521. #else
  1522. /* SSL loaded dynamically from DLL / shared object */
  1523. /* Add all prototypes here, to be independent from OpenSSL source
  1524. * installation. */
  1525. #include "openssl_dl.inl"
  1526. #endif /* Various SSL bindings */
  1527. #if !defined(NO_CACHING)
  1528. static const char month_names[][4] = {"Jan",
  1529. "Feb",
  1530. "Mar",
  1531. "Apr",
  1532. "May",
  1533. "Jun",
  1534. "Jul",
  1535. "Aug",
  1536. "Sep",
  1537. "Oct",
  1538. "Nov",
  1539. "Dec"};
  1540. #endif /* !NO_CACHING */
  1541. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1542. * the union u. */
  1543. union usa {
  1544. struct sockaddr sa;
  1545. struct sockaddr_in sin;
  1546. #if defined(USE_IPV6)
  1547. struct sockaddr_in6 sin6;
  1548. #endif
  1549. #if defined(USE_X_DOM_SOCKET)
  1550. struct sockaddr_un sun;
  1551. #endif
  1552. };
  1553. #if defined(USE_X_DOM_SOCKET)
  1554. static unsigned short
  1555. USA_IN_PORT_UNSAFE(union usa *s)
  1556. {
  1557. if (s->sa.sa_family == AF_INET)
  1558. return s->sin.sin_port;
  1559. #if defined(USE_IPV6)
  1560. if (s->sa.sa_family == AF_INET6)
  1561. return s->sin6.sin6_port;
  1562. #endif
  1563. return 0;
  1564. }
  1565. #endif
  1566. #if defined(USE_IPV6)
  1567. #define USA_IN_PORT_UNSAFE(s) \
  1568. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1569. #else
  1570. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1571. #endif
  1572. /* Describes a string (chunk of memory). */
  1573. struct vec {
  1574. const char *ptr;
  1575. size_t len;
  1576. };
  1577. struct mg_file_stat {
  1578. /* File properties filled by mg_stat: */
  1579. uint64_t size;
  1580. time_t last_modified;
  1581. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1582. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1583. * case we need a "Content-Eencoding: gzip" header */
  1584. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1585. };
  1586. struct mg_file_access {
  1587. /* File properties filled by mg_fopen: */
  1588. FILE *fp;
  1589. };
  1590. struct mg_file {
  1591. struct mg_file_stat stat;
  1592. struct mg_file_access access;
  1593. };
  1594. #define STRUCT_FILE_INITIALIZER \
  1595. { \
  1596. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1597. { \
  1598. (FILE *)NULL \
  1599. } \
  1600. }
  1601. /* Describes listening socket, or socket which was accept()-ed by the master
  1602. * thread and queued for future handling by the worker thread. */
  1603. struct socket {
  1604. SOCKET sock; /* Listening socket */
  1605. union usa lsa; /* Local socket address */
  1606. union usa rsa; /* Remote socket address */
  1607. unsigned char is_ssl; /* Is port SSL-ed */
  1608. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1609. * port */
  1610. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1611. };
  1612. /* Enum const for all options must be in sync with
  1613. * static struct mg_option config_options[]
  1614. * This is tested in the unit test (test/private.c)
  1615. * "Private Config Options"
  1616. */
  1617. enum {
  1618. /* Once for each server */
  1619. LISTENING_PORTS,
  1620. NUM_THREADS,
  1621. RUN_AS_USER,
  1622. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1623. * socket option typedef TCP_NODELAY. */
  1624. MAX_REQUEST_SIZE,
  1625. LINGER_TIMEOUT,
  1626. CONNECTION_QUEUE_SIZE,
  1627. LISTEN_BACKLOG_SIZE,
  1628. #if defined(__linux__)
  1629. ALLOW_SENDFILE_CALL,
  1630. #endif
  1631. #if defined(_WIN32)
  1632. CASE_SENSITIVE_FILES,
  1633. #endif
  1634. THROTTLE,
  1635. ENABLE_KEEP_ALIVE,
  1636. REQUEST_TIMEOUT,
  1637. KEEP_ALIVE_TIMEOUT,
  1638. #if defined(USE_WEBSOCKET)
  1639. WEBSOCKET_TIMEOUT,
  1640. ENABLE_WEBSOCKET_PING_PONG,
  1641. #endif
  1642. DECODE_URL,
  1643. DECODE_QUERY_STRING,
  1644. #if defined(USE_LUA)
  1645. LUA_BACKGROUND_SCRIPT,
  1646. LUA_BACKGROUND_SCRIPT_PARAMS,
  1647. #endif
  1648. #if defined(USE_HTTP2)
  1649. ENABLE_HTTP2,
  1650. #endif
  1651. /* Once for each domain */
  1652. DOCUMENT_ROOT,
  1653. ACCESS_LOG_FILE,
  1654. ERROR_LOG_FILE,
  1655. CGI_EXTENSIONS,
  1656. CGI_ENVIRONMENT,
  1657. CGI_INTERPRETER,
  1658. CGI_INTERPRETER_ARGS,
  1659. #if defined(USE_TIMERS)
  1660. CGI_TIMEOUT,
  1661. #endif
  1662. CGI_BUFFERING,
  1663. CGI2_EXTENSIONS,
  1664. CGI2_ENVIRONMENT,
  1665. CGI2_INTERPRETER,
  1666. CGI2_INTERPRETER_ARGS,
  1667. #if defined(USE_TIMERS)
  1668. CGI2_TIMEOUT,
  1669. #endif
  1670. CGI2_BUFFERING,
  1671. #if defined(USE_4_CGI)
  1672. CGI3_EXTENSIONS,
  1673. CGI3_ENVIRONMENT,
  1674. CGI3_INTERPRETER,
  1675. CGI3_INTERPRETER_ARGS,
  1676. #if defined(USE_TIMERS)
  1677. CGI3_TIMEOUT,
  1678. #endif
  1679. CGI3_BUFFERING,
  1680. CGI4_EXTENSIONS,
  1681. CGI4_ENVIRONMENT,
  1682. CGI4_INTERPRETER,
  1683. CGI4_INTERPRETER_ARGS,
  1684. #if defined(USE_TIMERS)
  1685. CGI4_TIMEOUT,
  1686. #endif
  1687. CGI4_BUFFERING,
  1688. #endif
  1689. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1690. PROTECT_URI,
  1691. AUTHENTICATION_DOMAIN,
  1692. ENABLE_AUTH_DOMAIN_CHECK,
  1693. SSI_EXTENSIONS,
  1694. ENABLE_DIRECTORY_LISTING,
  1695. ENABLE_WEBDAV,
  1696. GLOBAL_PASSWORDS_FILE,
  1697. INDEX_FILES,
  1698. ACCESS_CONTROL_LIST,
  1699. EXTRA_MIME_TYPES,
  1700. SSL_CERTIFICATE,
  1701. SSL_CERTIFICATE_CHAIN,
  1702. URL_REWRITE_PATTERN,
  1703. HIDE_FILES,
  1704. SSL_DO_VERIFY_PEER,
  1705. SSL_CACHE_TIMEOUT,
  1706. SSL_CA_PATH,
  1707. SSL_CA_FILE,
  1708. SSL_VERIFY_DEPTH,
  1709. SSL_DEFAULT_VERIFY_PATHS,
  1710. SSL_CIPHER_LIST,
  1711. SSL_PROTOCOL_VERSION,
  1712. SSL_SHORT_TRUST,
  1713. #if defined(USE_LUA)
  1714. LUA_PRELOAD_FILE,
  1715. LUA_SCRIPT_EXTENSIONS,
  1716. LUA_SERVER_PAGE_EXTENSIONS,
  1717. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1718. LUA_DEBUG_PARAMS,
  1719. #endif
  1720. #endif
  1721. #if defined(USE_DUKTAPE)
  1722. DUKTAPE_SCRIPT_EXTENSIONS,
  1723. #endif
  1724. #if defined(USE_WEBSOCKET)
  1725. WEBSOCKET_ROOT,
  1726. #endif
  1727. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1728. LUA_WEBSOCKET_EXTENSIONS,
  1729. #endif
  1730. ACCESS_CONTROL_ALLOW_ORIGIN,
  1731. ACCESS_CONTROL_ALLOW_METHODS,
  1732. ACCESS_CONTROL_ALLOW_HEADERS,
  1733. ERROR_PAGES,
  1734. #if !defined(NO_CACHING)
  1735. STATIC_FILE_MAX_AGE,
  1736. STATIC_FILE_CACHE_CONTROL,
  1737. #endif
  1738. #if !defined(NO_SSL)
  1739. STRICT_HTTPS_MAX_AGE,
  1740. #endif
  1741. ADDITIONAL_HEADER,
  1742. ALLOW_INDEX_SCRIPT_SUB_RES,
  1743. NUM_OPTIONS
  1744. };
  1745. /* Config option name, config types, default value.
  1746. * Must be in the same order as the enum const above.
  1747. */
  1748. static const struct mg_option config_options[] = {
  1749. /* Once for each server */
  1750. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1751. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1752. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1753. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1754. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1755. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1756. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1757. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1758. #if defined(__linux__)
  1759. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1760. #endif
  1761. #if defined(_WIN32)
  1762. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1763. #endif
  1764. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1765. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1766. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1767. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1768. #if defined(USE_WEBSOCKET)
  1769. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1770. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1771. #endif
  1772. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1773. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1774. #if defined(USE_LUA)
  1775. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1776. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1777. #endif
  1778. #if defined(USE_HTTP2)
  1779. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1780. #endif
  1781. /* Once for each domain */
  1782. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1783. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1784. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1785. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1786. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1787. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1788. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1789. #if defined(USE_TIMERS)
  1790. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1791. #endif
  1792. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1793. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1794. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1795. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1796. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1797. #if defined(USE_TIMERS)
  1798. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1799. #endif
  1800. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1801. #if defined(USE_4_CGI)
  1802. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1803. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1804. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1805. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1806. #if defined(USE_TIMERS)
  1807. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1808. #endif
  1809. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1810. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1811. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1812. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1813. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1814. #if defined(USE_TIMERS)
  1815. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1816. #endif
  1817. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1818. #endif
  1819. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1820. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1821. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1822. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1823. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1824. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1825. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1826. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1827. {"index_files",
  1828. MG_CONFIG_TYPE_STRING_LIST,
  1829. #if defined(USE_LUA)
  1830. "index.xhtml,index.html,index.htm,"
  1831. "index.lp,index.lsp,index.lua,index.cgi,"
  1832. "index.shtml,index.php"},
  1833. #else
  1834. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1835. #endif
  1836. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1837. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1838. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1839. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1841. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1842. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1843. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1844. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1845. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1846. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1847. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1848. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1849. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1850. * as a minimum in 2020 */
  1851. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1852. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1853. #if defined(USE_LUA)
  1854. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1855. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1856. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1857. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1858. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1859. #endif
  1860. #endif
  1861. #if defined(USE_DUKTAPE)
  1862. /* The support for duktape is still in alpha version state.
  1863. * The name of this config option might change. */
  1864. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1865. #endif
  1866. #if defined(USE_WEBSOCKET)
  1867. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1868. #endif
  1869. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1870. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1871. #endif
  1872. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1873. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1874. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1875. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1876. #if !defined(NO_CACHING)
  1877. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1878. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1879. #endif
  1880. #if !defined(NO_SSL)
  1881. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1882. #endif
  1883. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1884. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1885. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1886. /* Check if the config_options and the corresponding enum have compatible
  1887. * sizes. */
  1888. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1889. == (NUM_OPTIONS + 1),
  1890. "config_options and enum not sync");
  1891. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1892. struct mg_handler_info {
  1893. /* Name/Pattern of the URI. */
  1894. char *uri;
  1895. size_t uri_len;
  1896. /* handler type */
  1897. int handler_type;
  1898. /* Handler for http/https or requests. */
  1899. mg_request_handler handler;
  1900. unsigned int refcount;
  1901. int removing;
  1902. /* Handler for ws/wss (websocket) requests. */
  1903. mg_websocket_connect_handler connect_handler;
  1904. mg_websocket_ready_handler ready_handler;
  1905. mg_websocket_data_handler data_handler;
  1906. mg_websocket_close_handler close_handler;
  1907. /* accepted subprotocols for ws/wss requests. */
  1908. struct mg_websocket_subprotocols *subprotocols;
  1909. /* Handler for authorization requests */
  1910. mg_authorization_handler auth_handler;
  1911. /* User supplied argument for the handler function. */
  1912. void *cbdata;
  1913. /* next handler in a linked list */
  1914. struct mg_handler_info *next;
  1915. };
  1916. enum {
  1917. CONTEXT_INVALID,
  1918. CONTEXT_SERVER,
  1919. CONTEXT_HTTP_CLIENT,
  1920. CONTEXT_WS_CLIENT
  1921. };
  1922. struct mg_domain_context {
  1923. SSL_CTX *ssl_ctx; /* SSL context */
  1924. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1925. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1926. int64_t ssl_cert_last_mtime;
  1927. /* Server nonce */
  1928. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1929. unsigned long nonce_count; /* Used nonces, used for authentication */
  1930. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1931. /* linked list of shared lua websockets */
  1932. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1933. #endif
  1934. /* Linked list of domains */
  1935. struct mg_domain_context *next;
  1936. };
  1937. /* Stop flag can be "volatile" or require a lock.
  1938. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1939. * states a read operation for int is always atomic. */
  1940. #if defined(STOP_FLAG_NEEDS_LOCK)
  1941. typedef ptrdiff_t volatile stop_flag_t;
  1942. static int
  1943. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1944. {
  1945. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1946. return (sf == 0);
  1947. }
  1948. static int
  1949. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1950. {
  1951. stop_flag_t sf = mg_atomic_add(f, 0);
  1952. return (sf == 2);
  1953. }
  1954. static void
  1955. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1956. {
  1957. stop_flag_t sf;
  1958. do {
  1959. sf = mg_atomic_compare_and_swap(f, *f, v);
  1960. } while (sf != v);
  1961. }
  1962. #else /* STOP_FLAG_NEEDS_LOCK */
  1963. typedef int volatile stop_flag_t;
  1964. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1965. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1966. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1967. #endif /* STOP_FLAG_NEEDS_LOCK */
  1968. #if !defined(NUM_WEBDAV_LOCKS)
  1969. #define NUM_WEBDAV_LOCKS 10
  1970. #endif
  1971. #if !defined(LOCK_DURATION_S)
  1972. #define LOCK_DURATION_S 60
  1973. #endif
  1974. struct twebdav_lock {
  1975. uint64_t locktime;
  1976. char token[33];
  1977. char path[UTF8_PATH_MAX * 2];
  1978. char user[UTF8_PATH_MAX * 2];
  1979. };
  1980. struct mg_context {
  1981. /* Part 1 - Physical context:
  1982. * This holds threads, ports, timeouts, ...
  1983. * set for the entire server, independent from the
  1984. * addressed hostname.
  1985. */
  1986. /* Connection related */
  1987. int context_type; /* See CONTEXT_* above */
  1988. struct socket *listening_sockets;
  1989. struct mg_pollfd *listening_socket_fds;
  1990. unsigned int num_listening_sockets;
  1991. struct mg_connection *worker_connections; /* The connection struct, pre-
  1992. * allocated for each worker */
  1993. #if defined(USE_SERVER_STATS)
  1994. volatile ptrdiff_t active_connections;
  1995. volatile ptrdiff_t max_active_connections;
  1996. volatile ptrdiff_t total_connections;
  1997. volatile ptrdiff_t total_requests;
  1998. volatile int64_t total_data_read;
  1999. volatile int64_t total_data_written;
  2000. #endif
  2001. /* Thread related */
  2002. stop_flag_t stop_flag; /* Should we stop event loop */
  2003. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2004. pthread_t masterthreadid; /* The master thread ID */
  2005. unsigned int
  2006. cfg_worker_threads; /* The number of configured worker threads. */
  2007. pthread_t *worker_threadids; /* The worker thread IDs */
  2008. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2009. /* Connection to thread dispatching */
  2010. #if defined(ALTERNATIVE_QUEUE)
  2011. struct socket *client_socks;
  2012. void **client_wait_events;
  2013. #else
  2014. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2015. worker thread */
  2016. volatile int sq_head; /* Head of the socket queue */
  2017. volatile int sq_tail; /* Tail of the socket queue */
  2018. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2019. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2020. volatile int sq_blocked; /* Status information: sq is full */
  2021. int sq_size; /* No of elements in socket queue */
  2022. #if defined(USE_SERVER_STATS)
  2023. int sq_max_fill;
  2024. #endif /* USE_SERVER_STATS */
  2025. #endif /* ALTERNATIVE_QUEUE */
  2026. /* Memory related */
  2027. unsigned int max_request_size; /* The max request size */
  2028. #if defined(USE_SERVER_STATS)
  2029. struct mg_memory_stat ctx_memory;
  2030. #endif
  2031. /* WebDAV lock structures */
  2032. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2033. /* Operating system related */
  2034. char *systemName; /* What operating system is running */
  2035. time_t start_time; /* Server start time, used for authentication
  2036. * and for diagnstics. */
  2037. #if defined(USE_TIMERS)
  2038. struct ttimers *timers;
  2039. #endif
  2040. /* Lua specific: Background operations and shared websockets */
  2041. #if defined(USE_LUA)
  2042. void *lua_background_state; /* lua_State (here as void *) */
  2043. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2044. int lua_bg_log_available; /* Use Lua background state for access log */
  2045. #endif
  2046. /* Server nonce */
  2047. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2048. * ssl_cert_last_mtime, nonce_count, and
  2049. * next (linked list) */
  2050. /* Server callbacks */
  2051. struct mg_callbacks callbacks; /* User-defined callback function */
  2052. void *user_data; /* User-defined data */
  2053. /* Part 2 - Logical domain:
  2054. * This holds hostname, TLS certificate, document root, ...
  2055. * set for a domain hosted at the server.
  2056. * There may be multiple domains hosted at one physical server.
  2057. * The default domain "dd" is the first element of a list of
  2058. * domains.
  2059. */
  2060. struct mg_domain_context dd; /* default domain */
  2061. };
  2062. #if defined(USE_SERVER_STATS)
  2063. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2064. static struct mg_memory_stat *
  2065. get_memory_stat(struct mg_context *ctx)
  2066. {
  2067. if (ctx) {
  2068. return &(ctx->ctx_memory);
  2069. }
  2070. return &mg_common_memory;
  2071. }
  2072. #endif
  2073. enum {
  2074. CONNECTION_TYPE_INVALID = 0,
  2075. CONNECTION_TYPE_REQUEST = 1,
  2076. CONNECTION_TYPE_RESPONSE = 2
  2077. };
  2078. enum {
  2079. PROTOCOL_TYPE_HTTP1 = 0,
  2080. PROTOCOL_TYPE_WEBSOCKET = 1,
  2081. PROTOCOL_TYPE_HTTP2 = 2
  2082. };
  2083. #if defined(USE_HTTP2)
  2084. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2085. #define HTTP2_DYN_TABLE_SIZE (256)
  2086. #endif
  2087. struct mg_http2_connection {
  2088. uint32_t stream_id;
  2089. uint32_t dyn_table_size;
  2090. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2091. };
  2092. #endif
  2093. struct mg_connection {
  2094. int connection_type; /* see CONNECTION_TYPE_* above */
  2095. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2096. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2097. fully sent */
  2098. #if defined(USE_HTTP2)
  2099. struct mg_http2_connection http2;
  2100. #endif
  2101. struct mg_request_info request_info;
  2102. struct mg_response_info response_info;
  2103. struct mg_context *phys_ctx;
  2104. struct mg_domain_context *dom_ctx;
  2105. #if defined(USE_SERVER_STATS)
  2106. int conn_state; /* 0 = undef, numerical value may change in different
  2107. * versions. For the current definition, see
  2108. * mg_get_connection_info_impl */
  2109. #endif
  2110. SSL *ssl; /* SSL descriptor */
  2111. struct socket client; /* Connected client */
  2112. time_t conn_birth_time; /* Time (wall clock) when connection was
  2113. * established */
  2114. #if defined(USE_SERVER_STATS)
  2115. time_t conn_close_time; /* Time (wall clock) when connection was
  2116. * closed (or 0 if still open) */
  2117. double processing_time; /* Procesing time for one request. */
  2118. #endif
  2119. struct timespec req_time; /* Time (since system start) when the request
  2120. * was received */
  2121. int64_t num_bytes_sent; /* Total bytes sent to client */
  2122. int64_t content_len; /* How many bytes of content can be read
  2123. * !is_chunked: Content-Length header value
  2124. * or -1 (until connection closed,
  2125. * not allowed for a request)
  2126. * is_chunked: >= 0, appended gradually
  2127. */
  2128. int64_t consumed_content; /* How many bytes of content have been read */
  2129. int is_chunked; /* Transfer-Encoding is chunked:
  2130. * 0 = not chunked,
  2131. * 1 = chunked, not yet, or some data read,
  2132. * 2 = chunked, has error,
  2133. * 3 = chunked, all data read except trailer,
  2134. * 4 = chunked, all data read
  2135. */
  2136. char *buf; /* Buffer for received data */
  2137. char *path_info; /* PATH_INFO part of the URL */
  2138. int must_close; /* 1 if connection must be closed */
  2139. int accept_gzip; /* 1 if gzip encoding is accepted */
  2140. int in_error_handler; /* 1 if in handler for user defined error
  2141. * pages */
  2142. #if defined(USE_WEBSOCKET)
  2143. int in_websocket_handling; /* 1 if in read_websocket */
  2144. #endif
  2145. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2146. && defined(MG_EXPERIMENTAL_INTERFACES)
  2147. /* Parameters for websocket data compression according to rfc7692 */
  2148. int websocket_deflate_server_max_windows_bits;
  2149. int websocket_deflate_client_max_windows_bits;
  2150. int websocket_deflate_server_no_context_takeover;
  2151. int websocket_deflate_client_no_context_takeover;
  2152. int websocket_deflate_initialized;
  2153. int websocket_deflate_flush;
  2154. z_stream websocket_deflate_state;
  2155. z_stream websocket_inflate_state;
  2156. #endif
  2157. int handled_requests; /* Number of requests handled by this connection
  2158. */
  2159. int buf_size; /* Buffer size */
  2160. int request_len; /* Size of the request + headers in a buffer */
  2161. int data_len; /* Total size of data in a buffer */
  2162. int status_code; /* HTTP reply status code, e.g. 200 */
  2163. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2164. * throttle */
  2165. time_t last_throttle_time; /* Last time throttled data was sent */
  2166. int last_throttle_bytes; /* Bytes sent this second */
  2167. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2168. * atomic transmissions for websockets */
  2169. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2170. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2171. #endif
  2172. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2173. * for quick access */
  2174. };
  2175. /* Directory entry */
  2176. struct de {
  2177. char *file_name;
  2178. struct mg_file_stat file;
  2179. };
  2180. #define mg_cry_internal(conn, fmt, ...) \
  2181. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2182. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2183. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2184. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2185. struct mg_context *ctx,
  2186. const char *func,
  2187. unsigned line,
  2188. const char *fmt,
  2189. ...) PRINTF_ARGS(5, 6);
  2190. #if !defined(NO_THREAD_NAME)
  2191. #if defined(_WIN32) && defined(_MSC_VER)
  2192. /* Set the thread name for debugging purposes in Visual Studio
  2193. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2194. */
  2195. #pragma pack(push, 8)
  2196. typedef struct tagTHREADNAME_INFO {
  2197. DWORD dwType; /* Must be 0x1000. */
  2198. LPCSTR szName; /* Pointer to name (in user addr space). */
  2199. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2200. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2201. } THREADNAME_INFO;
  2202. #pragma pack(pop)
  2203. #elif defined(__linux__)
  2204. #include <sys/prctl.h>
  2205. #include <sys/sendfile.h>
  2206. #if defined(ALTERNATIVE_QUEUE)
  2207. #include <sys/eventfd.h>
  2208. #endif /* ALTERNATIVE_QUEUE */
  2209. #if defined(ALTERNATIVE_QUEUE)
  2210. static void *
  2211. event_create(void)
  2212. {
  2213. int evhdl = eventfd(0, EFD_CLOEXEC);
  2214. int *ret;
  2215. if (evhdl == -1) {
  2216. /* Linux uses -1 on error, Windows NULL. */
  2217. /* However, Linux does not return 0 on success either. */
  2218. return 0;
  2219. }
  2220. ret = (int *)mg_malloc(sizeof(int));
  2221. if (ret) {
  2222. *ret = evhdl;
  2223. } else {
  2224. (void)close(evhdl);
  2225. }
  2226. return (void *)ret;
  2227. }
  2228. static int
  2229. event_wait(void *eventhdl)
  2230. {
  2231. uint64_t u;
  2232. int evhdl, s;
  2233. if (!eventhdl) {
  2234. /* error */
  2235. return 0;
  2236. }
  2237. evhdl = *(int *)eventhdl;
  2238. s = (int)read(evhdl, &u, sizeof(u));
  2239. if (s != sizeof(u)) {
  2240. /* error */
  2241. return 0;
  2242. }
  2243. (void)u; /* the value is not required */
  2244. return 1;
  2245. }
  2246. static int
  2247. event_signal(void *eventhdl)
  2248. {
  2249. uint64_t u = 1;
  2250. int evhdl, s;
  2251. if (!eventhdl) {
  2252. /* error */
  2253. return 0;
  2254. }
  2255. evhdl = *(int *)eventhdl;
  2256. s = (int)write(evhdl, &u, sizeof(u));
  2257. if (s != sizeof(u)) {
  2258. /* error */
  2259. return 0;
  2260. }
  2261. return 1;
  2262. }
  2263. static void
  2264. event_destroy(void *eventhdl)
  2265. {
  2266. int evhdl;
  2267. if (!eventhdl) {
  2268. /* error */
  2269. return;
  2270. }
  2271. evhdl = *(int *)eventhdl;
  2272. close(evhdl);
  2273. mg_free(eventhdl);
  2274. }
  2275. #endif
  2276. #endif
  2277. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2278. struct posix_event {
  2279. pthread_mutex_t mutex;
  2280. pthread_cond_t cond;
  2281. int signaled;
  2282. };
  2283. static void *
  2284. event_create(void)
  2285. {
  2286. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2287. if (ret == 0) {
  2288. /* out of memory */
  2289. return 0;
  2290. }
  2291. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2292. /* pthread mutex not available */
  2293. mg_free(ret);
  2294. return 0;
  2295. }
  2296. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2297. /* pthread cond not available */
  2298. pthread_mutex_destroy(&(ret->mutex));
  2299. mg_free(ret);
  2300. return 0;
  2301. }
  2302. ret->signaled = 0;
  2303. return (void *)ret;
  2304. }
  2305. static int
  2306. event_wait(void *eventhdl)
  2307. {
  2308. struct posix_event *ev = (struct posix_event *)eventhdl;
  2309. pthread_mutex_lock(&(ev->mutex));
  2310. while (!ev->signaled) {
  2311. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2312. }
  2313. ev->signaled = 0;
  2314. pthread_mutex_unlock(&(ev->mutex));
  2315. return 1;
  2316. }
  2317. static int
  2318. event_signal(void *eventhdl)
  2319. {
  2320. struct posix_event *ev = (struct posix_event *)eventhdl;
  2321. pthread_mutex_lock(&(ev->mutex));
  2322. pthread_cond_signal(&(ev->cond));
  2323. ev->signaled = 1;
  2324. pthread_mutex_unlock(&(ev->mutex));
  2325. return 1;
  2326. }
  2327. static void
  2328. event_destroy(void *eventhdl)
  2329. {
  2330. struct posix_event *ev = (struct posix_event *)eventhdl;
  2331. pthread_cond_destroy(&(ev->cond));
  2332. pthread_mutex_destroy(&(ev->mutex));
  2333. mg_free(ev);
  2334. }
  2335. #endif
  2336. static void
  2337. mg_set_thread_name(const char *name)
  2338. {
  2339. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2340. mg_snprintf(
  2341. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2342. #if defined(_WIN32)
  2343. #if defined(_MSC_VER)
  2344. /* Windows and Visual Studio Compiler */
  2345. __try {
  2346. THREADNAME_INFO info;
  2347. info.dwType = 0x1000;
  2348. info.szName = threadName;
  2349. info.dwThreadID = ~0U;
  2350. info.dwFlags = 0;
  2351. RaiseException(0x406D1388,
  2352. 0,
  2353. sizeof(info) / sizeof(ULONG_PTR),
  2354. (ULONG_PTR *)&info);
  2355. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2356. }
  2357. #elif defined(__MINGW32__)
  2358. /* No option known to set thread name for MinGW known */
  2359. #endif
  2360. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2361. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2362. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2363. #if defined(__MACH__)
  2364. /* OS X only current thread name can be changed */
  2365. (void)pthread_setname_np(threadName);
  2366. #else
  2367. (void)pthread_setname_np(pthread_self(), threadName);
  2368. #endif
  2369. #elif defined(__linux__)
  2370. /* On Linux we can use the prctl function.
  2371. * When building for Linux Standard Base (LSB) use
  2372. * NO_THREAD_NAME. However, thread names are a big
  2373. * help for debugging, so the stadard is to set them.
  2374. */
  2375. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2376. #endif
  2377. }
  2378. #else /* !defined(NO_THREAD_NAME) */
  2379. void
  2380. mg_set_thread_name(const char *threadName)
  2381. {
  2382. }
  2383. #endif
  2384. const struct mg_option *
  2385. mg_get_valid_options(void)
  2386. {
  2387. return config_options;
  2388. }
  2389. /* Do not open file (unused) */
  2390. #define MG_FOPEN_MODE_NONE (0)
  2391. /* Open file for read only access */
  2392. #define MG_FOPEN_MODE_READ (1)
  2393. /* Open file for writing, create and overwrite */
  2394. #define MG_FOPEN_MODE_WRITE (2)
  2395. /* Open file for writing, create and append */
  2396. #define MG_FOPEN_MODE_APPEND (4)
  2397. static int
  2398. is_file_opened(const struct mg_file_access *fileacc)
  2399. {
  2400. if (!fileacc) {
  2401. return 0;
  2402. }
  2403. return (fileacc->fp != NULL);
  2404. }
  2405. #if !defined(NO_FILESYSTEMS)
  2406. static int mg_stat(const struct mg_connection *conn,
  2407. const char *path,
  2408. struct mg_file_stat *filep);
  2409. /* Reject files with special characters (for Windows) */
  2410. static int
  2411. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2412. {
  2413. const uint8_t *c = (const uint8_t *)path;
  2414. (void)conn; /* not used */
  2415. if ((c == NULL) || (c[0] == 0)) {
  2416. /* Null pointer or empty path --> suspicious */
  2417. return 1;
  2418. }
  2419. #if defined(_WIN32)
  2420. while (*c) {
  2421. if (*c < 32) {
  2422. /* Control character */
  2423. return 1;
  2424. }
  2425. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2426. /* stdin/stdout redirection character */
  2427. return 1;
  2428. }
  2429. if ((*c == '*') || (*c == '?')) {
  2430. /* Wildcard character */
  2431. return 1;
  2432. }
  2433. if (*c == '"') {
  2434. /* Windows quotation */
  2435. return 1;
  2436. }
  2437. c++;
  2438. }
  2439. #endif
  2440. /* Nothing suspicious found */
  2441. return 0;
  2442. }
  2443. /* mg_fopen will open a file either in memory or on the disk.
  2444. * The input parameter path is a string in UTF-8 encoding.
  2445. * The input parameter mode is MG_FOPEN_MODE_*
  2446. * On success, fp will be set in the output struct mg_file.
  2447. * All status members will also be set.
  2448. * The function returns 1 on success, 0 on error. */
  2449. static int
  2450. mg_fopen(const struct mg_connection *conn,
  2451. const char *path,
  2452. int mode,
  2453. struct mg_file *filep)
  2454. {
  2455. int found;
  2456. if (!filep) {
  2457. return 0;
  2458. }
  2459. filep->access.fp = NULL;
  2460. if (mg_path_suspicious(conn, path)) {
  2461. return 0;
  2462. }
  2463. /* filep is initialized in mg_stat: all fields with memset to,
  2464. * some fields like size and modification date with values */
  2465. found = mg_stat(conn, path, &(filep->stat));
  2466. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2467. /* file does not exist and will not be created */
  2468. return 0;
  2469. }
  2470. #if defined(_WIN32)
  2471. {
  2472. wchar_t wbuf[UTF16_PATH_MAX];
  2473. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2474. switch (mode) {
  2475. case MG_FOPEN_MODE_READ:
  2476. filep->access.fp = _wfopen(wbuf, L"rb");
  2477. break;
  2478. case MG_FOPEN_MODE_WRITE:
  2479. filep->access.fp = _wfopen(wbuf, L"wb");
  2480. break;
  2481. case MG_FOPEN_MODE_APPEND:
  2482. filep->access.fp = _wfopen(wbuf, L"ab");
  2483. break;
  2484. }
  2485. }
  2486. #else
  2487. /* Linux et al already use unicode. No need to convert. */
  2488. switch (mode) {
  2489. case MG_FOPEN_MODE_READ:
  2490. filep->access.fp = fopen(path, "r");
  2491. break;
  2492. case MG_FOPEN_MODE_WRITE:
  2493. filep->access.fp = fopen(path, "w");
  2494. break;
  2495. case MG_FOPEN_MODE_APPEND:
  2496. filep->access.fp = fopen(path, "a");
  2497. break;
  2498. }
  2499. #endif
  2500. if (!found) {
  2501. /* File did not exist before fopen was called.
  2502. * Maybe it has been created now. Get stat info
  2503. * like creation time now. */
  2504. found = mg_stat(conn, path, &(filep->stat));
  2505. (void)found;
  2506. }
  2507. /* return OK if file is opened */
  2508. return (filep->access.fp != NULL);
  2509. }
  2510. /* return 0 on success, just like fclose */
  2511. static int
  2512. mg_fclose(struct mg_file_access *fileacc)
  2513. {
  2514. int ret = -1;
  2515. if (fileacc != NULL) {
  2516. if (fileacc->fp != NULL) {
  2517. ret = fclose(fileacc->fp);
  2518. }
  2519. /* reset all members of fileacc */
  2520. memset(fileacc, 0, sizeof(*fileacc));
  2521. }
  2522. return ret;
  2523. }
  2524. #endif /* NO_FILESYSTEMS */
  2525. static void
  2526. mg_strlcpy(char *dst, const char *src, size_t n)
  2527. {
  2528. for (; *src != '\0' && n > 1; n--) {
  2529. *dst++ = *src++;
  2530. }
  2531. *dst = '\0';
  2532. }
  2533. static int
  2534. lowercase(const char *s)
  2535. {
  2536. return tolower((unsigned char)*s);
  2537. }
  2538. int
  2539. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2540. {
  2541. int diff = 0;
  2542. if (len > 0) {
  2543. do {
  2544. diff = lowercase(s1++) - lowercase(s2++);
  2545. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2546. }
  2547. return diff;
  2548. }
  2549. int
  2550. mg_strcasecmp(const char *s1, const char *s2)
  2551. {
  2552. int diff;
  2553. do {
  2554. diff = lowercase(s1++) - lowercase(s2++);
  2555. } while (diff == 0 && s1[-1] != '\0');
  2556. return diff;
  2557. }
  2558. static char *
  2559. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2560. {
  2561. char *p;
  2562. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2563. * defined */
  2564. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2565. mg_strlcpy(p, ptr, len + 1);
  2566. }
  2567. return p;
  2568. }
  2569. static char *
  2570. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2571. {
  2572. return mg_strndup_ctx(str, strlen(str), ctx);
  2573. }
  2574. static char *
  2575. mg_strdup(const char *str)
  2576. {
  2577. return mg_strndup_ctx(str, strlen(str), NULL);
  2578. }
  2579. static const char *
  2580. mg_strcasestr(const char *big_str, const char *small_str)
  2581. {
  2582. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2583. if (big_len >= small_len) {
  2584. for (i = 0; i <= (big_len - small_len); i++) {
  2585. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2586. return big_str + i;
  2587. }
  2588. }
  2589. }
  2590. return NULL;
  2591. }
  2592. /* Return null terminated string of given maximum length.
  2593. * Report errors if length is exceeded. */
  2594. static void
  2595. mg_vsnprintf(const struct mg_connection *conn,
  2596. int *truncated,
  2597. char *buf,
  2598. size_t buflen,
  2599. const char *fmt,
  2600. va_list ap)
  2601. {
  2602. int n, ok;
  2603. if (buflen == 0) {
  2604. if (truncated) {
  2605. *truncated = 1;
  2606. }
  2607. return;
  2608. }
  2609. #if defined(__clang__)
  2610. #pragma clang diagnostic push
  2611. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2612. /* Using fmt as a non-literal is intended here, since it is mostly called
  2613. * indirectly by mg_snprintf */
  2614. #endif
  2615. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2616. ok = (n >= 0) && ((size_t)n < buflen);
  2617. #if defined(__clang__)
  2618. #pragma clang diagnostic pop
  2619. #endif
  2620. if (ok) {
  2621. if (truncated) {
  2622. *truncated = 0;
  2623. }
  2624. } else {
  2625. if (truncated) {
  2626. *truncated = 1;
  2627. }
  2628. mg_cry_internal(conn,
  2629. "truncating vsnprintf buffer: [%.*s]",
  2630. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2631. buf);
  2632. n = (int)buflen - 1;
  2633. }
  2634. buf[n] = '\0';
  2635. }
  2636. static void
  2637. mg_snprintf(const struct mg_connection *conn,
  2638. int *truncated,
  2639. char *buf,
  2640. size_t buflen,
  2641. const char *fmt,
  2642. ...)
  2643. {
  2644. va_list ap;
  2645. va_start(ap, fmt);
  2646. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2647. va_end(ap);
  2648. }
  2649. static int
  2650. get_option_index(const char *name)
  2651. {
  2652. int i;
  2653. for (i = 0; config_options[i].name != NULL; i++) {
  2654. if (strcmp(config_options[i].name, name) == 0) {
  2655. return i;
  2656. }
  2657. }
  2658. return -1;
  2659. }
  2660. const char *
  2661. mg_get_option(const struct mg_context *ctx, const char *name)
  2662. {
  2663. int i;
  2664. if ((i = get_option_index(name)) == -1) {
  2665. return NULL;
  2666. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2667. return "";
  2668. } else {
  2669. return ctx->dd.config[i];
  2670. }
  2671. }
  2672. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2673. struct mg_context *
  2674. mg_get_context(const struct mg_connection *conn)
  2675. {
  2676. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2677. }
  2678. void *
  2679. mg_get_user_data(const struct mg_context *ctx)
  2680. {
  2681. return (ctx == NULL) ? NULL : ctx->user_data;
  2682. }
  2683. void *
  2684. mg_get_user_context_data(const struct mg_connection *conn)
  2685. {
  2686. return mg_get_user_data(mg_get_context(conn));
  2687. }
  2688. void *
  2689. mg_get_thread_pointer(const struct mg_connection *conn)
  2690. {
  2691. /* both methods should return the same pointer */
  2692. if (conn) {
  2693. /* quick access, in case conn is known */
  2694. return conn->tls_user_ptr;
  2695. } else {
  2696. /* otherwise get pointer from thread local storage (TLS) */
  2697. struct mg_workerTLS *tls =
  2698. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2699. return tls->user_ptr;
  2700. }
  2701. }
  2702. void
  2703. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2704. {
  2705. if (const_conn != NULL) {
  2706. /* Const cast, since "const struct mg_connection *" does not mean
  2707. * the connection object is not modified. Here "const" is used,
  2708. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2709. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2710. conn->request_info.conn_data = data;
  2711. }
  2712. }
  2713. void *
  2714. mg_get_user_connection_data(const struct mg_connection *conn)
  2715. {
  2716. if (conn != NULL) {
  2717. return conn->request_info.conn_data;
  2718. }
  2719. return NULL;
  2720. }
  2721. int
  2722. mg_get_server_ports(const struct mg_context *ctx,
  2723. int size,
  2724. struct mg_server_port *ports)
  2725. {
  2726. int i, cnt = 0;
  2727. if (size <= 0) {
  2728. return -1;
  2729. }
  2730. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2731. if (!ctx) {
  2732. return -1;
  2733. }
  2734. if (!ctx->listening_sockets) {
  2735. return -1;
  2736. }
  2737. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2738. ports[cnt].port =
  2739. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2740. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2741. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2742. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2743. /* IPv4 */
  2744. ports[cnt].protocol = 1;
  2745. cnt++;
  2746. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2747. /* IPv6 */
  2748. ports[cnt].protocol = 3;
  2749. cnt++;
  2750. }
  2751. }
  2752. return cnt;
  2753. }
  2754. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2755. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2756. #endif
  2757. static void
  2758. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2759. {
  2760. buf[0] = '\0';
  2761. if (!usa) {
  2762. return;
  2763. }
  2764. if (usa->sa.sa_family == AF_INET) {
  2765. getnameinfo(&usa->sa,
  2766. sizeof(usa->sin),
  2767. buf,
  2768. (unsigned)len,
  2769. NULL,
  2770. 0,
  2771. NI_NUMERICHOST);
  2772. }
  2773. #if defined(USE_IPV6)
  2774. else if (usa->sa.sa_family == AF_INET6) {
  2775. getnameinfo(&usa->sa,
  2776. sizeof(usa->sin6),
  2777. buf,
  2778. (unsigned)len,
  2779. NULL,
  2780. 0,
  2781. NI_NUMERICHOST);
  2782. }
  2783. #endif
  2784. #if defined(USE_X_DOM_SOCKET)
  2785. else if (usa->sa.sa_family == AF_UNIX) {
  2786. /* TODO: Define a remote address for unix domain sockets.
  2787. * This code will always return "localhost", identical to http+tcp:
  2788. getnameinfo(&usa->sa,
  2789. sizeof(usa->sun),
  2790. buf,
  2791. (unsigned)len,
  2792. NULL,
  2793. 0,
  2794. NI_NUMERICHOST);
  2795. */
  2796. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2797. buf[len] = 0;
  2798. }
  2799. #endif
  2800. }
  2801. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2802. * included in all responses other than 100, 101, 5xx. */
  2803. static void
  2804. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2805. {
  2806. #if !defined(REENTRANT_TIME)
  2807. struct tm *tm;
  2808. tm = ((t != NULL) ? gmtime(t) : NULL);
  2809. if (tm != NULL) {
  2810. #else
  2811. struct tm _tm;
  2812. struct tm *tm = &_tm;
  2813. if (t != NULL) {
  2814. gmtime_r(t, tm);
  2815. #endif
  2816. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2817. } else {
  2818. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2819. buf[buf_len - 1] = '\0';
  2820. }
  2821. }
  2822. /* difftime for struct timespec. Return value is in seconds. */
  2823. static double
  2824. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2825. {
  2826. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2827. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2828. }
  2829. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2830. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2831. const char *func,
  2832. unsigned line,
  2833. const char *fmt,
  2834. va_list ap);
  2835. #include "external_mg_cry_internal_impl.inl"
  2836. #elif !defined(NO_FILESYSTEMS)
  2837. /* Print error message to the opened error log stream. */
  2838. static void
  2839. mg_cry_internal_impl(const struct mg_connection *conn,
  2840. const char *func,
  2841. unsigned line,
  2842. const char *fmt,
  2843. va_list ap)
  2844. {
  2845. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2846. struct mg_file fi;
  2847. time_t timestamp;
  2848. /* Unused, in the RELEASE build */
  2849. (void)func;
  2850. (void)line;
  2851. #if defined(GCC_DIAGNOSTIC)
  2852. #pragma GCC diagnostic push
  2853. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2854. #endif
  2855. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2856. #if defined(GCC_DIAGNOSTIC)
  2857. #pragma GCC diagnostic pop
  2858. #endif
  2859. buf[sizeof(buf) - 1] = 0;
  2860. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2861. if (!conn) {
  2862. puts(buf);
  2863. return;
  2864. }
  2865. /* Do not lock when getting the callback value, here and below.
  2866. * I suppose this is fine, since function cannot disappear in the
  2867. * same way string option can. */
  2868. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2869. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2870. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2871. if (mg_fopen(conn,
  2872. conn->dom_ctx->config[ERROR_LOG_FILE],
  2873. MG_FOPEN_MODE_APPEND,
  2874. &fi)
  2875. == 0) {
  2876. fi.access.fp = NULL;
  2877. }
  2878. } else {
  2879. fi.access.fp = NULL;
  2880. }
  2881. if (fi.access.fp != NULL) {
  2882. flockfile(fi.access.fp);
  2883. timestamp = time(NULL);
  2884. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2885. fprintf(fi.access.fp,
  2886. "[%010lu] [error] [client %s] ",
  2887. (unsigned long)timestamp,
  2888. src_addr);
  2889. if (conn->request_info.request_method != NULL) {
  2890. fprintf(fi.access.fp,
  2891. "%s %s: ",
  2892. conn->request_info.request_method,
  2893. conn->request_info.request_uri
  2894. ? conn->request_info.request_uri
  2895. : "");
  2896. }
  2897. fprintf(fi.access.fp, "%s", buf);
  2898. fputc('\n', fi.access.fp);
  2899. fflush(fi.access.fp);
  2900. funlockfile(fi.access.fp);
  2901. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2902. * mg_cry here anyway ;-) */
  2903. }
  2904. }
  2905. }
  2906. #else
  2907. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2908. #endif /* Externally provided function */
  2909. /* Construct fake connection structure. Used for logging, if connection
  2910. * is not applicable at the moment of logging. */
  2911. static struct mg_connection *
  2912. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2913. {
  2914. static const struct mg_connection conn_zero = {0};
  2915. *fc = conn_zero;
  2916. fc->phys_ctx = ctx;
  2917. fc->dom_ctx = &(ctx->dd);
  2918. return fc;
  2919. }
  2920. static void
  2921. mg_cry_internal_wrap(const struct mg_connection *conn,
  2922. struct mg_context *ctx,
  2923. const char *func,
  2924. unsigned line,
  2925. const char *fmt,
  2926. ...)
  2927. {
  2928. va_list ap;
  2929. va_start(ap, fmt);
  2930. if (!conn && ctx) {
  2931. struct mg_connection fc;
  2932. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2933. } else {
  2934. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2935. }
  2936. va_end(ap);
  2937. }
  2938. void
  2939. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2940. {
  2941. va_list ap;
  2942. va_start(ap, fmt);
  2943. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2944. va_end(ap);
  2945. }
  2946. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2947. const char *
  2948. mg_version(void)
  2949. {
  2950. return CIVETWEB_VERSION;
  2951. }
  2952. const struct mg_request_info *
  2953. mg_get_request_info(const struct mg_connection *conn)
  2954. {
  2955. if (!conn) {
  2956. return NULL;
  2957. }
  2958. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2959. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2960. char txt[16];
  2961. struct mg_workerTLS *tls =
  2962. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2963. sprintf(txt, "%03i", conn->response_info.status_code);
  2964. if (strlen(txt) == 3) {
  2965. memcpy(tls->txtbuf, txt, 4);
  2966. } else {
  2967. strcpy(tls->txtbuf, "ERR");
  2968. }
  2969. ((struct mg_connection *)conn)->request_info.local_uri =
  2970. tls->txtbuf; /* use thread safe buffer */
  2971. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2972. tls->txtbuf; /* use the same thread safe buffer */
  2973. ((struct mg_connection *)conn)->request_info.request_uri =
  2974. tls->txtbuf; /* use the same thread safe buffer */
  2975. ((struct mg_connection *)conn)->request_info.num_headers =
  2976. conn->response_info.num_headers;
  2977. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2978. conn->response_info.http_headers,
  2979. sizeof(conn->response_info.http_headers));
  2980. } else
  2981. #endif
  2982. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2983. return NULL;
  2984. }
  2985. return &conn->request_info;
  2986. }
  2987. const struct mg_response_info *
  2988. mg_get_response_info(const struct mg_connection *conn)
  2989. {
  2990. if (!conn) {
  2991. return NULL;
  2992. }
  2993. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2994. return NULL;
  2995. }
  2996. return &conn->response_info;
  2997. }
  2998. static const char *
  2999. get_proto_name(const struct mg_connection *conn)
  3000. {
  3001. #if defined(__clang__)
  3002. #pragma clang diagnostic push
  3003. #pragma clang diagnostic ignored "-Wunreachable-code"
  3004. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3005. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3006. * unreachable, but splitting into four different #ifdef clauses here is
  3007. * more complicated.
  3008. */
  3009. #endif
  3010. const struct mg_request_info *ri = &conn->request_info;
  3011. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3012. ? (ri->is_ssl ? "wss" : "ws")
  3013. : (ri->is_ssl ? "https" : "http"));
  3014. return proto;
  3015. #if defined(__clang__)
  3016. #pragma clang diagnostic pop
  3017. #endif
  3018. }
  3019. static int
  3020. mg_construct_local_link(const struct mg_connection *conn,
  3021. char *buf,
  3022. size_t buflen,
  3023. const char *define_proto,
  3024. int define_port,
  3025. const char *define_uri)
  3026. {
  3027. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3028. return -1;
  3029. } else {
  3030. int i, j;
  3031. int truncated = 0;
  3032. const struct mg_request_info *ri = &conn->request_info;
  3033. const char *proto =
  3034. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3035. const char *uri =
  3036. (define_uri != NULL)
  3037. ? define_uri
  3038. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3039. int port = (define_port > 0) ? define_port : ri->server_port;
  3040. int default_port = 80;
  3041. char *uri_encoded;
  3042. if (uri == NULL) {
  3043. return -1;
  3044. }
  3045. size_t uri_encoded_len = strlen(uri) * 3 + 1;
  3046. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3047. if (uri_encoded == NULL) {
  3048. return -1;
  3049. }
  3050. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3051. /* Directory separator should be preserved. */
  3052. for (i = j = 0; uri_encoded[i]; j++) {
  3053. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3054. uri_encoded[j] = '/';
  3055. i += 3;
  3056. } else {
  3057. uri_encoded[j] = uri_encoded[i++];
  3058. }
  3059. }
  3060. uri_encoded[j] = '\0';
  3061. #if defined(USE_X_DOM_SOCKET)
  3062. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3063. /* TODO: Define and document a link for UNIX domain sockets. */
  3064. /* There seems to be no official standard for this.
  3065. * Common uses seem to be "httpunix://", "http.unix://" or
  3066. * "http+unix://" as a protocol definition string, followed by
  3067. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3068. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3069. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3070. * "" (completely skipping the server name part). In any case, the
  3071. * last part is the server local path. */
  3072. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3073. mg_snprintf(conn,
  3074. &truncated,
  3075. buf,
  3076. buflen,
  3077. "%s.unix://%s%s",
  3078. proto,
  3079. server_name,
  3080. ri->local_uri);
  3081. default_port = 0;
  3082. mg_free(uri_encoded);
  3083. return 0;
  3084. }
  3085. #endif
  3086. if (define_proto) {
  3087. /* If we got a protocol name, use the default port accordingly. */
  3088. if ((0 == strcmp(define_proto, "https"))
  3089. || (0 == strcmp(define_proto, "wss"))) {
  3090. default_port = 443;
  3091. }
  3092. } else if (ri->is_ssl) {
  3093. /* If we did not get a protocol name, use TLS as default if it is
  3094. * already used. */
  3095. default_port = 443;
  3096. }
  3097. {
  3098. #if defined(USE_IPV6)
  3099. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3100. #endif
  3101. int auth_domain_check_enabled =
  3102. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3103. && (!mg_strcasecmp(
  3104. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3105. const char *server_domain =
  3106. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3107. char portstr[16];
  3108. char server_ip[48];
  3109. if (port != default_port) {
  3110. sprintf(portstr, ":%u", (unsigned)port);
  3111. } else {
  3112. portstr[0] = 0;
  3113. }
  3114. if (!auth_domain_check_enabled || !server_domain) {
  3115. sockaddr_to_string(server_ip,
  3116. sizeof(server_ip),
  3117. &conn->client.lsa);
  3118. server_domain = server_ip;
  3119. }
  3120. mg_snprintf(conn,
  3121. &truncated,
  3122. buf,
  3123. buflen,
  3124. #if defined(USE_IPV6)
  3125. "%s://%s%s%s%s%s",
  3126. proto,
  3127. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3128. server_domain,
  3129. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3130. #else
  3131. "%s://%s%s%s",
  3132. proto,
  3133. server_domain,
  3134. #endif
  3135. portstr,
  3136. uri_encoded);
  3137. mg_free(uri_encoded);
  3138. if (truncated) {
  3139. return -1;
  3140. }
  3141. return 0;
  3142. }
  3143. }
  3144. }
  3145. int
  3146. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3147. {
  3148. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3149. }
  3150. /* Skip the characters until one of the delimiters characters found.
  3151. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3152. * Advance pointer to buffer to the next word. Return found 0-terminated
  3153. * word.
  3154. * Delimiters can be quoted with quotechar. */
  3155. static char *
  3156. skip_quoted(char **buf,
  3157. const char *delimiters,
  3158. const char *whitespace,
  3159. char quotechar)
  3160. {
  3161. char *p, *begin_word, *end_word, *end_whitespace;
  3162. begin_word = *buf;
  3163. end_word = begin_word + strcspn(begin_word, delimiters);
  3164. /* Check for quotechar */
  3165. if (end_word > begin_word) {
  3166. p = end_word - 1;
  3167. while (*p == quotechar) {
  3168. /* While the delimiter is quoted, look for the next delimiter.
  3169. */
  3170. /* This happens, e.g., in calls from parse_auth_header,
  3171. * if the user name contains a " character. */
  3172. /* If there is anything beyond end_word, copy it. */
  3173. if (*end_word != '\0') {
  3174. size_t end_off = strcspn(end_word + 1, delimiters);
  3175. memmove(p, end_word, end_off + 1);
  3176. p += end_off; /* p must correspond to end_word - 1 */
  3177. end_word += end_off + 1;
  3178. } else {
  3179. *p = '\0';
  3180. break;
  3181. }
  3182. }
  3183. for (p++; p < end_word; p++) {
  3184. *p = '\0';
  3185. }
  3186. }
  3187. if (*end_word == '\0') {
  3188. *buf = end_word;
  3189. } else {
  3190. #if defined(GCC_DIAGNOSTIC)
  3191. /* Disable spurious conversion warning for GCC */
  3192. #pragma GCC diagnostic push
  3193. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3194. #endif /* defined(GCC_DIAGNOSTIC) */
  3195. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3196. #if defined(GCC_DIAGNOSTIC)
  3197. #pragma GCC diagnostic pop
  3198. #endif /* defined(GCC_DIAGNOSTIC) */
  3199. for (p = end_word; p < end_whitespace; p++) {
  3200. *p = '\0';
  3201. }
  3202. *buf = end_whitespace;
  3203. }
  3204. return begin_word;
  3205. }
  3206. /* Return HTTP header value, or NULL if not found. */
  3207. static const char *
  3208. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3209. {
  3210. int i;
  3211. for (i = 0; i < num_hdr; i++) {
  3212. if (!mg_strcasecmp(name, hdr[i].name)) {
  3213. return hdr[i].value;
  3214. }
  3215. }
  3216. return NULL;
  3217. }
  3218. #if defined(USE_WEBSOCKET)
  3219. /* Retrieve requested HTTP header multiple values, and return the number of
  3220. * found occurrences */
  3221. static int
  3222. get_req_headers(const struct mg_request_info *ri,
  3223. const char *name,
  3224. const char **output,
  3225. int output_max_size)
  3226. {
  3227. int i;
  3228. int cnt = 0;
  3229. if (ri) {
  3230. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3231. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3232. output[cnt++] = ri->http_headers[i].value;
  3233. }
  3234. }
  3235. }
  3236. return cnt;
  3237. }
  3238. #endif
  3239. const char *
  3240. mg_get_header(const struct mg_connection *conn, const char *name)
  3241. {
  3242. if (!conn) {
  3243. return NULL;
  3244. }
  3245. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3246. return get_header(conn->request_info.http_headers,
  3247. conn->request_info.num_headers,
  3248. name);
  3249. }
  3250. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3251. return get_header(conn->response_info.http_headers,
  3252. conn->response_info.num_headers,
  3253. name);
  3254. }
  3255. return NULL;
  3256. }
  3257. static const char *
  3258. get_http_version(const struct mg_connection *conn)
  3259. {
  3260. if (!conn) {
  3261. return NULL;
  3262. }
  3263. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3264. return conn->request_info.http_version;
  3265. }
  3266. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3267. return conn->response_info.http_version;
  3268. }
  3269. return NULL;
  3270. }
  3271. /* A helper function for traversing a comma separated list of values.
  3272. * It returns a list pointer shifted to the next value, or NULL if the end
  3273. * of the list found.
  3274. * Value is stored in val vector. If value has form "x=y", then eq_val
  3275. * vector is initialized to point to the "y" part, and val vector length
  3276. * is adjusted to point only to "x". */
  3277. static const char *
  3278. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3279. {
  3280. int end;
  3281. reparse:
  3282. if (val == NULL || list == NULL || *list == '\0') {
  3283. /* End of the list */
  3284. return NULL;
  3285. }
  3286. /* Skip over leading LWS */
  3287. while (*list == ' ' || *list == '\t')
  3288. list++;
  3289. val->ptr = list;
  3290. if ((list = strchr(val->ptr, ',')) != NULL) {
  3291. /* Comma found. Store length and shift the list ptr */
  3292. val->len = ((size_t)(list - val->ptr));
  3293. list++;
  3294. } else {
  3295. /* This value is the last one */
  3296. list = val->ptr + strlen(val->ptr);
  3297. val->len = ((size_t)(list - val->ptr));
  3298. }
  3299. /* Adjust length for trailing LWS */
  3300. end = (int)val->len - 1;
  3301. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3302. end--;
  3303. val->len = (size_t)(end) + (size_t)(1);
  3304. if (val->len == 0) {
  3305. /* Ignore any empty entries. */
  3306. goto reparse;
  3307. }
  3308. if (eq_val != NULL) {
  3309. /* Value has form "x=y", adjust pointers and lengths
  3310. * so that val points to "x", and eq_val points to "y". */
  3311. eq_val->len = 0;
  3312. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3313. if (eq_val->ptr != NULL) {
  3314. eq_val->ptr++; /* Skip over '=' character */
  3315. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3316. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3317. }
  3318. }
  3319. return list;
  3320. }
  3321. /* A helper function for checking if a comma separated list of values
  3322. * contains
  3323. * the given option (case insensitvely).
  3324. * 'header' can be NULL, in which case false is returned. */
  3325. static int
  3326. header_has_option(const char *header, const char *option)
  3327. {
  3328. struct vec opt_vec;
  3329. struct vec eq_vec;
  3330. DEBUG_ASSERT(option != NULL);
  3331. DEBUG_ASSERT(option[0] != '\0');
  3332. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3333. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3334. return 1;
  3335. }
  3336. return 0;
  3337. }
  3338. /* Perform case-insensitive match of string against pattern */
  3339. static ptrdiff_t
  3340. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3341. {
  3342. const char *or_str;
  3343. ptrdiff_t i, j, len, res;
  3344. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3345. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3346. return (res > 0) ? res
  3347. : match_prefix(or_str + 1,
  3348. (size_t)((pattern + pattern_len)
  3349. - (or_str + 1)),
  3350. str);
  3351. }
  3352. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3353. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3354. continue;
  3355. } else if (pattern[i] == '$') {
  3356. return (str[j] == '\0') ? j : -1;
  3357. } else if (pattern[i] == '*') {
  3358. i++;
  3359. if (pattern[i] == '*') {
  3360. i++;
  3361. len = (ptrdiff_t)strlen(str + j);
  3362. } else {
  3363. len = (ptrdiff_t)strcspn(str + j, "/");
  3364. }
  3365. if (i == (ptrdiff_t)pattern_len) {
  3366. return j + len;
  3367. }
  3368. do {
  3369. res = match_prefix(pattern + i,
  3370. (pattern_len - (size_t)i),
  3371. str + j + len);
  3372. } while (res == -1 && len-- > 0);
  3373. return (res == -1) ? -1 : j + res + len;
  3374. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3375. return -1;
  3376. }
  3377. }
  3378. return (ptrdiff_t)j;
  3379. }
  3380. static ptrdiff_t
  3381. match_prefix_strlen(const char *pattern, const char *str)
  3382. {
  3383. if (pattern == NULL) {
  3384. return -1;
  3385. }
  3386. return match_prefix(pattern, strlen(pattern), str);
  3387. }
  3388. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3389. * This function must tolerate situations when connection info is not
  3390. * set up, for example if request parsing failed. */
  3391. static int
  3392. should_keep_alive(const struct mg_connection *conn)
  3393. {
  3394. const char *http_version;
  3395. const char *header;
  3396. /* First satisfy needs of the server */
  3397. if ((conn == NULL) || conn->must_close) {
  3398. /* Close, if civetweb framework needs to close */
  3399. return 0;
  3400. }
  3401. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3402. /* Close, if keep alive is not enabled */
  3403. return 0;
  3404. }
  3405. /* Check explicit wish of the client */
  3406. header = mg_get_header(conn, "Connection");
  3407. if (header) {
  3408. /* If there is a connection header from the client, obey */
  3409. if (header_has_option(header, "keep-alive")) {
  3410. return 1;
  3411. }
  3412. return 0;
  3413. }
  3414. /* Use default of the standard */
  3415. http_version = get_http_version(conn);
  3416. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3417. /* HTTP 1.1 default is keep alive */
  3418. return 1;
  3419. }
  3420. /* HTTP 1.0 (and earlier) default is to close the connection */
  3421. return 0;
  3422. }
  3423. static int
  3424. should_decode_url(const struct mg_connection *conn)
  3425. {
  3426. if (!conn || !conn->dom_ctx) {
  3427. return 0;
  3428. }
  3429. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3430. }
  3431. static int
  3432. should_decode_query_string(const struct mg_connection *conn)
  3433. {
  3434. if (!conn || !conn->dom_ctx) {
  3435. return 0;
  3436. }
  3437. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3438. == 0);
  3439. }
  3440. static const char *
  3441. suggest_connection_header(const struct mg_connection *conn)
  3442. {
  3443. return should_keep_alive(conn) ? "keep-alive" : "close";
  3444. }
  3445. #include "response.inl"
  3446. static void
  3447. send_no_cache_header(struct mg_connection *conn)
  3448. {
  3449. /* Send all current and obsolete cache opt-out directives. */
  3450. mg_response_header_add(conn,
  3451. "Cache-Control",
  3452. "no-cache, no-store, "
  3453. "must-revalidate, private, max-age=0",
  3454. -1);
  3455. mg_response_header_add(conn, "Expires", "0", -1);
  3456. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3457. /* Obsolete, but still send it for HTTP/1.0 */
  3458. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3459. }
  3460. }
  3461. static void
  3462. send_static_cache_header(struct mg_connection *conn)
  3463. {
  3464. #if !defined(NO_CACHING)
  3465. int max_age;
  3466. char val[64];
  3467. const char *cache_control =
  3468. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3469. /* If there is a full cache-control option configured,0 use it */
  3470. if (cache_control != NULL) {
  3471. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3472. return;
  3473. }
  3474. /* Read the server config to check how long a file may be cached.
  3475. * The configuration is in seconds. */
  3476. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3477. if (max_age <= 0) {
  3478. /* 0 means "do not cache". All values <0 are reserved
  3479. * and may be used differently in the future. */
  3480. /* If a file should not be cached, do not only send
  3481. * max-age=0, but also pragmas and Expires headers. */
  3482. send_no_cache_header(conn);
  3483. return;
  3484. }
  3485. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3486. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3487. /* See also https://www.mnot.net/cache_docs/ */
  3488. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3489. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3490. * leap
  3491. * year to 31622400 seconds. For the moment, we just send whatever has
  3492. * been configured, still the behavior for >1 year should be considered
  3493. * as undefined. */
  3494. mg_snprintf(
  3495. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3496. mg_response_header_add(conn, "Cache-Control", val, -1);
  3497. #else /* NO_CACHING */
  3498. send_no_cache_header(conn);
  3499. #endif /* !NO_CACHING */
  3500. }
  3501. static void
  3502. send_additional_header(struct mg_connection *conn)
  3503. {
  3504. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3505. #if !defined(NO_SSL)
  3506. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3507. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3508. if (max_age >= 0) {
  3509. char val[64];
  3510. mg_snprintf(conn,
  3511. NULL,
  3512. val,
  3513. sizeof(val),
  3514. "max-age=%lu",
  3515. (unsigned long)max_age);
  3516. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3517. }
  3518. }
  3519. #endif
  3520. if (header && header[0]) {
  3521. mg_response_header_add_lines(conn, header);
  3522. }
  3523. }
  3524. static void
  3525. send_cors_header(struct mg_connection *conn)
  3526. {
  3527. const char *origin_hdr = mg_get_header(conn, "Origin");
  3528. const char *cors_orig_cfg =
  3529. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3530. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3531. /* Cross-origin resource sharing (CORS), see
  3532. * http://www.html5rocks.com/en/tutorials/cors/,
  3533. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3534. * CORS preflight is not supported for files. */
  3535. mg_response_header_add(conn,
  3536. "Access-Control-Allow-Origin",
  3537. cors_orig_cfg,
  3538. -1);
  3539. }
  3540. }
  3541. #if !defined(NO_FILESYSTEMS)
  3542. static void handle_file_based_request(struct mg_connection *conn,
  3543. const char *path,
  3544. struct mg_file *filep);
  3545. #endif /* NO_FILESYSTEMS */
  3546. const char *
  3547. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3548. {
  3549. /* See IANA HTTP status code assignment:
  3550. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3551. */
  3552. switch (response_code) {
  3553. /* RFC2616 Section 10.1 - Informational 1xx */
  3554. case 100:
  3555. return "Continue"; /* RFC2616 Section 10.1.1 */
  3556. case 101:
  3557. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3558. case 102:
  3559. return "Processing"; /* RFC2518 Section 10.1 */
  3560. /* RFC2616 Section 10.2 - Successful 2xx */
  3561. case 200:
  3562. return "OK"; /* RFC2616 Section 10.2.1 */
  3563. case 201:
  3564. return "Created"; /* RFC2616 Section 10.2.2 */
  3565. case 202:
  3566. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3567. case 203:
  3568. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3569. case 204:
  3570. return "No Content"; /* RFC2616 Section 10.2.5 */
  3571. case 205:
  3572. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3573. case 206:
  3574. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3575. case 207:
  3576. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3577. */
  3578. case 208:
  3579. return "Already Reported"; /* RFC5842 Section 7.1 */
  3580. case 226:
  3581. return "IM used"; /* RFC3229 Section 10.4.1 */
  3582. /* RFC2616 Section 10.3 - Redirection 3xx */
  3583. case 300:
  3584. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3585. case 301:
  3586. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3587. case 302:
  3588. return "Found"; /* RFC2616 Section 10.3.3 */
  3589. case 303:
  3590. return "See Other"; /* RFC2616 Section 10.3.4 */
  3591. case 304:
  3592. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3593. case 305:
  3594. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3595. case 307:
  3596. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3597. case 308:
  3598. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3599. /* RFC2616 Section 10.4 - Client Error 4xx */
  3600. case 400:
  3601. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3602. case 401:
  3603. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3604. case 402:
  3605. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3606. case 403:
  3607. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3608. case 404:
  3609. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3610. case 405:
  3611. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3612. case 406:
  3613. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3614. case 407:
  3615. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3616. case 408:
  3617. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3618. case 409:
  3619. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3620. case 410:
  3621. return "Gone"; /* RFC2616 Section 10.4.11 */
  3622. case 411:
  3623. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3624. case 412:
  3625. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3626. case 413:
  3627. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3628. case 414:
  3629. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3630. case 415:
  3631. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3632. case 416:
  3633. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3634. */
  3635. case 417:
  3636. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3637. case 421:
  3638. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3639. case 422:
  3640. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3641. * Section 11.2 */
  3642. case 423:
  3643. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3644. case 424:
  3645. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3646. * Section 11.4 */
  3647. case 426:
  3648. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3649. case 428:
  3650. return "Precondition Required"; /* RFC 6585, Section 3 */
  3651. case 429:
  3652. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3653. case 431:
  3654. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3655. case 451:
  3656. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3657. * Section 3 */
  3658. /* RFC2616 Section 10.5 - Server Error 5xx */
  3659. case 500:
  3660. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3661. case 501:
  3662. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3663. case 502:
  3664. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3665. case 503:
  3666. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3667. case 504:
  3668. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3669. case 505:
  3670. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3671. case 506:
  3672. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3673. case 507:
  3674. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3675. * Section 11.5 */
  3676. case 508:
  3677. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3678. case 510:
  3679. return "Not Extended"; /* RFC 2774, Section 7 */
  3680. case 511:
  3681. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3682. /* Other status codes, not shown in the IANA HTTP status code
  3683. * assignment.
  3684. * E.g., "de facto" standards due to common use, ... */
  3685. case 418:
  3686. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3687. case 419:
  3688. return "Authentication Timeout"; /* common use */
  3689. case 420:
  3690. return "Enhance Your Calm"; /* common use */
  3691. case 440:
  3692. return "Login Timeout"; /* common use */
  3693. case 509:
  3694. return "Bandwidth Limit Exceeded"; /* common use */
  3695. default:
  3696. /* This error code is unknown. This should not happen. */
  3697. if (conn) {
  3698. mg_cry_internal(conn,
  3699. "Unknown HTTP response code: %u",
  3700. response_code);
  3701. }
  3702. /* Return at least a category according to RFC 2616 Section 10. */
  3703. if (response_code >= 100 && response_code < 200) {
  3704. /* Unknown informational status code */
  3705. return "Information";
  3706. }
  3707. if (response_code >= 200 && response_code < 300) {
  3708. /* Unknown success code */
  3709. return "Success";
  3710. }
  3711. if (response_code >= 300 && response_code < 400) {
  3712. /* Unknown redirection code */
  3713. return "Redirection";
  3714. }
  3715. if (response_code >= 400 && response_code < 500) {
  3716. /* Unknown request error code */
  3717. return "Client Error";
  3718. }
  3719. if (response_code >= 500 && response_code < 600) {
  3720. /* Unknown server error code */
  3721. return "Server Error";
  3722. }
  3723. /* Response code not even within reasonable range */
  3724. return "";
  3725. }
  3726. }
  3727. static int
  3728. mg_send_http_error_impl(struct mg_connection *conn,
  3729. int status,
  3730. const char *fmt,
  3731. va_list args)
  3732. {
  3733. char errmsg_buf[MG_BUF_LEN];
  3734. va_list ap;
  3735. int has_body;
  3736. #if !defined(NO_FILESYSTEMS)
  3737. char path_buf[UTF8_PATH_MAX];
  3738. int len, i, page_handler_found, scope, truncated;
  3739. const char *error_handler = NULL;
  3740. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3741. const char *error_page_file_ext, *tstr;
  3742. #endif /* NO_FILESYSTEMS */
  3743. int handled_by_callback = 0;
  3744. if ((conn == NULL) || (fmt == NULL)) {
  3745. return -2;
  3746. }
  3747. /* Set status (for log) */
  3748. conn->status_code = status;
  3749. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3750. has_body = ((status > 199) && (status != 204) && (status != 304));
  3751. /* Prepare message in buf, if required */
  3752. if (has_body
  3753. || (!conn->in_error_handler
  3754. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3755. /* Store error message in errmsg_buf */
  3756. va_copy(ap, args);
  3757. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3758. va_end(ap);
  3759. /* In a debug build, print all html errors */
  3760. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3761. }
  3762. /* If there is a http_error callback, call it.
  3763. * But don't do it recursively, if callback calls mg_send_http_error again.
  3764. */
  3765. if (!conn->in_error_handler
  3766. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3767. /* Mark in_error_handler to avoid recursion and call user callback. */
  3768. conn->in_error_handler = 1;
  3769. handled_by_callback =
  3770. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3771. == 0);
  3772. conn->in_error_handler = 0;
  3773. }
  3774. if (!handled_by_callback) {
  3775. /* Check for recursion */
  3776. if (conn->in_error_handler) {
  3777. DEBUG_TRACE(
  3778. "Recursion when handling error %u - fall back to default",
  3779. status);
  3780. #if !defined(NO_FILESYSTEMS)
  3781. } else {
  3782. /* Send user defined error pages, if defined */
  3783. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3784. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3785. page_handler_found = 0;
  3786. if (error_handler != NULL) {
  3787. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3788. switch (scope) {
  3789. case 1: /* Handler for specific error, e.g. 404 error */
  3790. mg_snprintf(conn,
  3791. &truncated,
  3792. path_buf,
  3793. sizeof(path_buf) - 32,
  3794. "%serror%03u.",
  3795. error_handler,
  3796. status);
  3797. break;
  3798. case 2: /* Handler for error group, e.g., 5xx error
  3799. * handler
  3800. * for all server errors (500-599) */
  3801. mg_snprintf(conn,
  3802. &truncated,
  3803. path_buf,
  3804. sizeof(path_buf) - 32,
  3805. "%serror%01uxx.",
  3806. error_handler,
  3807. status / 100);
  3808. break;
  3809. default: /* Handler for all errors */
  3810. mg_snprintf(conn,
  3811. &truncated,
  3812. path_buf,
  3813. sizeof(path_buf) - 32,
  3814. "%serror.",
  3815. error_handler);
  3816. break;
  3817. }
  3818. /* String truncation in buf may only occur if
  3819. * error_handler is too long. This string is
  3820. * from the config, not from a client. */
  3821. (void)truncated;
  3822. /* The following code is redundant, but it should avoid
  3823. * false positives in static source code analyzers and
  3824. * vulnerability scanners.
  3825. */
  3826. path_buf[sizeof(path_buf) - 32] = 0;
  3827. len = (int)strlen(path_buf);
  3828. if (len > (int)sizeof(path_buf) - 32) {
  3829. len = (int)sizeof(path_buf) - 32;
  3830. }
  3831. /* Start with the file extenstion from the configuration. */
  3832. tstr = strchr(error_page_file_ext, '.');
  3833. while (tstr) {
  3834. for (i = 1;
  3835. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3836. i++) {
  3837. /* buffer overrun is not possible here, since
  3838. * (i < 32) && (len < sizeof(path_buf) - 32)
  3839. * ==> (i + len) < sizeof(path_buf) */
  3840. path_buf[len + i - 1] = tstr[i];
  3841. }
  3842. /* buffer overrun is not possible here, since
  3843. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3844. * ==> (i + len) <= sizeof(path_buf) */
  3845. path_buf[len + i - 1] = 0;
  3846. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3847. DEBUG_TRACE("Check error page %s - found",
  3848. path_buf);
  3849. page_handler_found = 1;
  3850. break;
  3851. }
  3852. DEBUG_TRACE("Check error page %s - not found",
  3853. path_buf);
  3854. /* Continue with the next file extenstion from the
  3855. * configuration (if there is a next one). */
  3856. tstr = strchr(tstr + i, '.');
  3857. }
  3858. }
  3859. }
  3860. if (page_handler_found) {
  3861. conn->in_error_handler = 1;
  3862. handle_file_based_request(conn, path_buf, &error_page_file);
  3863. conn->in_error_handler = 0;
  3864. return 0;
  3865. }
  3866. #endif /* NO_FILESYSTEMS */
  3867. }
  3868. /* No custom error page. Send default error page. */
  3869. conn->must_close = 1;
  3870. mg_response_header_start(conn, status);
  3871. send_no_cache_header(conn);
  3872. send_additional_header(conn);
  3873. send_cors_header(conn);
  3874. if (has_body) {
  3875. mg_response_header_add(conn,
  3876. "Content-Type",
  3877. "text/plain; charset=utf-8",
  3878. -1);
  3879. }
  3880. mg_response_header_send(conn);
  3881. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3882. if (has_body) {
  3883. /* For other errors, send a generic error message. */
  3884. const char *status_text = mg_get_response_code_text(conn, status);
  3885. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3886. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3887. } else {
  3888. /* No body allowed. Close the connection. */
  3889. DEBUG_TRACE("Error %i", status);
  3890. }
  3891. }
  3892. return 0;
  3893. }
  3894. int
  3895. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3896. {
  3897. va_list ap;
  3898. int ret;
  3899. va_start(ap, fmt);
  3900. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3901. va_end(ap);
  3902. return ret;
  3903. }
  3904. int
  3905. mg_send_http_ok(struct mg_connection *conn,
  3906. const char *mime_type,
  3907. long long content_length)
  3908. {
  3909. if ((mime_type == NULL) || (*mime_type == 0)) {
  3910. /* No content type defined: default to text/html */
  3911. mime_type = "text/html";
  3912. }
  3913. mg_response_header_start(conn, 200);
  3914. send_no_cache_header(conn);
  3915. send_additional_header(conn);
  3916. send_cors_header(conn);
  3917. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3918. if (content_length < 0) {
  3919. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3920. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3921. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3922. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3923. }
  3924. } else {
  3925. char len[32];
  3926. int trunc = 0;
  3927. mg_snprintf(conn,
  3928. &trunc,
  3929. len,
  3930. sizeof(len),
  3931. "%" UINT64_FMT,
  3932. (uint64_t)content_length);
  3933. if (!trunc) {
  3934. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3935. * !trunc is always true */
  3936. mg_response_header_add(conn, "Content-Length", len, -1);
  3937. }
  3938. }
  3939. mg_response_header_send(conn);
  3940. return 0;
  3941. }
  3942. int
  3943. mg_send_http_redirect(struct mg_connection *conn,
  3944. const char *target_url,
  3945. int redirect_code)
  3946. {
  3947. /* Send a 30x redirect response.
  3948. *
  3949. * Redirect types (status codes):
  3950. *
  3951. * Status | Perm/Temp | Method | Version
  3952. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3953. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3954. * 303 | temporary | always use GET | HTTP/1.1
  3955. * 307 | temporary | always keep method | HTTP/1.1
  3956. * 308 | permanent | always keep method | HTTP/1.1
  3957. */
  3958. #if defined(MG_SEND_REDIRECT_BODY)
  3959. char redirect_body[MG_BUF_LEN];
  3960. size_t content_len = 0;
  3961. char content_len_text[32];
  3962. #endif
  3963. /* In case redirect_code=0, use 307. */
  3964. if (redirect_code == 0) {
  3965. redirect_code = 307;
  3966. }
  3967. /* In case redirect_code is none of the above, return error. */
  3968. if ((redirect_code != 301) && (redirect_code != 302)
  3969. && (redirect_code != 303) && (redirect_code != 307)
  3970. && (redirect_code != 308)) {
  3971. /* Parameter error */
  3972. return -2;
  3973. }
  3974. /* If target_url is not defined, redirect to "/". */
  3975. if ((target_url == NULL) || (*target_url == 0)) {
  3976. target_url = "/";
  3977. }
  3978. #if defined(MG_SEND_REDIRECT_BODY)
  3979. /* TODO: condition name? */
  3980. /* Prepare a response body with a hyperlink.
  3981. *
  3982. * According to RFC2616 (and RFC1945 before):
  3983. * Unless the request method was HEAD, the entity of the
  3984. * response SHOULD contain a short hypertext note with a hyperlink to
  3985. * the new URI(s).
  3986. *
  3987. * However, this response body is not useful in M2M communication.
  3988. * Probably the original reason in the RFC was, clients not supporting
  3989. * a 30x HTTP redirect could still show the HTML page and let the user
  3990. * press the link. Since current browsers support 30x HTTP, the additional
  3991. * HTML body does not seem to make sense anymore.
  3992. *
  3993. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3994. * but it only notes:
  3995. * The server's response payload usually contains a short
  3996. * hypertext note with a hyperlink to the new URI(s).
  3997. *
  3998. * Deactivated by default. If you need the 30x body, set the define.
  3999. */
  4000. mg_snprintf(
  4001. conn,
  4002. NULL /* ignore truncation */,
  4003. redirect_body,
  4004. sizeof(redirect_body),
  4005. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4006. redirect_text,
  4007. target_url,
  4008. target_url);
  4009. content_len = strlen(reply);
  4010. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4011. #endif
  4012. /* Send all required headers */
  4013. mg_response_header_start(conn, redirect_code);
  4014. mg_response_header_add(conn, "Location", target_url, -1);
  4015. if ((redirect_code == 301) || (redirect_code == 308)) {
  4016. /* Permanent redirect */
  4017. send_static_cache_header(conn);
  4018. } else {
  4019. /* Temporary redirect */
  4020. send_no_cache_header(conn);
  4021. }
  4022. send_additional_header(conn);
  4023. send_cors_header(conn);
  4024. #if defined(MG_SEND_REDIRECT_BODY)
  4025. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4026. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4027. #else
  4028. mg_response_header_add(conn, "Content-Length", "0", 1);
  4029. #endif
  4030. mg_response_header_send(conn);
  4031. #if defined(MG_SEND_REDIRECT_BODY)
  4032. /* Send response body */
  4033. /* ... unless it is a HEAD request */
  4034. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4035. ret = mg_write(conn, redirect_body, content_len);
  4036. }
  4037. #endif
  4038. return 1;
  4039. }
  4040. #if defined(_WIN32)
  4041. /* Create substitutes for POSIX functions in Win32. */
  4042. #if defined(GCC_DIAGNOSTIC)
  4043. /* Show no warning in case system functions are not used. */
  4044. #pragma GCC diagnostic push
  4045. #pragma GCC diagnostic ignored "-Wunused-function"
  4046. #endif
  4047. static int
  4048. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4049. {
  4050. (void)unused;
  4051. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4052. InitializeCriticalSection(&mutex->sec);
  4053. return 0;
  4054. }
  4055. static int
  4056. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4057. {
  4058. DeleteCriticalSection(&mutex->sec);
  4059. return 0;
  4060. }
  4061. static int
  4062. pthread_mutex_lock(pthread_mutex_t *mutex)
  4063. {
  4064. EnterCriticalSection(&mutex->sec);
  4065. return 0;
  4066. }
  4067. static int
  4068. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4069. {
  4070. LeaveCriticalSection(&mutex->sec);
  4071. return 0;
  4072. }
  4073. FUNCTION_MAY_BE_UNUSED
  4074. static int
  4075. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4076. {
  4077. (void)unused;
  4078. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4079. cv->waiting_thread = NULL;
  4080. return 0;
  4081. }
  4082. FUNCTION_MAY_BE_UNUSED
  4083. static int
  4084. pthread_cond_timedwait(pthread_cond_t *cv,
  4085. pthread_mutex_t *mutex,
  4086. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4087. {
  4088. struct mg_workerTLS **ptls,
  4089. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4090. int ok;
  4091. uint64_t nsnow, nswaitabs;
  4092. int64_t nswaitrel;
  4093. DWORD mswaitrel;
  4094. pthread_mutex_lock(&cv->threadIdSec);
  4095. /* Add this thread to cv's waiting list */
  4096. ptls = &cv->waiting_thread;
  4097. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4098. ;
  4099. tls->next_waiting_thread = NULL;
  4100. *ptls = tls;
  4101. pthread_mutex_unlock(&cv->threadIdSec);
  4102. if (abstime) {
  4103. nsnow = mg_get_current_time_ns();
  4104. nswaitabs =
  4105. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4106. nswaitrel = nswaitabs - nsnow;
  4107. if (nswaitrel < 0) {
  4108. nswaitrel = 0;
  4109. }
  4110. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4111. } else {
  4112. mswaitrel = (DWORD)INFINITE;
  4113. }
  4114. pthread_mutex_unlock(mutex);
  4115. ok = (WAIT_OBJECT_0
  4116. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4117. if (!ok) {
  4118. ok = 1;
  4119. pthread_mutex_lock(&cv->threadIdSec);
  4120. ptls = &cv->waiting_thread;
  4121. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4122. if (*ptls == tls) {
  4123. *ptls = tls->next_waiting_thread;
  4124. ok = 0;
  4125. break;
  4126. }
  4127. }
  4128. pthread_mutex_unlock(&cv->threadIdSec);
  4129. if (ok) {
  4130. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4131. (DWORD)INFINITE);
  4132. }
  4133. }
  4134. /* This thread has been removed from cv's waiting list */
  4135. pthread_mutex_lock(mutex);
  4136. return ok ? 0 : -1;
  4137. }
  4138. FUNCTION_MAY_BE_UNUSED
  4139. static int
  4140. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4141. {
  4142. return pthread_cond_timedwait(cv, mutex, NULL);
  4143. }
  4144. FUNCTION_MAY_BE_UNUSED
  4145. static int
  4146. pthread_cond_signal(pthread_cond_t *cv)
  4147. {
  4148. HANDLE wkup = NULL;
  4149. BOOL ok = FALSE;
  4150. pthread_mutex_lock(&cv->threadIdSec);
  4151. if (cv->waiting_thread) {
  4152. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4153. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4154. ok = SetEvent(wkup);
  4155. DEBUG_ASSERT(ok);
  4156. }
  4157. pthread_mutex_unlock(&cv->threadIdSec);
  4158. return ok ? 0 : 1;
  4159. }
  4160. FUNCTION_MAY_BE_UNUSED
  4161. static int
  4162. pthread_cond_broadcast(pthread_cond_t *cv)
  4163. {
  4164. pthread_mutex_lock(&cv->threadIdSec);
  4165. while (cv->waiting_thread) {
  4166. pthread_cond_signal(cv);
  4167. }
  4168. pthread_mutex_unlock(&cv->threadIdSec);
  4169. return 0;
  4170. }
  4171. FUNCTION_MAY_BE_UNUSED
  4172. static int
  4173. pthread_cond_destroy(pthread_cond_t *cv)
  4174. {
  4175. pthread_mutex_lock(&cv->threadIdSec);
  4176. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4177. pthread_mutex_unlock(&cv->threadIdSec);
  4178. pthread_mutex_destroy(&cv->threadIdSec);
  4179. return 0;
  4180. }
  4181. #if defined(ALTERNATIVE_QUEUE)
  4182. FUNCTION_MAY_BE_UNUSED
  4183. static void *
  4184. event_create(void)
  4185. {
  4186. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4187. }
  4188. FUNCTION_MAY_BE_UNUSED
  4189. static int
  4190. event_wait(void *eventhdl)
  4191. {
  4192. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4193. return (res == WAIT_OBJECT_0);
  4194. }
  4195. FUNCTION_MAY_BE_UNUSED
  4196. static int
  4197. event_signal(void *eventhdl)
  4198. {
  4199. return (int)SetEvent((HANDLE)eventhdl);
  4200. }
  4201. FUNCTION_MAY_BE_UNUSED
  4202. static void
  4203. event_destroy(void *eventhdl)
  4204. {
  4205. CloseHandle((HANDLE)eventhdl);
  4206. }
  4207. #endif
  4208. #if defined(GCC_DIAGNOSTIC)
  4209. /* Enable unused function warning again */
  4210. #pragma GCC diagnostic pop
  4211. #endif
  4212. /* For Windows, change all slashes to backslashes in path names. */
  4213. static void
  4214. change_slashes_to_backslashes(char *path)
  4215. {
  4216. int i;
  4217. for (i = 0; path[i] != '\0'; i++) {
  4218. if (path[i] == '/') {
  4219. path[i] = '\\';
  4220. }
  4221. /* remove double backslash (check i > 0 to preserve UNC paths,
  4222. * like \\server\file.txt) */
  4223. if ((i > 0) && (path[i] == '\\')) {
  4224. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4225. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4226. }
  4227. }
  4228. }
  4229. }
  4230. static int
  4231. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4232. {
  4233. int diff;
  4234. do {
  4235. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4236. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4237. s1++;
  4238. s2++;
  4239. } while ((diff == 0) && (s1[-1] != L'\0'));
  4240. return diff;
  4241. }
  4242. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4243. * wbuf and wbuf_len is a target buffer and its length. */
  4244. static void
  4245. path_to_unicode(const struct mg_connection *conn,
  4246. const char *path,
  4247. wchar_t *wbuf,
  4248. size_t wbuf_len)
  4249. {
  4250. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4251. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4252. DWORD long_len, err;
  4253. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4254. mg_strlcpy(buf, path, sizeof(buf));
  4255. change_slashes_to_backslashes(buf);
  4256. /* Convert to Unicode and back. If doubly-converted string does not
  4257. * match the original, something is fishy, reject. */
  4258. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4259. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4260. WideCharToMultiByte(
  4261. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4262. if (strcmp(buf, buf2) != 0) {
  4263. wbuf[0] = L'\0';
  4264. }
  4265. /* Windows file systems are not case sensitive, but you can still use
  4266. * uppercase and lowercase letters (on all modern file systems).
  4267. * The server can check if the URI uses the same upper/lowercase
  4268. * letters an the file system, effectively making Windows servers
  4269. * case sensitive (like Linux servers are). It is still not possible
  4270. * to use two files with the same name in different cases on Windows
  4271. * (like /a and /A) - this would be possible in Linux.
  4272. * As a default, Windows is not case sensitive, but the case sensitive
  4273. * file name check can be activated by an additional configuration. */
  4274. if (conn) {
  4275. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4276. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4277. "yes")) {
  4278. /* Use case sensitive compare function */
  4279. fcompare = wcscmp;
  4280. }
  4281. }
  4282. (void)conn; /* conn is currently unused */
  4283. /* Only accept a full file path, not a Windows short (8.3) path. */
  4284. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4285. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4286. if (long_len == 0) {
  4287. err = GetLastError();
  4288. if (err == ERROR_FILE_NOT_FOUND) {
  4289. /* File does not exist. This is not always a problem here. */
  4290. return;
  4291. }
  4292. }
  4293. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4294. /* Short name is used. */
  4295. wbuf[0] = L'\0';
  4296. }
  4297. }
  4298. #if !defined(NO_FILESYSTEMS)
  4299. /* Get file information, return 1 if file exists, 0 if not */
  4300. static int
  4301. mg_stat(const struct mg_connection *conn,
  4302. const char *path,
  4303. struct mg_file_stat *filep)
  4304. {
  4305. wchar_t wbuf[UTF16_PATH_MAX];
  4306. WIN32_FILE_ATTRIBUTE_DATA info;
  4307. time_t creation_time;
  4308. size_t len;
  4309. if (!filep) {
  4310. return 0;
  4311. }
  4312. memset(filep, 0, sizeof(*filep));
  4313. if (mg_path_suspicious(conn, path)) {
  4314. return 0;
  4315. }
  4316. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4317. /* Windows happily opens files with some garbage at the end of file name.
  4318. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4319. * "a.cgi", despite one would expect an error back. */
  4320. len = strlen(path);
  4321. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4322. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4323. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4324. filep->last_modified =
  4325. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4326. info.ftLastWriteTime.dwHighDateTime);
  4327. /* On Windows, the file creation time can be higher than the
  4328. * modification time, e.g. when a file is copied.
  4329. * Since the Last-Modified timestamp is used for caching
  4330. * it should be based on the most recent timestamp. */
  4331. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4332. info.ftCreationTime.dwHighDateTime);
  4333. if (creation_time > filep->last_modified) {
  4334. filep->last_modified = creation_time;
  4335. }
  4336. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4337. return 1;
  4338. }
  4339. return 0;
  4340. }
  4341. #endif
  4342. static int
  4343. mg_remove(const struct mg_connection *conn, const char *path)
  4344. {
  4345. wchar_t wbuf[UTF16_PATH_MAX];
  4346. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4347. return DeleteFileW(wbuf) ? 0 : -1;
  4348. }
  4349. static int
  4350. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4351. {
  4352. wchar_t wbuf[UTF16_PATH_MAX];
  4353. (void)mode;
  4354. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4355. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4356. }
  4357. /* Create substitutes for POSIX functions in Win32. */
  4358. #if defined(GCC_DIAGNOSTIC)
  4359. /* Show no warning in case system functions are not used. */
  4360. #pragma GCC diagnostic push
  4361. #pragma GCC diagnostic ignored "-Wunused-function"
  4362. #endif
  4363. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4364. FUNCTION_MAY_BE_UNUSED
  4365. static DIR *
  4366. mg_opendir(const struct mg_connection *conn, const char *name)
  4367. {
  4368. DIR *dir = NULL;
  4369. wchar_t wpath[UTF16_PATH_MAX];
  4370. DWORD attrs;
  4371. if (name == NULL) {
  4372. SetLastError(ERROR_BAD_ARGUMENTS);
  4373. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4374. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4375. } else {
  4376. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4377. attrs = GetFileAttributesW(wpath);
  4378. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4379. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4380. (void)wcscat(wpath, L"\\*");
  4381. dir->handle = FindFirstFileW(wpath, &dir->info);
  4382. dir->result.d_name[0] = '\0';
  4383. } else {
  4384. mg_free(dir);
  4385. dir = NULL;
  4386. }
  4387. }
  4388. return dir;
  4389. }
  4390. FUNCTION_MAY_BE_UNUSED
  4391. static int
  4392. mg_closedir(DIR *dir)
  4393. {
  4394. int result = 0;
  4395. if (dir != NULL) {
  4396. if (dir->handle != INVALID_HANDLE_VALUE)
  4397. result = FindClose(dir->handle) ? 0 : -1;
  4398. mg_free(dir);
  4399. } else {
  4400. result = -1;
  4401. SetLastError(ERROR_BAD_ARGUMENTS);
  4402. }
  4403. return result;
  4404. }
  4405. FUNCTION_MAY_BE_UNUSED
  4406. static struct dirent *
  4407. mg_readdir(DIR *dir)
  4408. {
  4409. struct dirent *result = 0;
  4410. if (dir) {
  4411. if (dir->handle != INVALID_HANDLE_VALUE) {
  4412. result = &dir->result;
  4413. (void)WideCharToMultiByte(CP_UTF8,
  4414. 0,
  4415. dir->info.cFileName,
  4416. -1,
  4417. result->d_name,
  4418. sizeof(result->d_name),
  4419. NULL,
  4420. NULL);
  4421. if (!FindNextFileW(dir->handle, &dir->info)) {
  4422. (void)FindClose(dir->handle);
  4423. dir->handle = INVALID_HANDLE_VALUE;
  4424. }
  4425. } else {
  4426. SetLastError(ERROR_FILE_NOT_FOUND);
  4427. }
  4428. } else {
  4429. SetLastError(ERROR_BAD_ARGUMENTS);
  4430. }
  4431. return result;
  4432. }
  4433. #if !defined(HAVE_POLL)
  4434. #undef POLLIN
  4435. #undef POLLPRI
  4436. #undef POLLOUT
  4437. #undef POLLERR
  4438. #define POLLIN (1) /* Data ready - read will not block. */
  4439. #define POLLPRI (2) /* Priority data ready. */
  4440. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4441. #define POLLERR (8) /* Error event */
  4442. FUNCTION_MAY_BE_UNUSED
  4443. static int
  4444. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4445. {
  4446. struct timeval tv;
  4447. fd_set rset;
  4448. fd_set wset;
  4449. fd_set eset;
  4450. unsigned int i;
  4451. int result;
  4452. SOCKET maxfd = 0;
  4453. memset(&tv, 0, sizeof(tv));
  4454. tv.tv_sec = milliseconds / 1000;
  4455. tv.tv_usec = (milliseconds % 1000) * 1000;
  4456. FD_ZERO(&rset);
  4457. FD_ZERO(&wset);
  4458. FD_ZERO(&eset);
  4459. for (i = 0; i < n; i++) {
  4460. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4461. if (pfd[i].events & POLLIN) {
  4462. FD_SET(pfd[i].fd, &rset);
  4463. }
  4464. if (pfd[i].events & POLLOUT) {
  4465. FD_SET(pfd[i].fd, &wset);
  4466. }
  4467. /* Check for errors for any FD in the set */
  4468. FD_SET(pfd[i].fd, &eset);
  4469. }
  4470. pfd[i].revents = 0;
  4471. if (pfd[i].fd > maxfd) {
  4472. maxfd = pfd[i].fd;
  4473. }
  4474. }
  4475. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4476. for (i = 0; i < n; i++) {
  4477. if (FD_ISSET(pfd[i].fd, &rset)) {
  4478. pfd[i].revents |= POLLIN;
  4479. }
  4480. if (FD_ISSET(pfd[i].fd, &wset)) {
  4481. pfd[i].revents |= POLLOUT;
  4482. }
  4483. if (FD_ISSET(pfd[i].fd, &eset)) {
  4484. pfd[i].revents |= POLLERR;
  4485. }
  4486. }
  4487. }
  4488. /* We should subtract the time used in select from remaining
  4489. * "milliseconds", in particular if called from mg_poll with a
  4490. * timeout quantum.
  4491. * Unfortunately, the remaining time is not stored in "tv" in all
  4492. * implementations, so the result in "tv" must be considered undefined.
  4493. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4494. return result;
  4495. }
  4496. #endif /* HAVE_POLL */
  4497. #if defined(GCC_DIAGNOSTIC)
  4498. /* Enable unused function warning again */
  4499. #pragma GCC diagnostic pop
  4500. #endif
  4501. static void
  4502. set_close_on_exec(SOCKET sock,
  4503. const struct mg_connection *conn /* may be null */,
  4504. struct mg_context *ctx /* may be null */)
  4505. {
  4506. (void)conn; /* Unused. */
  4507. (void)ctx;
  4508. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4509. }
  4510. int
  4511. mg_start_thread(mg_thread_func_t f, void *p)
  4512. {
  4513. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4514. /* Compile-time option to control stack size, e.g.
  4515. * -DUSE_STACK_SIZE=16384
  4516. */
  4517. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4518. == ((uintptr_t)(-1L)))
  4519. ? -1
  4520. : 0);
  4521. #else
  4522. return (
  4523. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4524. ? -1
  4525. : 0);
  4526. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4527. }
  4528. /* Start a thread storing the thread context. */
  4529. static int
  4530. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4531. void *p,
  4532. pthread_t *threadidptr)
  4533. {
  4534. uintptr_t uip;
  4535. HANDLE threadhandle;
  4536. int result = -1;
  4537. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4538. threadhandle = (HANDLE)uip;
  4539. if ((uip != 0) && (threadidptr != NULL)) {
  4540. *threadidptr = threadhandle;
  4541. result = 0;
  4542. }
  4543. return result;
  4544. }
  4545. /* Wait for a thread to finish. */
  4546. static int
  4547. mg_join_thread(pthread_t threadid)
  4548. {
  4549. int result;
  4550. DWORD dwevent;
  4551. result = -1;
  4552. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4553. if (dwevent == WAIT_FAILED) {
  4554. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4555. } else {
  4556. if (dwevent == WAIT_OBJECT_0) {
  4557. CloseHandle(threadid);
  4558. result = 0;
  4559. }
  4560. }
  4561. return result;
  4562. }
  4563. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4564. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4565. /* Create substitutes for POSIX functions in Win32. */
  4566. #if defined(GCC_DIAGNOSTIC)
  4567. /* Show no warning in case system functions are not used. */
  4568. #pragma GCC diagnostic push
  4569. #pragma GCC diagnostic ignored "-Wunused-function"
  4570. #endif
  4571. FUNCTION_MAY_BE_UNUSED
  4572. static HANDLE
  4573. dlopen(const char *dll_name, int flags)
  4574. {
  4575. wchar_t wbuf[UTF16_PATH_MAX];
  4576. (void)flags;
  4577. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4578. return LoadLibraryW(wbuf);
  4579. }
  4580. FUNCTION_MAY_BE_UNUSED
  4581. static int
  4582. dlclose(void *handle)
  4583. {
  4584. int result;
  4585. if (FreeLibrary((HMODULE)handle) != 0) {
  4586. result = 0;
  4587. } else {
  4588. result = -1;
  4589. }
  4590. return result;
  4591. }
  4592. #if defined(GCC_DIAGNOSTIC)
  4593. /* Enable unused function warning again */
  4594. #pragma GCC diagnostic pop
  4595. #endif
  4596. #endif
  4597. #if !defined(NO_CGI)
  4598. #define SIGKILL (0)
  4599. static int
  4600. kill(pid_t pid, int sig_num)
  4601. {
  4602. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4603. (void)CloseHandle((HANDLE)pid);
  4604. return 0;
  4605. }
  4606. #if !defined(WNOHANG)
  4607. #define WNOHANG (1)
  4608. #endif
  4609. static pid_t
  4610. waitpid(pid_t pid, int *status, int flags)
  4611. {
  4612. DWORD timeout = INFINITE;
  4613. DWORD waitres;
  4614. (void)status; /* Currently not used by any client here */
  4615. if ((flags | WNOHANG) == WNOHANG) {
  4616. timeout = 0;
  4617. }
  4618. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4619. if (waitres == WAIT_OBJECT_0) {
  4620. return pid;
  4621. }
  4622. if (waitres == WAIT_TIMEOUT) {
  4623. return 0;
  4624. }
  4625. return (pid_t)-1;
  4626. }
  4627. static void
  4628. trim_trailing_whitespaces(char *s)
  4629. {
  4630. char *e = s + strlen(s);
  4631. while ((e > s) && isspace((unsigned char)e[-1])) {
  4632. *(--e) = '\0';
  4633. }
  4634. }
  4635. static pid_t
  4636. spawn_process(struct mg_connection *conn,
  4637. const char *prog,
  4638. char *envblk,
  4639. char *envp[],
  4640. int fdin[2],
  4641. int fdout[2],
  4642. int fderr[2],
  4643. const char *dir,
  4644. unsigned char cgi_config_idx)
  4645. {
  4646. HANDLE me;
  4647. char *interp;
  4648. char *interp_arg = 0;
  4649. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4650. int truncated;
  4651. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4652. STARTUPINFOA si;
  4653. PROCESS_INFORMATION pi = {0};
  4654. (void)envp;
  4655. memset(&si, 0, sizeof(si));
  4656. si.cb = sizeof(si);
  4657. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4658. si.wShowWindow = SW_HIDE;
  4659. me = GetCurrentProcess();
  4660. DuplicateHandle(me,
  4661. (HANDLE)_get_osfhandle(fdin[0]),
  4662. me,
  4663. &si.hStdInput,
  4664. 0,
  4665. TRUE,
  4666. DUPLICATE_SAME_ACCESS);
  4667. DuplicateHandle(me,
  4668. (HANDLE)_get_osfhandle(fdout[1]),
  4669. me,
  4670. &si.hStdOutput,
  4671. 0,
  4672. TRUE,
  4673. DUPLICATE_SAME_ACCESS);
  4674. DuplicateHandle(me,
  4675. (HANDLE)_get_osfhandle(fderr[1]),
  4676. me,
  4677. &si.hStdError,
  4678. 0,
  4679. TRUE,
  4680. DUPLICATE_SAME_ACCESS);
  4681. /* Mark handles that should not be inherited. See
  4682. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4683. */
  4684. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4685. HANDLE_FLAG_INHERIT,
  4686. 0);
  4687. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4688. HANDLE_FLAG_INHERIT,
  4689. 0);
  4690. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4691. HANDLE_FLAG_INHERIT,
  4692. 0);
  4693. /* First check, if there is a CGI interpreter configured for all CGI
  4694. * scripts. */
  4695. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4696. if (interp != NULL) {
  4697. /* If there is a configured interpreter, check for additional arguments
  4698. */
  4699. interp_arg =
  4700. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4701. } else {
  4702. /* Otherwise, the interpreter must be stated in the first line of the
  4703. * CGI script file, after a #! (shebang) mark. */
  4704. buf[0] = buf[1] = '\0';
  4705. /* Get the full script path */
  4706. mg_snprintf(
  4707. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4708. if (truncated) {
  4709. pi.hProcess = (pid_t)-1;
  4710. goto spawn_cleanup;
  4711. }
  4712. /* Open the script file, to read the first line */
  4713. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4714. /* Read the first line of the script into the buffer */
  4715. mg_fgets(buf, sizeof(buf), &file);
  4716. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4717. buf[sizeof(buf) - 1] = '\0';
  4718. }
  4719. if ((buf[0] == '#') && (buf[1] == '!')) {
  4720. trim_trailing_whitespaces(buf + 2);
  4721. } else {
  4722. buf[2] = '\0';
  4723. }
  4724. interp = buf + 2;
  4725. }
  4726. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4727. if (interp[0] != '\0') {
  4728. /* This is an interpreted script file. We must call the interpreter. */
  4729. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4730. mg_snprintf(conn,
  4731. &truncated,
  4732. cmdline,
  4733. sizeof(cmdline),
  4734. "\"%s\" %s \"%s\\%s\"",
  4735. interp,
  4736. interp_arg,
  4737. full_dir,
  4738. prog);
  4739. } else {
  4740. mg_snprintf(conn,
  4741. &truncated,
  4742. cmdline,
  4743. sizeof(cmdline),
  4744. "\"%s\" \"%s\\%s\"",
  4745. interp,
  4746. full_dir,
  4747. prog);
  4748. }
  4749. } else {
  4750. /* This is (probably) a compiled program. We call it directly. */
  4751. mg_snprintf(conn,
  4752. &truncated,
  4753. cmdline,
  4754. sizeof(cmdline),
  4755. "\"%s\\%s\"",
  4756. full_dir,
  4757. prog);
  4758. }
  4759. if (truncated) {
  4760. pi.hProcess = (pid_t)-1;
  4761. goto spawn_cleanup;
  4762. }
  4763. DEBUG_TRACE("Running [%s]", cmdline);
  4764. if (CreateProcessA(NULL,
  4765. cmdline,
  4766. NULL,
  4767. NULL,
  4768. TRUE,
  4769. CREATE_NEW_PROCESS_GROUP,
  4770. envblk,
  4771. NULL,
  4772. &si,
  4773. &pi)
  4774. == 0) {
  4775. mg_cry_internal(
  4776. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4777. pi.hProcess = (pid_t)-1;
  4778. /* goto spawn_cleanup; */
  4779. }
  4780. spawn_cleanup:
  4781. (void)CloseHandle(si.hStdOutput);
  4782. (void)CloseHandle(si.hStdError);
  4783. (void)CloseHandle(si.hStdInput);
  4784. if (pi.hThread != NULL) {
  4785. (void)CloseHandle(pi.hThread);
  4786. }
  4787. return (pid_t)pi.hProcess;
  4788. }
  4789. #endif /* !NO_CGI */
  4790. static int
  4791. set_blocking_mode(SOCKET sock)
  4792. {
  4793. unsigned long non_blocking = 0;
  4794. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4795. }
  4796. static int
  4797. set_non_blocking_mode(SOCKET sock)
  4798. {
  4799. unsigned long non_blocking = 1;
  4800. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4801. }
  4802. #else
  4803. #if !defined(NO_FILESYSTEMS)
  4804. static int
  4805. mg_stat(const struct mg_connection *conn,
  4806. const char *path,
  4807. struct mg_file_stat *filep)
  4808. {
  4809. struct stat st;
  4810. if (!filep) {
  4811. return 0;
  4812. }
  4813. memset(filep, 0, sizeof(*filep));
  4814. if (mg_path_suspicious(conn, path)) {
  4815. return 0;
  4816. }
  4817. if (0 == stat(path, &st)) {
  4818. filep->size = (uint64_t)(st.st_size);
  4819. filep->last_modified = st.st_mtime;
  4820. filep->is_directory = S_ISDIR(st.st_mode);
  4821. return 1;
  4822. }
  4823. return 0;
  4824. }
  4825. #endif /* NO_FILESYSTEMS */
  4826. static void
  4827. set_close_on_exec(int fd,
  4828. const struct mg_connection *conn /* may be null */,
  4829. struct mg_context *ctx /* may be null */)
  4830. {
  4831. #if defined(__ZEPHYR__)
  4832. (void)fd;
  4833. (void)conn;
  4834. (void)ctx;
  4835. #else
  4836. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4837. if (conn || ctx) {
  4838. struct mg_connection fc;
  4839. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4840. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4841. __func__,
  4842. strerror(ERRNO));
  4843. }
  4844. }
  4845. #endif
  4846. }
  4847. int
  4848. mg_start_thread(mg_thread_func_t func, void *param)
  4849. {
  4850. pthread_t thread_id;
  4851. pthread_attr_t attr;
  4852. int result;
  4853. (void)pthread_attr_init(&attr);
  4854. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4855. #if defined(__ZEPHYR__)
  4856. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4857. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4858. /* Compile-time option to control stack size,
  4859. * e.g. -DUSE_STACK_SIZE=16384 */
  4860. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4861. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4862. result = pthread_create(&thread_id, &attr, func, param);
  4863. pthread_attr_destroy(&attr);
  4864. return result;
  4865. }
  4866. /* Start a thread storing the thread context. */
  4867. static int
  4868. mg_start_thread_with_id(mg_thread_func_t func,
  4869. void *param,
  4870. pthread_t *threadidptr)
  4871. {
  4872. pthread_t thread_id;
  4873. pthread_attr_t attr;
  4874. int result;
  4875. (void)pthread_attr_init(&attr);
  4876. #if defined(__ZEPHYR__)
  4877. pthread_attr_setstack(&attr,
  4878. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4879. ZEPHYR_STACK_SIZE);
  4880. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4881. /* Compile-time option to control stack size,
  4882. * e.g. -DUSE_STACK_SIZE=16384 */
  4883. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4884. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4885. result = pthread_create(&thread_id, &attr, func, param);
  4886. pthread_attr_destroy(&attr);
  4887. if ((result == 0) && (threadidptr != NULL)) {
  4888. *threadidptr = thread_id;
  4889. }
  4890. return result;
  4891. }
  4892. /* Wait for a thread to finish. */
  4893. static int
  4894. mg_join_thread(pthread_t threadid)
  4895. {
  4896. int result;
  4897. result = pthread_join(threadid, NULL);
  4898. return result;
  4899. }
  4900. #if !defined(NO_CGI)
  4901. static pid_t
  4902. spawn_process(struct mg_connection *conn,
  4903. const char *prog,
  4904. char *envblk,
  4905. char *envp[],
  4906. int fdin[2],
  4907. int fdout[2],
  4908. int fderr[2],
  4909. const char *dir,
  4910. unsigned char cgi_config_idx)
  4911. {
  4912. pid_t pid;
  4913. const char *interp;
  4914. (void)envblk;
  4915. if ((pid = fork()) == -1) {
  4916. /* Parent */
  4917. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4918. } else if (pid != 0) {
  4919. /* Make sure children close parent-side descriptors.
  4920. * The caller will close the child-side immediately. */
  4921. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4922. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4923. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4924. } else {
  4925. /* Child */
  4926. if (chdir(dir) != 0) {
  4927. mg_cry_internal(
  4928. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4929. } else if (dup2(fdin[0], 0) == -1) {
  4930. mg_cry_internal(conn,
  4931. "%s: dup2(%d, 0): %s",
  4932. __func__,
  4933. fdin[0],
  4934. strerror(ERRNO));
  4935. } else if (dup2(fdout[1], 1) == -1) {
  4936. mg_cry_internal(conn,
  4937. "%s: dup2(%d, 1): %s",
  4938. __func__,
  4939. fdout[1],
  4940. strerror(ERRNO));
  4941. } else if (dup2(fderr[1], 2) == -1) {
  4942. mg_cry_internal(conn,
  4943. "%s: dup2(%d, 2): %s",
  4944. __func__,
  4945. fderr[1],
  4946. strerror(ERRNO));
  4947. } else {
  4948. struct sigaction sa;
  4949. /* Keep stderr and stdout in two different pipes.
  4950. * Stdout will be sent back to the client,
  4951. * stderr should go into a server error log. */
  4952. (void)close(fdin[0]);
  4953. (void)close(fdout[1]);
  4954. (void)close(fderr[1]);
  4955. /* Close write end fdin and read end fdout and fderr */
  4956. (void)close(fdin[1]);
  4957. (void)close(fdout[0]);
  4958. (void)close(fderr[0]);
  4959. /* After exec, all signal handlers are restored to their default
  4960. * values, with one exception of SIGCHLD. According to
  4961. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4962. * will leave unchanged after exec if it was set to be ignored.
  4963. * Restore it to default action. */
  4964. memset(&sa, 0, sizeof(sa));
  4965. sa.sa_handler = SIG_DFL;
  4966. sigaction(SIGCHLD, &sa, NULL);
  4967. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4968. if (interp == NULL) {
  4969. /* no interpreter configured, call the programm directly */
  4970. (void)execle(prog, prog, NULL, envp);
  4971. mg_cry_internal(conn,
  4972. "%s: execle(%s): %s",
  4973. __func__,
  4974. prog,
  4975. strerror(ERRNO));
  4976. } else {
  4977. /* call the configured interpreter */
  4978. const char *interp_args =
  4979. conn->dom_ctx
  4980. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4981. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4982. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4983. } else {
  4984. (void)execle(interp, interp, prog, NULL, envp);
  4985. }
  4986. mg_cry_internal(conn,
  4987. "%s: execle(%s %s): %s",
  4988. __func__,
  4989. interp,
  4990. prog,
  4991. strerror(ERRNO));
  4992. }
  4993. }
  4994. exit(EXIT_FAILURE);
  4995. }
  4996. return pid;
  4997. }
  4998. #endif /* !NO_CGI */
  4999. static int
  5000. set_non_blocking_mode(SOCKET sock)
  5001. {
  5002. int flags = fcntl(sock, F_GETFL, 0);
  5003. if (flags < 0) {
  5004. return -1;
  5005. }
  5006. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5007. return -1;
  5008. }
  5009. return 0;
  5010. }
  5011. static int
  5012. set_blocking_mode(SOCKET sock)
  5013. {
  5014. int flags = fcntl(sock, F_GETFL, 0);
  5015. if (flags < 0) {
  5016. return -1;
  5017. }
  5018. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5019. return -1;
  5020. }
  5021. return 0;
  5022. }
  5023. #endif /* _WIN32 / else */
  5024. /* End of initial operating system specific define block. */
  5025. /* Get a random number (independent of C rand function) */
  5026. static uint64_t
  5027. get_random(void)
  5028. {
  5029. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5030. static uint64_t lcg = 0; /* Linear congruential generator */
  5031. uint64_t now = mg_get_current_time_ns();
  5032. if (lfsr == 0) {
  5033. /* lfsr will be only 0 if has not been initialized,
  5034. * so this code is called only once. */
  5035. lfsr = mg_get_current_time_ns();
  5036. lcg = mg_get_current_time_ns();
  5037. } else {
  5038. /* Get the next step of both random number generators. */
  5039. lfsr = (lfsr >> 1)
  5040. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5041. << 63);
  5042. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5043. }
  5044. /* Combining two pseudo-random number generators and a high resolution
  5045. * part
  5046. * of the current server time will make it hard (impossible?) to guess
  5047. * the
  5048. * next number. */
  5049. return (lfsr ^ lcg ^ now);
  5050. }
  5051. static int
  5052. mg_poll(struct mg_pollfd *pfd,
  5053. unsigned int n,
  5054. int milliseconds,
  5055. const stop_flag_t *stop_flag)
  5056. {
  5057. /* Call poll, but only for a maximum time of a few seconds.
  5058. * This will allow to stop the server after some seconds, instead
  5059. * of having to wait for a long socket timeout. */
  5060. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5061. int check_pollerr = 0;
  5062. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5063. /* If we wait for only one file descriptor, wait on error as well */
  5064. pfd[0].events |= POLLERR;
  5065. check_pollerr = 1;
  5066. }
  5067. do {
  5068. int result;
  5069. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5070. /* Shut down signal */
  5071. return -2;
  5072. }
  5073. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5074. ms_now = milliseconds;
  5075. }
  5076. result = poll(pfd, n, ms_now);
  5077. if (result != 0) {
  5078. /* Poll returned either success (1) or error (-1).
  5079. * Forward both to the caller. */
  5080. if ((check_pollerr)
  5081. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5082. == POLLERR)) {
  5083. /* One and only file descriptor returned error */
  5084. return -1;
  5085. }
  5086. return result;
  5087. }
  5088. /* Poll returned timeout (0). */
  5089. if (milliseconds > 0) {
  5090. milliseconds -= ms_now;
  5091. }
  5092. } while (milliseconds > 0);
  5093. /* timeout: return 0 */
  5094. return 0;
  5095. }
  5096. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5097. * descriptor.
  5098. * Return value:
  5099. * >=0 .. number of bytes successfully written
  5100. * -1 .. timeout
  5101. * -2 .. error
  5102. */
  5103. static int
  5104. push_inner(struct mg_context *ctx,
  5105. FILE *fp,
  5106. SOCKET sock,
  5107. SSL *ssl,
  5108. const char *buf,
  5109. int len,
  5110. double timeout)
  5111. {
  5112. uint64_t start = 0, now = 0, timeout_ns = 0;
  5113. int n, err;
  5114. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5115. #if defined(_WIN32)
  5116. typedef int len_t;
  5117. #else
  5118. typedef size_t len_t;
  5119. #endif
  5120. if (timeout > 0) {
  5121. now = mg_get_current_time_ns();
  5122. start = now;
  5123. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5124. }
  5125. if (ctx == NULL) {
  5126. return -2;
  5127. }
  5128. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5129. if (ssl) {
  5130. return -2;
  5131. }
  5132. #endif
  5133. /* Try to read until it succeeds, fails, times out, or the server
  5134. * shuts down. */
  5135. for (;;) {
  5136. #if defined(USE_MBEDTLS)
  5137. if (ssl != NULL) {
  5138. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5139. if (n <= 0) {
  5140. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5141. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5142. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5143. n = 0;
  5144. } else {
  5145. fprintf(stderr, "SSL write failed, error %d\n", n);
  5146. return -2;
  5147. }
  5148. } else {
  5149. err = 0;
  5150. }
  5151. } else
  5152. #elif !defined(NO_SSL)
  5153. if (ssl != NULL) {
  5154. ERR_clear_error();
  5155. n = SSL_write(ssl, buf, len);
  5156. if (n <= 0) {
  5157. err = SSL_get_error(ssl, n);
  5158. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5159. err = ERRNO;
  5160. } else if ((err == SSL_ERROR_WANT_READ)
  5161. || (err == SSL_ERROR_WANT_WRITE)) {
  5162. n = 0;
  5163. } else {
  5164. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5165. ERR_clear_error();
  5166. return -2;
  5167. }
  5168. ERR_clear_error();
  5169. } else {
  5170. err = 0;
  5171. }
  5172. } else
  5173. #endif
  5174. if (fp != NULL) {
  5175. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5176. if (ferror(fp)) {
  5177. n = -1;
  5178. err = ERRNO;
  5179. } else {
  5180. err = 0;
  5181. }
  5182. } else {
  5183. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5184. err = (n < 0) ? ERRNO : 0;
  5185. #if defined(_WIN32)
  5186. if (err == WSAEWOULDBLOCK) {
  5187. err = 0;
  5188. n = 0;
  5189. }
  5190. #else
  5191. if (ERROR_TRY_AGAIN(err)) {
  5192. err = 0;
  5193. n = 0;
  5194. }
  5195. #endif
  5196. if (n < 0) {
  5197. /* shutdown of the socket at client side */
  5198. return -2;
  5199. }
  5200. }
  5201. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5202. return -2;
  5203. }
  5204. if ((n > 0) || ((n == 0) && (len == 0))) {
  5205. /* some data has been read, or no data was requested */
  5206. return n;
  5207. }
  5208. if (n < 0) {
  5209. /* socket error - check errno */
  5210. DEBUG_TRACE("send() failed, error %d", err);
  5211. /* TODO (mid): error handling depending on the error code.
  5212. * These codes are different between Windows and Linux.
  5213. * Currently there is no problem with failing send calls,
  5214. * if there is a reproducible situation, it should be
  5215. * investigated in detail.
  5216. */
  5217. return -2;
  5218. }
  5219. /* Only in case n=0 (timeout), repeat calling the write function */
  5220. /* If send failed, wait before retry */
  5221. if (fp != NULL) {
  5222. /* For files, just wait a fixed time.
  5223. * Maybe it helps, maybe not. */
  5224. mg_sleep(5);
  5225. } else {
  5226. /* For sockets, wait for the socket using poll */
  5227. struct mg_pollfd pfd[1];
  5228. int pollres;
  5229. pfd[0].fd = sock;
  5230. pfd[0].events = POLLOUT;
  5231. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5232. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5233. return -2;
  5234. }
  5235. if (pollres > 0) {
  5236. continue;
  5237. }
  5238. }
  5239. if (timeout > 0) {
  5240. now = mg_get_current_time_ns();
  5241. if ((now - start) > timeout_ns) {
  5242. /* Timeout */
  5243. break;
  5244. }
  5245. }
  5246. }
  5247. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5248. used */
  5249. return -1;
  5250. }
  5251. static int
  5252. push_all(struct mg_context *ctx,
  5253. FILE *fp,
  5254. SOCKET sock,
  5255. SSL *ssl,
  5256. const char *buf,
  5257. int len)
  5258. {
  5259. double timeout = -1.0;
  5260. int n, nwritten = 0;
  5261. if (ctx == NULL) {
  5262. return -1;
  5263. }
  5264. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5265. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5266. }
  5267. if (timeout <= 0.0) {
  5268. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5269. / 1000.0;
  5270. }
  5271. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5272. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5273. if (n < 0) {
  5274. if (nwritten == 0) {
  5275. nwritten = -1; /* Propagate the error */
  5276. }
  5277. break;
  5278. } else if (n == 0) {
  5279. break; /* No more data to write */
  5280. } else {
  5281. nwritten += n;
  5282. len -= n;
  5283. }
  5284. }
  5285. return nwritten;
  5286. }
  5287. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5288. * Return value:
  5289. * >=0 .. number of bytes successfully read
  5290. * -1 .. timeout
  5291. * -2 .. error
  5292. */
  5293. static int
  5294. pull_inner(FILE *fp,
  5295. struct mg_connection *conn,
  5296. char *buf,
  5297. int len,
  5298. double timeout)
  5299. {
  5300. int nread, err = 0;
  5301. #if defined(_WIN32)
  5302. typedef int len_t;
  5303. #else
  5304. typedef size_t len_t;
  5305. #endif
  5306. /* We need an additional wait loop around this, because in some cases
  5307. * with TLSwe may get data from the socket but not from SSL_read.
  5308. * In this case we need to repeat at least once.
  5309. */
  5310. if (fp != NULL) {
  5311. /* Use read() instead of fread(), because if we're reading from the
  5312. * CGI pipe, fread() may block until IO buffer is filled up. We
  5313. * cannot afford to block and must pass all read bytes immediately
  5314. * to the client. */
  5315. nread = (int)read(fileno(fp), buf, (size_t)len);
  5316. err = (nread < 0) ? ERRNO : 0;
  5317. if ((nread == 0) && (len > 0)) {
  5318. /* Should get data, but got EOL */
  5319. return -2;
  5320. }
  5321. #if defined(USE_MBEDTLS)
  5322. } else if (conn->ssl != NULL) {
  5323. struct mg_pollfd pfd[1];
  5324. int to_read;
  5325. int pollres;
  5326. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5327. if (to_read > 0) {
  5328. /* We already know there is no more data buffered in conn->buf
  5329. * but there is more available in the SSL layer. So don't poll
  5330. * conn->client.sock yet. */
  5331. pollres = 1;
  5332. if (to_read > len)
  5333. to_read = len;
  5334. } else {
  5335. pfd[0].fd = conn->client.sock;
  5336. pfd[0].events = POLLIN;
  5337. to_read = len;
  5338. pollres = mg_poll(pfd,
  5339. 1,
  5340. (int)(timeout * 1000.0),
  5341. &(conn->phys_ctx->stop_flag));
  5342. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5343. return -2;
  5344. }
  5345. }
  5346. if (pollres > 0) {
  5347. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5348. if (nread <= 0) {
  5349. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5350. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5351. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5352. nread = 0;
  5353. } else {
  5354. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5355. return -2;
  5356. }
  5357. } else {
  5358. err = 0;
  5359. }
  5360. } else if (pollres < 0) {
  5361. /* Error */
  5362. return -2;
  5363. } else {
  5364. /* pollres = 0 means timeout */
  5365. nread = 0;
  5366. }
  5367. #elif !defined(NO_SSL)
  5368. } else if (conn->ssl != NULL) {
  5369. int ssl_pending;
  5370. struct mg_pollfd pfd[1];
  5371. int pollres;
  5372. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5373. /* We already know there is no more data buffered in conn->buf
  5374. * but there is more available in the SSL layer. So don't poll
  5375. * conn->client.sock yet. */
  5376. if (ssl_pending > len) {
  5377. ssl_pending = len;
  5378. }
  5379. pollres = 1;
  5380. } else {
  5381. pfd[0].fd = conn->client.sock;
  5382. pfd[0].events = POLLIN;
  5383. pollres = mg_poll(pfd,
  5384. 1,
  5385. (int)(timeout * 1000.0),
  5386. &(conn->phys_ctx->stop_flag));
  5387. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5388. return -2;
  5389. }
  5390. }
  5391. if (pollres > 0) {
  5392. ERR_clear_error();
  5393. nread =
  5394. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5395. if (nread <= 0) {
  5396. err = SSL_get_error(conn->ssl, nread);
  5397. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5398. err = ERRNO;
  5399. } else if ((err == SSL_ERROR_WANT_READ)
  5400. || (err == SSL_ERROR_WANT_WRITE)) {
  5401. nread = 0;
  5402. } else {
  5403. /* All errors should return -2 */
  5404. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5405. ERR_clear_error();
  5406. return -2;
  5407. }
  5408. ERR_clear_error();
  5409. } else {
  5410. err = 0;
  5411. }
  5412. } else if (pollres < 0) {
  5413. /* Error */
  5414. return -2;
  5415. } else {
  5416. /* pollres = 0 means timeout */
  5417. nread = 0;
  5418. }
  5419. #endif
  5420. } else {
  5421. struct mg_pollfd pfd[1];
  5422. int pollres;
  5423. pfd[0].fd = conn->client.sock;
  5424. pfd[0].events = POLLIN;
  5425. pollres = mg_poll(pfd,
  5426. 1,
  5427. (int)(timeout * 1000.0),
  5428. &(conn->phys_ctx->stop_flag));
  5429. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5430. return -2;
  5431. }
  5432. if (pollres > 0) {
  5433. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5434. err = (nread < 0) ? ERRNO : 0;
  5435. if (nread <= 0) {
  5436. /* shutdown of the socket at client side */
  5437. return -2;
  5438. }
  5439. } else if (pollres < 0) {
  5440. /* error callint poll */
  5441. return -2;
  5442. } else {
  5443. /* pollres = 0 means timeout */
  5444. nread = 0;
  5445. }
  5446. }
  5447. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5448. return -2;
  5449. }
  5450. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5451. /* some data has been read, or no data was requested */
  5452. return nread;
  5453. }
  5454. if (nread < 0) {
  5455. /* socket error - check errno */
  5456. #if defined(_WIN32)
  5457. if (err == WSAEWOULDBLOCK) {
  5458. /* TODO (low): check if this is still required */
  5459. /* standard case if called from close_socket_gracefully */
  5460. return -2;
  5461. } else if (err == WSAETIMEDOUT) {
  5462. /* TODO (low): check if this is still required */
  5463. /* timeout is handled by the while loop */
  5464. return 0;
  5465. } else if (err == WSAECONNABORTED) {
  5466. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5467. return -2;
  5468. } else {
  5469. DEBUG_TRACE("recv() failed, error %d", err);
  5470. return -2;
  5471. }
  5472. #else
  5473. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5474. * if the timeout is reached and if the socket was set to non-
  5475. * blocking in close_socket_gracefully, so we can not distinguish
  5476. * here. We have to wait for the timeout in both cases for now.
  5477. */
  5478. if (ERROR_TRY_AGAIN(err)) {
  5479. /* TODO (low): check if this is still required */
  5480. /* EAGAIN/EWOULDBLOCK:
  5481. * standard case if called from close_socket_gracefully
  5482. * => should return -1 */
  5483. /* or timeout occurred
  5484. * => the code must stay in the while loop */
  5485. /* EINTR can be generated on a socket with a timeout set even
  5486. * when SA_RESTART is effective for all relevant signals
  5487. * (see signal(7)).
  5488. * => stay in the while loop */
  5489. } else {
  5490. DEBUG_TRACE("recv() failed, error %d", err);
  5491. return -2;
  5492. }
  5493. #endif
  5494. }
  5495. /* Timeout occurred, but no data available. */
  5496. return -1;
  5497. }
  5498. static int
  5499. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5500. {
  5501. int n, nread = 0;
  5502. double timeout = -1.0;
  5503. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5504. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5505. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5506. }
  5507. if (timeout <= 0.0) {
  5508. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5509. / 1000.0;
  5510. }
  5511. start_time = mg_get_current_time_ns();
  5512. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5513. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5514. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5515. if (n == -2) {
  5516. if (nread == 0) {
  5517. nread = -1; /* Propagate the error */
  5518. }
  5519. break;
  5520. } else if (n == -1) {
  5521. /* timeout */
  5522. if (timeout >= 0.0) {
  5523. now = mg_get_current_time_ns();
  5524. if ((now - start_time) <= timeout_ns) {
  5525. continue;
  5526. }
  5527. }
  5528. break;
  5529. } else if (n == 0) {
  5530. break; /* No more data to read */
  5531. } else {
  5532. nread += n;
  5533. len -= n;
  5534. }
  5535. }
  5536. return nread;
  5537. }
  5538. static void
  5539. discard_unread_request_data(struct mg_connection *conn)
  5540. {
  5541. char buf[MG_BUF_LEN];
  5542. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5543. ;
  5544. }
  5545. static int
  5546. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5547. {
  5548. int64_t content_len, n, buffered_len, nread;
  5549. int64_t len64 =
  5550. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5551. * int, we may not read more
  5552. * bytes */
  5553. const char *body;
  5554. if (conn == NULL) {
  5555. return 0;
  5556. }
  5557. /* If Content-Length is not set for a response with body data,
  5558. * we do not know in advance how much data should be read. */
  5559. content_len = conn->content_len;
  5560. if (content_len < 0) {
  5561. /* The body data is completed when the connection is closed. */
  5562. content_len = INT64_MAX;
  5563. }
  5564. nread = 0;
  5565. if (conn->consumed_content < content_len) {
  5566. /* Adjust number of bytes to read. */
  5567. int64_t left_to_read = content_len - conn->consumed_content;
  5568. if (left_to_read < len64) {
  5569. /* Do not read more than the total content length of the
  5570. * request.
  5571. */
  5572. len64 = left_to_read;
  5573. }
  5574. /* Return buffered data */
  5575. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5576. - conn->consumed_content;
  5577. if (buffered_len > 0) {
  5578. if (len64 < buffered_len) {
  5579. buffered_len = len64;
  5580. }
  5581. body = conn->buf + conn->request_len + conn->consumed_content;
  5582. memcpy(buf, body, (size_t)buffered_len);
  5583. len64 -= buffered_len;
  5584. conn->consumed_content += buffered_len;
  5585. nread += buffered_len;
  5586. buf = (char *)buf + buffered_len;
  5587. }
  5588. /* We have returned all buffered data. Read new data from the remote
  5589. * socket.
  5590. */
  5591. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5592. conn->consumed_content += n;
  5593. nread += n;
  5594. } else {
  5595. nread = ((nread > 0) ? nread : n);
  5596. }
  5597. }
  5598. return (int)nread;
  5599. }
  5600. /* Forward declarations */
  5601. static void handle_request(struct mg_connection *);
  5602. static void log_access(const struct mg_connection *);
  5603. /* Handle request, update statistics and call access log */
  5604. static void
  5605. handle_request_stat_log(struct mg_connection *conn)
  5606. {
  5607. #if defined(USE_SERVER_STATS)
  5608. struct timespec tnow;
  5609. conn->conn_state = 4; /* processing */
  5610. #endif
  5611. handle_request(conn);
  5612. #if defined(USE_SERVER_STATS)
  5613. conn->conn_state = 5; /* processed */
  5614. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5615. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5616. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5617. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5618. conn->num_bytes_sent);
  5619. #endif
  5620. DEBUG_TRACE("%s", "handle_request done");
  5621. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5622. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5623. DEBUG_TRACE("%s", "end_request callback done");
  5624. }
  5625. log_access(conn);
  5626. }
  5627. #if defined(USE_HTTP2)
  5628. #if defined(NO_SSL)
  5629. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5630. #endif
  5631. #define USE_ALPN
  5632. #include "http2.inl"
  5633. /* Not supported with HTTP/2 */
  5634. #define HTTP1_only \
  5635. { \
  5636. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5637. http2_must_use_http1(conn); \
  5638. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5639. return; \
  5640. } \
  5641. }
  5642. #else
  5643. #define HTTP1_only
  5644. #endif
  5645. int
  5646. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5647. {
  5648. if (len > INT_MAX) {
  5649. len = INT_MAX;
  5650. }
  5651. if (conn == NULL) {
  5652. return 0;
  5653. }
  5654. if (conn->is_chunked) {
  5655. size_t all_read = 0;
  5656. while (len > 0) {
  5657. if (conn->is_chunked >= 3) {
  5658. /* No more data left to read */
  5659. return 0;
  5660. }
  5661. if (conn->is_chunked != 1) {
  5662. /* Has error */
  5663. return -1;
  5664. }
  5665. if (conn->consumed_content != conn->content_len) {
  5666. /* copy from the current chunk */
  5667. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5668. if (read_ret < 1) {
  5669. /* read error */
  5670. conn->is_chunked = 2;
  5671. return -1;
  5672. }
  5673. all_read += (size_t)read_ret;
  5674. len -= (size_t)read_ret;
  5675. if (conn->consumed_content == conn->content_len) {
  5676. /* Add data bytes in the current chunk have been read,
  5677. * so we are expecting \r\n now. */
  5678. char x[2];
  5679. conn->content_len += 2;
  5680. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5681. || (x[1] != '\n')) {
  5682. /* Protocol violation */
  5683. conn->is_chunked = 2;
  5684. return -1;
  5685. }
  5686. }
  5687. } else {
  5688. /* fetch a new chunk */
  5689. size_t i;
  5690. char lenbuf[64];
  5691. char *end = NULL;
  5692. unsigned long chunkSize = 0;
  5693. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5694. conn->content_len++;
  5695. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5696. lenbuf[i] = 0;
  5697. }
  5698. if ((i > 0) && (lenbuf[i] == '\r')
  5699. && (lenbuf[i - 1] != '\r')) {
  5700. continue;
  5701. }
  5702. if ((i > 1) && (lenbuf[i] == '\n')
  5703. && (lenbuf[i - 1] == '\r')) {
  5704. lenbuf[i + 1] = 0;
  5705. chunkSize = strtoul(lenbuf, &end, 16);
  5706. if (chunkSize == 0) {
  5707. /* regular end of content */
  5708. conn->is_chunked = 3;
  5709. }
  5710. break;
  5711. }
  5712. if (!isxdigit((unsigned char)lenbuf[i])) {
  5713. /* illegal character for chunk length */
  5714. conn->is_chunked = 2;
  5715. return -1;
  5716. }
  5717. }
  5718. if ((end == NULL) || (*end != '\r')) {
  5719. /* chunksize not set correctly */
  5720. conn->is_chunked = 2;
  5721. return -1;
  5722. }
  5723. if (chunkSize == 0) {
  5724. /* try discarding trailer for keep-alive */
  5725. conn->content_len += 2;
  5726. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5727. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5728. conn->is_chunked = 4;
  5729. }
  5730. break;
  5731. }
  5732. /* append a new chunk */
  5733. conn->content_len += (int64_t)chunkSize;
  5734. }
  5735. }
  5736. return (int)all_read;
  5737. }
  5738. return mg_read_inner(conn, buf, len);
  5739. }
  5740. int
  5741. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5742. {
  5743. time_t now;
  5744. int n, total, allowed;
  5745. if (conn == NULL) {
  5746. return 0;
  5747. }
  5748. if (len > INT_MAX) {
  5749. return -1;
  5750. }
  5751. /* Mark connection as "data sent" */
  5752. conn->request_state = 10;
  5753. #if defined(USE_HTTP2)
  5754. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5755. http2_data_frame_head(conn, len, 0);
  5756. }
  5757. #endif
  5758. if (conn->throttle > 0) {
  5759. if ((now = time(NULL)) != conn->last_throttle_time) {
  5760. conn->last_throttle_time = now;
  5761. conn->last_throttle_bytes = 0;
  5762. }
  5763. allowed = conn->throttle - conn->last_throttle_bytes;
  5764. if (allowed > (int)len) {
  5765. allowed = (int)len;
  5766. }
  5767. total = push_all(conn->phys_ctx,
  5768. NULL,
  5769. conn->client.sock,
  5770. conn->ssl,
  5771. (const char *)buf,
  5772. allowed);
  5773. if (total == allowed) {
  5774. buf = (const char *)buf + total;
  5775. conn->last_throttle_bytes += total;
  5776. while ((total < (int)len)
  5777. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5778. allowed = (conn->throttle > ((int)len - total))
  5779. ? (int)len - total
  5780. : conn->throttle;
  5781. n = push_all(conn->phys_ctx,
  5782. NULL,
  5783. conn->client.sock,
  5784. conn->ssl,
  5785. (const char *)buf,
  5786. allowed);
  5787. if (n != allowed) {
  5788. break;
  5789. }
  5790. sleep(1);
  5791. conn->last_throttle_bytes = allowed;
  5792. conn->last_throttle_time = time(NULL);
  5793. buf = (const char *)buf + n;
  5794. total += n;
  5795. }
  5796. }
  5797. } else {
  5798. total = push_all(conn->phys_ctx,
  5799. NULL,
  5800. conn->client.sock,
  5801. conn->ssl,
  5802. (const char *)buf,
  5803. (int)len);
  5804. }
  5805. if (total > 0) {
  5806. conn->num_bytes_sent += total;
  5807. }
  5808. return total;
  5809. }
  5810. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5811. int
  5812. mg_send_chunk(struct mg_connection *conn,
  5813. const char *chunk,
  5814. unsigned int chunk_len)
  5815. {
  5816. char lenbuf[16];
  5817. size_t lenbuf_len;
  5818. int ret;
  5819. int t;
  5820. /* First store the length information in a text buffer. */
  5821. sprintf(lenbuf, "%x\r\n", chunk_len);
  5822. lenbuf_len = strlen(lenbuf);
  5823. /* Then send length information, chunk and terminating \r\n. */
  5824. ret = mg_write(conn, lenbuf, lenbuf_len);
  5825. if (ret != (int)lenbuf_len) {
  5826. return -1;
  5827. }
  5828. t = ret;
  5829. ret = mg_write(conn, chunk, chunk_len);
  5830. if (ret != (int)chunk_len) {
  5831. return -1;
  5832. }
  5833. t += ret;
  5834. ret = mg_write(conn, "\r\n", 2);
  5835. if (ret != 2) {
  5836. return -1;
  5837. }
  5838. t += ret;
  5839. return t;
  5840. }
  5841. #if defined(GCC_DIAGNOSTIC)
  5842. /* This block forwards format strings to printf implementations,
  5843. * so we need to disable the format-nonliteral warning. */
  5844. #pragma GCC diagnostic push
  5845. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5846. #endif
  5847. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5848. static int
  5849. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5850. {
  5851. va_list ap_copy;
  5852. size_t size = MG_BUF_LEN / 4;
  5853. int len = -1;
  5854. *buf = NULL;
  5855. while (len < 0) {
  5856. if (*buf) {
  5857. mg_free(*buf);
  5858. }
  5859. size *= 4;
  5860. *buf = (char *)mg_malloc(size);
  5861. if (!*buf) {
  5862. break;
  5863. }
  5864. va_copy(ap_copy, ap);
  5865. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5866. va_end(ap_copy);
  5867. (*buf)[size - 1] = 0;
  5868. }
  5869. return len;
  5870. }
  5871. /* Print message to buffer. If buffer is large enough to hold the message,
  5872. * return buffer. If buffer is to small, allocate large enough buffer on
  5873. * heap,
  5874. * and return allocated buffer. */
  5875. static int
  5876. alloc_vprintf(char **out_buf,
  5877. char *prealloc_buf,
  5878. size_t prealloc_size,
  5879. const char *fmt,
  5880. va_list ap)
  5881. {
  5882. va_list ap_copy;
  5883. int len;
  5884. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5885. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5886. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5887. * Therefore, we make two passes: on first pass, get required message
  5888. * length.
  5889. * On second pass, actually print the message. */
  5890. va_copy(ap_copy, ap);
  5891. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5892. va_end(ap_copy);
  5893. if (len < 0) {
  5894. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5895. * Switch to alternative code path that uses incremental
  5896. * allocations.
  5897. */
  5898. va_copy(ap_copy, ap);
  5899. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5900. va_end(ap_copy);
  5901. } else if ((size_t)(len) >= prealloc_size) {
  5902. /* The pre-allocated buffer not large enough. */
  5903. /* Allocate a new buffer. */
  5904. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5905. if (!*out_buf) {
  5906. /* Allocation failed. Return -1 as "out of memory" error. */
  5907. return -1;
  5908. }
  5909. /* Buffer allocation successful. Store the string there. */
  5910. va_copy(ap_copy, ap);
  5911. IGNORE_UNUSED_RESULT(
  5912. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5913. va_end(ap_copy);
  5914. } else {
  5915. /* The pre-allocated buffer is large enough.
  5916. * Use it to store the string and return the address. */
  5917. va_copy(ap_copy, ap);
  5918. IGNORE_UNUSED_RESULT(
  5919. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5920. va_end(ap_copy);
  5921. *out_buf = prealloc_buf;
  5922. }
  5923. return len;
  5924. }
  5925. static int
  5926. alloc_printf(char **out_buf, const char *fmt, ...)
  5927. {
  5928. va_list ap;
  5929. int result;
  5930. va_start(ap, fmt);
  5931. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5932. va_end(ap);
  5933. return result;
  5934. }
  5935. #if defined(GCC_DIAGNOSTIC)
  5936. /* Enable format-nonliteral warning again. */
  5937. #pragma GCC diagnostic pop
  5938. #endif
  5939. static int
  5940. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5941. {
  5942. char mem[MG_BUF_LEN];
  5943. char *buf = NULL;
  5944. int len;
  5945. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5946. len = mg_write(conn, buf, (size_t)len);
  5947. }
  5948. if (buf != mem) {
  5949. mg_free(buf);
  5950. }
  5951. return len;
  5952. }
  5953. int
  5954. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5955. {
  5956. va_list ap;
  5957. int result;
  5958. va_start(ap, fmt);
  5959. result = mg_vprintf(conn, fmt, ap);
  5960. va_end(ap);
  5961. return result;
  5962. }
  5963. int
  5964. mg_url_decode(const char *src,
  5965. int src_len,
  5966. char *dst,
  5967. int dst_len,
  5968. int is_form_url_encoded)
  5969. {
  5970. int i, j, a, b;
  5971. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5972. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5973. if ((i < src_len - 2) && (src[i] == '%')
  5974. && isxdigit((unsigned char)src[i + 1])
  5975. && isxdigit((unsigned char)src[i + 2])) {
  5976. a = tolower((unsigned char)src[i + 1]);
  5977. b = tolower((unsigned char)src[i + 2]);
  5978. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5979. i += 2;
  5980. } else if (is_form_url_encoded && (src[i] == '+')) {
  5981. dst[j] = ' ';
  5982. } else {
  5983. dst[j] = src[i];
  5984. }
  5985. }
  5986. dst[j] = '\0'; /* Null-terminate the destination */
  5987. return (i >= src_len) ? j : -1;
  5988. }
  5989. /* form url decoding of an entire string */
  5990. static void
  5991. url_decode_in_place(char *buf)
  5992. {
  5993. int len = (int)strlen(buf);
  5994. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5995. }
  5996. int
  5997. mg_get_var(const char *data,
  5998. size_t data_len,
  5999. const char *name,
  6000. char *dst,
  6001. size_t dst_len)
  6002. {
  6003. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6004. }
  6005. int
  6006. mg_get_var2(const char *data,
  6007. size_t data_len,
  6008. const char *name,
  6009. char *dst,
  6010. size_t dst_len,
  6011. size_t occurrence)
  6012. {
  6013. const char *p, *e, *s;
  6014. size_t name_len;
  6015. int len;
  6016. if ((dst == NULL) || (dst_len == 0)) {
  6017. len = -2;
  6018. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6019. len = -1;
  6020. dst[0] = '\0';
  6021. } else {
  6022. name_len = strlen(name);
  6023. e = data + data_len;
  6024. len = -1;
  6025. dst[0] = '\0';
  6026. /* data is "var1=val1&var2=val2...". Find variable first */
  6027. for (p = data; p + name_len < e; p++) {
  6028. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6029. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6030. /* Point p to variable value */
  6031. p += name_len + 1;
  6032. /* Point s to the end of the value */
  6033. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6034. if (s == NULL) {
  6035. s = e;
  6036. }
  6037. DEBUG_ASSERT(s >= p);
  6038. if (s < p) {
  6039. return -3;
  6040. }
  6041. /* Decode variable into destination buffer */
  6042. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6043. /* Redirect error code from -1 to -2 (destination buffer too
  6044. * small). */
  6045. if (len == -1) {
  6046. len = -2;
  6047. }
  6048. break;
  6049. }
  6050. }
  6051. }
  6052. return len;
  6053. }
  6054. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6055. int
  6056. mg_split_form_urlencoded(char *data,
  6057. struct mg_header *form_fields,
  6058. unsigned num_form_fields)
  6059. {
  6060. char *b;
  6061. int i;
  6062. int num = 0;
  6063. if (data == NULL) {
  6064. /* parameter error */
  6065. return -1;
  6066. }
  6067. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6068. /* determine the number of expected fields */
  6069. if (data[0] == 0) {
  6070. return 0;
  6071. }
  6072. /* count number of & to return the number of key-value-pairs */
  6073. num = 1;
  6074. while (*data) {
  6075. if (*data == '&') {
  6076. num++;
  6077. }
  6078. data++;
  6079. }
  6080. return num;
  6081. }
  6082. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6083. /* parameter error */
  6084. return -1;
  6085. }
  6086. for (i = 0; i < (int)num_form_fields; i++) {
  6087. /* extract key-value pairs from input data */
  6088. while ((*data == ' ') || (*data == '\t')) {
  6089. /* skip initial spaces */
  6090. data++;
  6091. }
  6092. if (*data == 0) {
  6093. /* end of string reached */
  6094. break;
  6095. }
  6096. form_fields[num].name = data;
  6097. /* find & or = */
  6098. b = data;
  6099. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6100. b++;
  6101. }
  6102. if (*b == 0) {
  6103. /* last key without value */
  6104. form_fields[num].value = NULL;
  6105. } else if (*b == '&') {
  6106. /* mid key without value */
  6107. form_fields[num].value = NULL;
  6108. } else {
  6109. /* terminate string */
  6110. *b = 0;
  6111. /* value starts after '=' */
  6112. data = b + 1;
  6113. form_fields[num].value = data;
  6114. }
  6115. /* new field is stored */
  6116. num++;
  6117. /* find a next key */
  6118. b = strchr(data, '&');
  6119. if (b == 0) {
  6120. /* no more data */
  6121. break;
  6122. } else {
  6123. /* terminate value of last field at '&' */
  6124. *b = 0;
  6125. /* next key-value-pairs starts after '&' */
  6126. data = b + 1;
  6127. }
  6128. }
  6129. /* Decode all values */
  6130. for (i = 0; i < num; i++) {
  6131. if (form_fields[i].name) {
  6132. url_decode_in_place((char *)form_fields[i].name);
  6133. }
  6134. if (form_fields[i].value) {
  6135. url_decode_in_place((char *)form_fields[i].value);
  6136. }
  6137. }
  6138. /* return number of fields found */
  6139. return num;
  6140. }
  6141. /* HCP24: some changes to compare whole var_name */
  6142. int
  6143. mg_get_cookie(const char *cookie_header,
  6144. const char *var_name,
  6145. char *dst,
  6146. size_t dst_size)
  6147. {
  6148. const char *s, *p, *end;
  6149. int name_len, len = -1;
  6150. if ((dst == NULL) || (dst_size == 0)) {
  6151. return -2;
  6152. }
  6153. dst[0] = '\0';
  6154. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6155. return -1;
  6156. }
  6157. name_len = (int)strlen(var_name);
  6158. end = s + strlen(s);
  6159. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6160. if (s[name_len] == '=') {
  6161. /* HCP24: now check is it a substring or a full cookie name */
  6162. if ((s == cookie_header) || (s[-1] == ' ')) {
  6163. s += name_len + 1;
  6164. if ((p = strchr(s, ' ')) == NULL) {
  6165. p = end;
  6166. }
  6167. if (p[-1] == ';') {
  6168. p--;
  6169. }
  6170. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6171. s++;
  6172. p--;
  6173. }
  6174. if ((size_t)(p - s) < dst_size) {
  6175. len = (int)(p - s);
  6176. mg_strlcpy(dst, s, (size_t)len + 1);
  6177. } else {
  6178. len = -3;
  6179. }
  6180. break;
  6181. }
  6182. }
  6183. }
  6184. return len;
  6185. }
  6186. int
  6187. mg_base64_encode(const unsigned char *src,
  6188. size_t src_len,
  6189. char *dst,
  6190. size_t *dst_len)
  6191. {
  6192. static const char *b64 =
  6193. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6194. size_t i, j;
  6195. int a, b, c;
  6196. if (dst_len != NULL) {
  6197. /* Expected length including 0 termination: */
  6198. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6199. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6200. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6201. if (*dst_len < expected_len) {
  6202. if (*dst_len > 0) {
  6203. dst[0] = '\0';
  6204. }
  6205. *dst_len = expected_len;
  6206. return 0;
  6207. }
  6208. }
  6209. for (i = j = 0; i < src_len; i += 3) {
  6210. a = src[i];
  6211. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6212. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6213. dst[j++] = b64[a >> 2];
  6214. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6215. if (i + 1 < src_len) {
  6216. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6217. }
  6218. if (i + 2 < src_len) {
  6219. dst[j++] = b64[c & 63];
  6220. }
  6221. }
  6222. while (j % 4 != 0) {
  6223. dst[j++] = '=';
  6224. }
  6225. dst[j++] = '\0';
  6226. if (dst_len != NULL) {
  6227. *dst_len = (size_t)j;
  6228. }
  6229. /* Return -1 for "OK" */
  6230. return -1;
  6231. }
  6232. static unsigned char
  6233. b64reverse(char letter)
  6234. {
  6235. if ((letter >= 'A') && (letter <= 'Z')) {
  6236. return letter - 'A';
  6237. }
  6238. if ((letter >= 'a') && (letter <= 'z')) {
  6239. return letter - 'a' + 26;
  6240. }
  6241. if ((letter >= '0') && (letter <= '9')) {
  6242. return letter - '0' + 52;
  6243. }
  6244. if (letter == '+') {
  6245. return 62;
  6246. }
  6247. if (letter == '/') {
  6248. return 63;
  6249. }
  6250. if (letter == '=') {
  6251. return 255; /* normal end */
  6252. }
  6253. return 254; /* error */
  6254. }
  6255. int
  6256. mg_base64_decode(const char *src,
  6257. size_t src_len,
  6258. unsigned char *dst,
  6259. size_t *dst_len)
  6260. {
  6261. size_t i;
  6262. unsigned char a, b, c, d;
  6263. size_t dst_len_limit = (size_t)-1;
  6264. size_t dst_len_used = 0;
  6265. if (dst_len != NULL) {
  6266. dst_len_limit = *dst_len;
  6267. *dst_len = 0;
  6268. }
  6269. for (i = 0; i < src_len; i += 4) {
  6270. /* Read 4 characters from BASE64 string */
  6271. a = b64reverse(src[i]);
  6272. if (a >= 254) {
  6273. return (int)i;
  6274. }
  6275. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6276. if (b >= 254) {
  6277. return (int)i + 1;
  6278. }
  6279. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6280. if (c == 254) {
  6281. return (int)i + 2;
  6282. }
  6283. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6284. if (d == 254) {
  6285. return (int)i + 3;
  6286. }
  6287. /* Add first (of 3) decoded character */
  6288. if (dst_len_used < dst_len_limit) {
  6289. dst[dst_len_used] = (a << 2) + (b >> 4);
  6290. }
  6291. dst_len_used++;
  6292. if (c != 255) {
  6293. if (dst_len_used < dst_len_limit) {
  6294. dst[dst_len_used] = (b << 4) + (c >> 2);
  6295. }
  6296. dst_len_used++;
  6297. if (d != 255) {
  6298. if (dst_len_used < dst_len_limit) {
  6299. dst[dst_len_used] = (c << 6) + d;
  6300. }
  6301. dst_len_used++;
  6302. }
  6303. }
  6304. }
  6305. /* Add terminating zero */
  6306. if (dst_len_used < dst_len_limit) {
  6307. dst[dst_len_used] = '\0';
  6308. }
  6309. dst_len_used++;
  6310. if (dst_len != NULL) {
  6311. *dst_len = dst_len_used;
  6312. }
  6313. if (dst_len_used > dst_len_limit) {
  6314. /* Out of memory */
  6315. return 0;
  6316. }
  6317. /* Return -1 for "OK" */
  6318. return -1;
  6319. }
  6320. static int
  6321. is_put_or_delete_method(const struct mg_connection *conn)
  6322. {
  6323. if (conn) {
  6324. const char *s = conn->request_info.request_method;
  6325. if (s != NULL) {
  6326. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6327. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6328. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6329. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6330. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6331. || !strcmp(s, "COPY"));
  6332. }
  6333. }
  6334. return 0;
  6335. }
  6336. static int
  6337. is_civetweb_webdav_method(const struct mg_connection *conn)
  6338. {
  6339. /* Note: Here we only have to identify the WebDav methods that need special
  6340. * handling in the CivetWeb code - not all methods used in WebDav. In
  6341. * particular, methods used on directories (when using Windows Explorer as
  6342. * WebDav client).
  6343. */
  6344. if (conn) {
  6345. const char *s = conn->request_info.request_method;
  6346. if (s != NULL) {
  6347. /* These are the civetweb builtin DAV methods */
  6348. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6349. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6350. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6351. }
  6352. }
  6353. return 0;
  6354. }
  6355. #if !defined(NO_FILES)
  6356. static int
  6357. extention_matches_script(
  6358. struct mg_connection *conn, /* in: request (must be valid) */
  6359. const char *filename /* in: filename (must be valid) */
  6360. )
  6361. {
  6362. #if !defined(NO_CGI)
  6363. unsigned char cgi_config_idx, inc, max;
  6364. #endif
  6365. #if defined(USE_LUA)
  6366. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6367. filename)
  6368. > 0) {
  6369. return 1;
  6370. }
  6371. #endif
  6372. #if defined(USE_DUKTAPE)
  6373. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6374. filename)
  6375. > 0) {
  6376. return 1;
  6377. }
  6378. #endif
  6379. #if !defined(NO_CGI)
  6380. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6381. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6382. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6383. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6384. && (match_prefix_strlen(
  6385. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6386. filename)
  6387. > 0)) {
  6388. return 1;
  6389. }
  6390. }
  6391. #endif
  6392. /* filename and conn could be unused, if all preocessor conditions
  6393. * are false (no script language supported). */
  6394. (void)filename;
  6395. (void)conn;
  6396. return 0;
  6397. }
  6398. static int
  6399. extention_matches_template_text(
  6400. struct mg_connection *conn, /* in: request (must be valid) */
  6401. const char *filename /* in: filename (must be valid) */
  6402. )
  6403. {
  6404. #if defined(USE_LUA)
  6405. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6406. filename)
  6407. > 0) {
  6408. return 1;
  6409. }
  6410. #endif
  6411. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6412. > 0) {
  6413. return 1;
  6414. }
  6415. return 0;
  6416. }
  6417. /* For given directory path, substitute it to valid index file.
  6418. * Return 1 if index file has been found, 0 if not found.
  6419. * If the file is found, it's stats is returned in stp. */
  6420. static int
  6421. substitute_index_file(struct mg_connection *conn,
  6422. char *path,
  6423. size_t path_len,
  6424. struct mg_file_stat *filestat)
  6425. {
  6426. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6427. struct vec filename_vec;
  6428. size_t n = strlen(path);
  6429. int found = 0;
  6430. /* The 'path' given to us points to the directory. Remove all trailing
  6431. * directory separator characters from the end of the path, and
  6432. * then append single directory separator character. */
  6433. while ((n > 0) && (path[n - 1] == '/')) {
  6434. n--;
  6435. }
  6436. path[n] = '/';
  6437. /* Traverse index files list. For each entry, append it to the given
  6438. * path and see if the file exists. If it exists, break the loop */
  6439. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6440. /* Ignore too long entries that may overflow path buffer */
  6441. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6442. continue;
  6443. }
  6444. /* Prepare full path to the index file */
  6445. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6446. /* Does it exist? */
  6447. if (mg_stat(conn, path, filestat)) {
  6448. /* Yes it does, break the loop */
  6449. found = 1;
  6450. break;
  6451. }
  6452. }
  6453. /* If no index file exists, restore directory path */
  6454. if (!found) {
  6455. path[n] = '\0';
  6456. }
  6457. return found;
  6458. }
  6459. #endif
  6460. static void
  6461. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6462. char *filename, /* out: filename */
  6463. size_t filename_buf_len, /* in: size of filename buffer */
  6464. struct mg_file_stat *filestat, /* out: file status structure */
  6465. int *is_found, /* out: file found (directly) */
  6466. int *is_script_resource, /* out: handled by a script? */
  6467. int *is_websocket_request, /* out: websocket connetion? */
  6468. int *is_put_or_delete_request, /* out: put/delete a file? */
  6469. int *is_webdav_request, /* out: webdav request? */
  6470. int *is_template_text /* out: SSI file or LSP file? */
  6471. )
  6472. {
  6473. char const *accept_encoding;
  6474. #if !defined(NO_FILES)
  6475. const char *uri = conn->request_info.local_uri;
  6476. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6477. const char *rewrite;
  6478. struct vec a, b;
  6479. ptrdiff_t match_len;
  6480. char gz_path[UTF8_PATH_MAX];
  6481. int truncated;
  6482. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6483. char *tmp_str;
  6484. size_t tmp_str_len, sep_pos;
  6485. int allow_substitute_script_subresources;
  6486. #endif
  6487. #else
  6488. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6489. #endif
  6490. /* Step 1: Set all initially unknown outputs to zero */
  6491. memset(filestat, 0, sizeof(*filestat));
  6492. *filename = 0;
  6493. *is_found = 0;
  6494. *is_script_resource = 0;
  6495. *is_template_text = 0;
  6496. /* Step 2: Classify the request method */
  6497. /* Step 2a: Check if the request attempts to modify the file system */
  6498. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6499. /* Step 2b: Check if the request uses WebDav method that requires special
  6500. * handling */
  6501. *is_webdav_request = is_civetweb_webdav_method(conn);
  6502. /* Step 3: Check if it is a websocket request, and modify the document
  6503. * root if required */
  6504. #if defined(USE_WEBSOCKET)
  6505. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6506. #if !defined(NO_FILES)
  6507. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6508. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6509. }
  6510. #endif /* !NO_FILES */
  6511. #else /* USE_WEBSOCKET */
  6512. *is_websocket_request = 0;
  6513. #endif /* USE_WEBSOCKET */
  6514. /* Step 4: Check if gzip encoded response is allowed */
  6515. conn->accept_gzip = 0;
  6516. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6517. if (strstr(accept_encoding, "gzip") != NULL) {
  6518. conn->accept_gzip = 1;
  6519. }
  6520. }
  6521. #if !defined(NO_FILES)
  6522. /* Step 5: If there is no root directory, don't look for files. */
  6523. /* Note that root == NULL is a regular use case here. This occurs,
  6524. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6525. * config is not required. */
  6526. if (root == NULL) {
  6527. /* all file related outputs have already been set to 0, just return
  6528. */
  6529. return;
  6530. }
  6531. /* Step 6: Determine the local file path from the root path and the
  6532. * request uri. */
  6533. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6534. * part of the path one byte on the right. */
  6535. truncated = 0;
  6536. mg_snprintf(
  6537. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6538. if (truncated) {
  6539. goto interpret_cleanup;
  6540. }
  6541. /* Step 7: URI rewriting */
  6542. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6543. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6544. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6545. mg_snprintf(conn,
  6546. &truncated,
  6547. filename,
  6548. filename_buf_len - 1,
  6549. "%.*s%s",
  6550. (int)b.len,
  6551. b.ptr,
  6552. uri + match_len);
  6553. break;
  6554. }
  6555. }
  6556. if (truncated) {
  6557. goto interpret_cleanup;
  6558. }
  6559. /* Step 8: Check if the file exists at the server */
  6560. /* Local file path and name, corresponding to requested URI
  6561. * is now stored in "filename" variable. */
  6562. if (mg_stat(conn, filename, filestat)) {
  6563. int uri_len = (int)strlen(uri);
  6564. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6565. /* 8.1: File exists. */
  6566. *is_found = 1;
  6567. /* 8.2: Check if it is a script type. */
  6568. if (extention_matches_script(conn, filename)) {
  6569. /* The request addresses a CGI resource, Lua script or
  6570. * server-side javascript.
  6571. * The URI corresponds to the script itself (like
  6572. * /path/script.cgi), and there is no additional resource
  6573. * path (like /path/script.cgi/something).
  6574. * Requests that modify (replace or delete) a resource, like
  6575. * PUT and DELETE requests, should replace/delete the script
  6576. * file.
  6577. * Requests that read or write from/to a resource, like GET and
  6578. * POST requests, should call the script and return the
  6579. * generated response. */
  6580. *is_script_resource = (!*is_put_or_delete_request);
  6581. }
  6582. /* 8.3: Check for SSI and LSP files */
  6583. if (extention_matches_template_text(conn, filename)) {
  6584. /* Same as above, but for *.lsp and *.shtml files. */
  6585. /* A "template text" is a file delivered directly to the client,
  6586. * but with some text tags replaced by dynamic content.
  6587. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6588. * (LP, LSP) file. */
  6589. *is_template_text = (!*is_put_or_delete_request);
  6590. }
  6591. /* 8.4: If the request target is a directory, there could be
  6592. * a substitute file (index.html, index.cgi, ...). */
  6593. /* But do not substitute a directory for a WebDav request */
  6594. if (filestat->is_directory && is_uri_end_slash
  6595. && (!*is_webdav_request)) {
  6596. /* Use a local copy here, since substitute_index_file will
  6597. * change the content of the file status */
  6598. struct mg_file_stat tmp_filestat;
  6599. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6600. if (substitute_index_file(
  6601. conn, filename, filename_buf_len, &tmp_filestat)) {
  6602. /* Substitute file found. Copy stat to the output, then
  6603. * check if the file is a script file */
  6604. *filestat = tmp_filestat;
  6605. if (extention_matches_script(conn, filename)) {
  6606. /* Substitute file is a script file */
  6607. *is_script_resource = 1;
  6608. } else if (extention_matches_template_text(conn, filename)) {
  6609. /* Substitute file is a LSP or SSI file */
  6610. *is_template_text = 1;
  6611. } else {
  6612. /* Substitute file is a regular file */
  6613. *is_script_resource = 0;
  6614. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6615. }
  6616. }
  6617. /* If there is no substitute file, the server could return
  6618. * a directory listing in a later step */
  6619. }
  6620. return;
  6621. }
  6622. /* Step 9: Check for zipped files: */
  6623. /* If we can't find the actual file, look for the file
  6624. * with the same name but a .gz extension. If we find it,
  6625. * use that and set the gzipped flag in the file struct
  6626. * to indicate that the response need to have the content-
  6627. * encoding: gzip header.
  6628. * We can only do this if the browser declares support. */
  6629. if (conn->accept_gzip) {
  6630. mg_snprintf(
  6631. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6632. if (truncated) {
  6633. goto interpret_cleanup;
  6634. }
  6635. if (mg_stat(conn, gz_path, filestat)) {
  6636. if (filestat) {
  6637. filestat->is_gzipped = 1;
  6638. *is_found = 1;
  6639. }
  6640. /* Currently gz files can not be scripts. */
  6641. return;
  6642. }
  6643. }
  6644. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6645. /* Step 10: Script resources may handle sub-resources */
  6646. /* Support PATH_INFO for CGI scripts. */
  6647. tmp_str_len = strlen(filename);
  6648. tmp_str =
  6649. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6650. if (!tmp_str) {
  6651. /* Out of memory */
  6652. goto interpret_cleanup;
  6653. }
  6654. memcpy(tmp_str, filename, tmp_str_len + 1);
  6655. /* Check config, if index scripts may have sub-resources */
  6656. allow_substitute_script_subresources =
  6657. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6658. "yes");
  6659. if (*is_webdav_request) {
  6660. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6661. * PROPFIND fo their subresources? */
  6662. /* allow_substitute_script_subresources = 0; */
  6663. }
  6664. sep_pos = tmp_str_len;
  6665. while (sep_pos > 0) {
  6666. sep_pos--;
  6667. if (tmp_str[sep_pos] == '/') {
  6668. int is_script = 0, does_exist = 0;
  6669. tmp_str[sep_pos] = 0;
  6670. if (tmp_str[0]) {
  6671. is_script = extention_matches_script(conn, tmp_str);
  6672. does_exist = mg_stat(conn, tmp_str, filestat);
  6673. }
  6674. if (does_exist && is_script) {
  6675. filename[sep_pos] = 0;
  6676. memmove(filename + sep_pos + 2,
  6677. filename + sep_pos + 1,
  6678. strlen(filename + sep_pos + 1) + 1);
  6679. conn->path_info = filename + sep_pos + 1;
  6680. filename[sep_pos + 1] = '/';
  6681. *is_script_resource = 1;
  6682. *is_found = 1;
  6683. break;
  6684. }
  6685. if (allow_substitute_script_subresources) {
  6686. if (substitute_index_file(
  6687. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6688. /* some intermediate directory has an index file */
  6689. if (extention_matches_script(conn, tmp_str)) {
  6690. size_t script_name_len = strlen(tmp_str);
  6691. /* subres_name read before this memory locatio will be
  6692. overwritten */
  6693. char *subres_name = filename + sep_pos;
  6694. size_t subres_name_len = strlen(subres_name);
  6695. DEBUG_TRACE("Substitute script %s serving path %s",
  6696. tmp_str,
  6697. filename);
  6698. /* this index file is a script */
  6699. if ((script_name_len + subres_name_len + 2)
  6700. >= filename_buf_len) {
  6701. mg_free(tmp_str);
  6702. goto interpret_cleanup;
  6703. }
  6704. conn->path_info =
  6705. filename + script_name_len + 1; /* new target */
  6706. memmove(conn->path_info, subres_name, subres_name_len);
  6707. conn->path_info[subres_name_len] = 0;
  6708. memcpy(filename, tmp_str, script_name_len + 1);
  6709. *is_script_resource = 1;
  6710. *is_found = 1;
  6711. break;
  6712. } else {
  6713. DEBUG_TRACE("Substitute file %s serving path %s",
  6714. tmp_str,
  6715. filename);
  6716. /* non-script files will not have sub-resources */
  6717. filename[sep_pos] = 0;
  6718. conn->path_info = 0;
  6719. *is_script_resource = 0;
  6720. *is_found = 0;
  6721. break;
  6722. }
  6723. }
  6724. }
  6725. tmp_str[sep_pos] = '/';
  6726. }
  6727. }
  6728. mg_free(tmp_str);
  6729. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6730. #endif /* !defined(NO_FILES) */
  6731. return;
  6732. #if !defined(NO_FILES)
  6733. /* Reset all outputs */
  6734. interpret_cleanup:
  6735. memset(filestat, 0, sizeof(*filestat));
  6736. *filename = 0;
  6737. *is_found = 0;
  6738. *is_script_resource = 0;
  6739. *is_websocket_request = 0;
  6740. *is_put_or_delete_request = 0;
  6741. #endif /* !defined(NO_FILES) */
  6742. }
  6743. /* Check whether full request is buffered. Return:
  6744. * -1 if request or response is malformed
  6745. * 0 if request or response is not yet fully buffered
  6746. * >0 actual request length, including last \r\n\r\n */
  6747. static int
  6748. get_http_header_len(const char *buf, int buflen)
  6749. {
  6750. int i;
  6751. for (i = 0; i < buflen; i++) {
  6752. /* Do an unsigned comparison in some conditions below */
  6753. const unsigned char c = (unsigned char)buf[i];
  6754. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6755. && !isprint(c)) {
  6756. /* abort scan as soon as one malformed character is found */
  6757. return -1;
  6758. }
  6759. if (i < buflen - 1) {
  6760. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6761. /* Two newline, no carriage return - not standard compliant,
  6762. * but it should be accepted */
  6763. return i + 2;
  6764. }
  6765. }
  6766. if (i < buflen - 3) {
  6767. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6768. && (buf[i + 3] == '\n')) {
  6769. /* Two \r\n - standard compliant */
  6770. return i + 4;
  6771. }
  6772. }
  6773. }
  6774. return 0;
  6775. }
  6776. #if !defined(NO_CACHING)
  6777. /* Convert month to the month number. Return -1 on error, or month number */
  6778. static int
  6779. get_month_index(const char *s)
  6780. {
  6781. size_t i;
  6782. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6783. if (!strcmp(s, month_names[i])) {
  6784. return (int)i;
  6785. }
  6786. }
  6787. return -1;
  6788. }
  6789. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6790. static time_t
  6791. parse_date_string(const char *datetime)
  6792. {
  6793. char month_str[32] = {0};
  6794. int second, minute, hour, day, month, year;
  6795. time_t result = (time_t)0;
  6796. struct tm tm;
  6797. if ((sscanf(datetime,
  6798. "%d/%3s/%d %d:%d:%d",
  6799. &day,
  6800. month_str,
  6801. &year,
  6802. &hour,
  6803. &minute,
  6804. &second)
  6805. == 6)
  6806. || (sscanf(datetime,
  6807. "%d %3s %d %d:%d:%d",
  6808. &day,
  6809. month_str,
  6810. &year,
  6811. &hour,
  6812. &minute,
  6813. &second)
  6814. == 6)
  6815. || (sscanf(datetime,
  6816. "%*3s, %d %3s %d %d:%d:%d",
  6817. &day,
  6818. month_str,
  6819. &year,
  6820. &hour,
  6821. &minute,
  6822. &second)
  6823. == 6)
  6824. || (sscanf(datetime,
  6825. "%d-%3s-%d %d:%d:%d",
  6826. &day,
  6827. month_str,
  6828. &year,
  6829. &hour,
  6830. &minute,
  6831. &second)
  6832. == 6)) {
  6833. month = get_month_index(month_str);
  6834. if ((month >= 0) && (year >= 1970)) {
  6835. memset(&tm, 0, sizeof(tm));
  6836. tm.tm_year = year - 1900;
  6837. tm.tm_mon = month;
  6838. tm.tm_mday = day;
  6839. tm.tm_hour = hour;
  6840. tm.tm_min = minute;
  6841. tm.tm_sec = second;
  6842. result = timegm(&tm);
  6843. }
  6844. }
  6845. return result;
  6846. }
  6847. #endif /* !NO_CACHING */
  6848. /* Pre-process URIs according to RFC + protect against directory disclosure
  6849. * attacks by removing '..', excessive '/' and '\' characters */
  6850. static void
  6851. remove_dot_segments(char *inout)
  6852. {
  6853. /* Windows backend protection
  6854. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6855. * in URI by slash */
  6856. char *out_end = inout;
  6857. char *in = inout;
  6858. if (!in) {
  6859. /* Param error. */
  6860. return;
  6861. }
  6862. while (*in) {
  6863. if (*in == '\\') {
  6864. *in = '/';
  6865. }
  6866. in++;
  6867. }
  6868. /* Algorithm "remove_dot_segments" from
  6869. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6870. /* Step 1:
  6871. * The input buffer is initialized.
  6872. * The output buffer is initialized to the empty string.
  6873. */
  6874. in = inout;
  6875. /* Step 2:
  6876. * While the input buffer is not empty, loop as follows:
  6877. */
  6878. /* Less than out_end of the inout buffer is used as output, so keep
  6879. * condition: out_end <= in */
  6880. while (*in) {
  6881. /* Step 2a:
  6882. * If the input buffer begins with a prefix of "../" or "./",
  6883. * then remove that prefix from the input buffer;
  6884. */
  6885. if (!strncmp(in, "../", 3)) {
  6886. in += 3;
  6887. } else if (!strncmp(in, "./", 2)) {
  6888. in += 2;
  6889. }
  6890. /* otherwise */
  6891. /* Step 2b:
  6892. * if the input buffer begins with a prefix of "/./" or "/.",
  6893. * where "." is a complete path segment, then replace that
  6894. * prefix with "/" in the input buffer;
  6895. */
  6896. else if (!strncmp(in, "/./", 3)) {
  6897. in += 2;
  6898. } else if (!strcmp(in, "/.")) {
  6899. in[1] = 0;
  6900. }
  6901. /* otherwise */
  6902. /* Step 2c:
  6903. * if the input buffer begins with a prefix of "/../" or "/..",
  6904. * where ".." is a complete path segment, then replace that
  6905. * prefix with "/" in the input buffer and remove the last
  6906. * segment and its preceding "/" (if any) from the output
  6907. * buffer;
  6908. */
  6909. else if (!strncmp(in, "/../", 4)) {
  6910. in += 3;
  6911. if (inout != out_end) {
  6912. /* remove last segment */
  6913. do {
  6914. out_end--;
  6915. } while ((inout != out_end) && (*out_end != '/'));
  6916. }
  6917. } else if (!strcmp(in, "/..")) {
  6918. in[1] = 0;
  6919. if (inout != out_end) {
  6920. /* remove last segment */
  6921. do {
  6922. out_end--;
  6923. } while ((inout != out_end) && (*out_end != '/'));
  6924. }
  6925. }
  6926. /* otherwise */
  6927. /* Step 2d:
  6928. * if the input buffer consists only of "." or "..", then remove
  6929. * that from the input buffer;
  6930. */
  6931. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6932. *in = 0;
  6933. }
  6934. /* otherwise */
  6935. /* Step 2e:
  6936. * move the first path segment in the input buffer to the end of
  6937. * the output buffer, including the initial "/" character (if
  6938. * any) and any subsequent characters up to, but not including,
  6939. * the next "/" character or the end of the input buffer.
  6940. */
  6941. else {
  6942. do {
  6943. *out_end = *in;
  6944. out_end++;
  6945. in++;
  6946. } while ((*in != 0) && (*in != '/'));
  6947. }
  6948. }
  6949. /* Step 3:
  6950. * Finally, the output buffer is returned as the result of
  6951. * remove_dot_segments.
  6952. */
  6953. /* Terminate output */
  6954. *out_end = 0;
  6955. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6956. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6957. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6958. * or "//" anymore.
  6959. */
  6960. out_end = in = inout;
  6961. while (*in) {
  6962. if (*in == '.') {
  6963. /* remove . at the end or preceding of / */
  6964. char *in_ahead = in;
  6965. do {
  6966. in_ahead++;
  6967. } while (*in_ahead == '.');
  6968. if (*in_ahead == '/') {
  6969. in = in_ahead;
  6970. if ((out_end != inout) && (out_end[-1] == '/')) {
  6971. /* remove generated // */
  6972. out_end--;
  6973. }
  6974. } else if (*in_ahead == 0) {
  6975. in = in_ahead;
  6976. } else {
  6977. do {
  6978. *out_end++ = '.';
  6979. in++;
  6980. } while (in != in_ahead);
  6981. }
  6982. } else if (*in == '/') {
  6983. /* replace // by / */
  6984. *out_end++ = '/';
  6985. do {
  6986. in++;
  6987. } while (*in == '/');
  6988. } else {
  6989. *out_end++ = *in;
  6990. in++;
  6991. }
  6992. }
  6993. *out_end = 0;
  6994. }
  6995. static const struct {
  6996. const char *extension;
  6997. size_t ext_len;
  6998. const char *mime_type;
  6999. } builtin_mime_types[] = {
  7000. /* IANA registered MIME types
  7001. * (http://www.iana.org/assignments/media-types)
  7002. * application types */
  7003. {".bin", 4, "application/octet-stream"},
  7004. {".deb", 4, "application/octet-stream"},
  7005. {".dmg", 4, "application/octet-stream"},
  7006. {".dll", 4, "application/octet-stream"},
  7007. {".doc", 4, "application/msword"},
  7008. {".eps", 4, "application/postscript"},
  7009. {".exe", 4, "application/octet-stream"},
  7010. {".iso", 4, "application/octet-stream"},
  7011. {".js", 3, "application/javascript"},
  7012. {".json", 5, "application/json"},
  7013. {".msi", 4, "application/octet-stream"},
  7014. {".pdf", 4, "application/pdf"},
  7015. {".ps", 3, "application/postscript"},
  7016. {".rtf", 4, "application/rtf"},
  7017. {".xhtml", 6, "application/xhtml+xml"},
  7018. {".xsl", 4, "application/xml"},
  7019. {".xslt", 5, "application/xml"},
  7020. /* fonts */
  7021. {".ttf", 4, "application/font-sfnt"},
  7022. {".cff", 4, "application/font-sfnt"},
  7023. {".otf", 4, "application/font-sfnt"},
  7024. {".aat", 4, "application/font-sfnt"},
  7025. {".sil", 4, "application/font-sfnt"},
  7026. {".pfr", 4, "application/font-tdpfr"},
  7027. {".woff", 5, "application/font-woff"},
  7028. {".woff2", 6, "application/font-woff2"},
  7029. /* audio */
  7030. {".mp3", 4, "audio/mpeg"},
  7031. {".oga", 4, "audio/ogg"},
  7032. {".ogg", 4, "audio/ogg"},
  7033. /* image */
  7034. {".gif", 4, "image/gif"},
  7035. {".ief", 4, "image/ief"},
  7036. {".jpeg", 5, "image/jpeg"},
  7037. {".jpg", 4, "image/jpeg"},
  7038. {".jpm", 4, "image/jpm"},
  7039. {".jpx", 4, "image/jpx"},
  7040. {".png", 4, "image/png"},
  7041. {".svg", 4, "image/svg+xml"},
  7042. {".tif", 4, "image/tiff"},
  7043. {".tiff", 5, "image/tiff"},
  7044. /* model */
  7045. {".wrl", 4, "model/vrml"},
  7046. /* text */
  7047. {".css", 4, "text/css"},
  7048. {".csv", 4, "text/csv"},
  7049. {".htm", 4, "text/html"},
  7050. {".html", 5, "text/html"},
  7051. {".sgm", 4, "text/sgml"},
  7052. {".shtm", 5, "text/html"},
  7053. {".shtml", 6, "text/html"},
  7054. {".txt", 4, "text/plain"},
  7055. {".xml", 4, "text/xml"},
  7056. /* video */
  7057. {".mov", 4, "video/quicktime"},
  7058. {".mp4", 4, "video/mp4"},
  7059. {".mpeg", 5, "video/mpeg"},
  7060. {".mpg", 4, "video/mpeg"},
  7061. {".ogv", 4, "video/ogg"},
  7062. {".qt", 3, "video/quicktime"},
  7063. /* not registered types
  7064. * (http://reference.sitepoint.com/html/mime-types-full,
  7065. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7066. {".arj", 4, "application/x-arj-compressed"},
  7067. {".gz", 3, "application/x-gunzip"},
  7068. {".rar", 4, "application/x-arj-compressed"},
  7069. {".swf", 4, "application/x-shockwave-flash"},
  7070. {".tar", 4, "application/x-tar"},
  7071. {".tgz", 4, "application/x-tar-gz"},
  7072. {".torrent", 8, "application/x-bittorrent"},
  7073. {".ppt", 4, "application/x-mspowerpoint"},
  7074. {".xls", 4, "application/x-msexcel"},
  7075. {".zip", 4, "application/x-zip-compressed"},
  7076. {".aac",
  7077. 4,
  7078. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7079. {".flac", 5, "audio/flac"},
  7080. {".aif", 4, "audio/x-aif"},
  7081. {".m3u", 4, "audio/x-mpegurl"},
  7082. {".mid", 4, "audio/x-midi"},
  7083. {".ra", 3, "audio/x-pn-realaudio"},
  7084. {".ram", 4, "audio/x-pn-realaudio"},
  7085. {".wav", 4, "audio/x-wav"},
  7086. {".bmp", 4, "image/bmp"},
  7087. {".ico", 4, "image/x-icon"},
  7088. {".pct", 4, "image/x-pct"},
  7089. {".pict", 5, "image/pict"},
  7090. {".rgb", 4, "image/x-rgb"},
  7091. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7092. {".asf", 4, "video/x-ms-asf"},
  7093. {".avi", 4, "video/x-msvideo"},
  7094. {".m4v", 4, "video/x-m4v"},
  7095. {NULL, 0, NULL}};
  7096. const char *
  7097. mg_get_builtin_mime_type(const char *path)
  7098. {
  7099. const char *ext;
  7100. size_t i, path_len;
  7101. path_len = strlen(path);
  7102. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7103. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7104. if ((path_len > builtin_mime_types[i].ext_len)
  7105. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7106. return builtin_mime_types[i].mime_type;
  7107. }
  7108. }
  7109. return "text/plain";
  7110. }
  7111. /* Look at the "path" extension and figure what mime type it has.
  7112. * Store mime type in the vector. */
  7113. static void
  7114. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7115. {
  7116. struct vec ext_vec, mime_vec;
  7117. const char *list, *ext;
  7118. size_t path_len;
  7119. path_len = strlen(path);
  7120. if ((conn == NULL) || (vec == NULL)) {
  7121. if (vec != NULL) {
  7122. memset(vec, '\0', sizeof(struct vec));
  7123. }
  7124. return;
  7125. }
  7126. /* Scan user-defined mime types first, in case user wants to
  7127. * override default mime types. */
  7128. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7129. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7130. /* ext now points to the path suffix */
  7131. ext = path + path_len - ext_vec.len;
  7132. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7133. *vec = mime_vec;
  7134. return;
  7135. }
  7136. }
  7137. vec->ptr = mg_get_builtin_mime_type(path);
  7138. vec->len = strlen(vec->ptr);
  7139. }
  7140. /* Stringify binary data. Output buffer must be twice as big as input,
  7141. * because each byte takes 2 bytes in string representation */
  7142. static void
  7143. bin2str(char *to, const unsigned char *p, size_t len)
  7144. {
  7145. static const char *hex = "0123456789abcdef";
  7146. for (; len--; p++) {
  7147. *to++ = hex[p[0] >> 4];
  7148. *to++ = hex[p[0] & 0x0f];
  7149. }
  7150. *to = '\0';
  7151. }
  7152. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7153. */
  7154. char *
  7155. mg_md5(char buf[33], ...)
  7156. {
  7157. md5_byte_t hash[16];
  7158. const char *p;
  7159. va_list ap;
  7160. md5_state_t ctx;
  7161. md5_init(&ctx);
  7162. va_start(ap, buf);
  7163. while ((p = va_arg(ap, const char *)) != NULL) {
  7164. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7165. }
  7166. va_end(ap);
  7167. md5_finish(&ctx, hash);
  7168. bin2str(buf, hash, sizeof(hash));
  7169. return buf;
  7170. }
  7171. /* Check the user's password, return 1 if OK */
  7172. static int
  7173. check_password(const char *method,
  7174. const char *ha1,
  7175. const char *uri,
  7176. const char *nonce,
  7177. const char *nc,
  7178. const char *cnonce,
  7179. const char *qop,
  7180. const char *response)
  7181. {
  7182. char ha2[32 + 1], expected_response[32 + 1];
  7183. /* Some of the parameters may be NULL */
  7184. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7185. || (qop == NULL) || (response == NULL)) {
  7186. return 0;
  7187. }
  7188. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7189. if (strlen(response) != 32) {
  7190. return 0;
  7191. }
  7192. mg_md5(ha2, method, ":", uri, NULL);
  7193. mg_md5(expected_response,
  7194. ha1,
  7195. ":",
  7196. nonce,
  7197. ":",
  7198. nc,
  7199. ":",
  7200. cnonce,
  7201. ":",
  7202. qop,
  7203. ":",
  7204. ha2,
  7205. NULL);
  7206. return mg_strcasecmp(response, expected_response) == 0;
  7207. }
  7208. #if !defined(NO_FILESYSTEMS)
  7209. /* Use the global passwords file, if specified by auth_gpass option,
  7210. * or search for .htpasswd in the requested directory. */
  7211. static void
  7212. open_auth_file(struct mg_connection *conn,
  7213. const char *path,
  7214. struct mg_file *filep)
  7215. {
  7216. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7217. char name[UTF8_PATH_MAX];
  7218. const char *p, *e,
  7219. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7220. int truncated;
  7221. if (gpass != NULL) {
  7222. /* Use global passwords file */
  7223. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7224. #if defined(DEBUG)
  7225. /* Use mg_cry_internal here, since gpass has been
  7226. * configured. */
  7227. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7228. #endif
  7229. }
  7230. /* Important: using local struct mg_file to test path for
  7231. * is_directory flag. If filep is used, mg_stat() makes it
  7232. * appear as if auth file was opened.
  7233. * TODO(mid): Check if this is still required after rewriting
  7234. * mg_stat */
  7235. } else if (mg_stat(conn, path, &filep->stat)
  7236. && filep->stat.is_directory) {
  7237. mg_snprintf(conn,
  7238. &truncated,
  7239. name,
  7240. sizeof(name),
  7241. "%s/%s",
  7242. path,
  7243. PASSWORDS_FILE_NAME);
  7244. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7245. #if defined(DEBUG)
  7246. /* Don't use mg_cry_internal here, but only a trace, since
  7247. * this is a typical case. It will occur for every directory
  7248. * without a password file. */
  7249. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7250. #endif
  7251. }
  7252. } else {
  7253. /* Try to find .htpasswd in requested directory. */
  7254. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7255. if (e[0] == '/') {
  7256. break;
  7257. }
  7258. }
  7259. mg_snprintf(conn,
  7260. &truncated,
  7261. name,
  7262. sizeof(name),
  7263. "%.*s/%s",
  7264. (int)(e - p),
  7265. p,
  7266. PASSWORDS_FILE_NAME);
  7267. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7268. #if defined(DEBUG)
  7269. /* Don't use mg_cry_internal here, but only a trace, since
  7270. * this is a typical case. It will occur for every directory
  7271. * without a password file. */
  7272. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7273. #endif
  7274. }
  7275. }
  7276. }
  7277. }
  7278. #endif /* NO_FILESYSTEMS */
  7279. /* Parsed Authorization header */
  7280. struct ah {
  7281. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7282. };
  7283. /* Return 1 on success. Always initializes the ah structure. */
  7284. static int
  7285. parse_auth_header(struct mg_connection *conn,
  7286. char *buf,
  7287. size_t buf_size,
  7288. struct ah *ah)
  7289. {
  7290. char *name, *value, *s;
  7291. const char *auth_header;
  7292. uint64_t nonce;
  7293. if (!ah || !conn) {
  7294. return 0;
  7295. }
  7296. (void)memset(ah, 0, sizeof(*ah));
  7297. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7298. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7299. return 0;
  7300. }
  7301. /* Make modifiable copy of the auth header */
  7302. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7303. s = buf;
  7304. /* Parse authorization header */
  7305. for (;;) {
  7306. /* Gobble initial spaces */
  7307. while (isspace((unsigned char)*s)) {
  7308. s++;
  7309. }
  7310. name = skip_quoted(&s, "=", " ", 0);
  7311. /* Value is either quote-delimited, or ends at first comma or space.
  7312. */
  7313. if (s[0] == '\"') {
  7314. s++;
  7315. value = skip_quoted(&s, "\"", " ", '\\');
  7316. if (s[0] == ',') {
  7317. s++;
  7318. }
  7319. } else {
  7320. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7321. * uses spaces */
  7322. }
  7323. if (*name == '\0') {
  7324. break;
  7325. }
  7326. if (!strcmp(name, "username")) {
  7327. ah->user = value;
  7328. } else if (!strcmp(name, "cnonce")) {
  7329. ah->cnonce = value;
  7330. } else if (!strcmp(name, "response")) {
  7331. ah->response = value;
  7332. } else if (!strcmp(name, "uri")) {
  7333. ah->uri = value;
  7334. } else if (!strcmp(name, "qop")) {
  7335. ah->qop = value;
  7336. } else if (!strcmp(name, "nc")) {
  7337. ah->nc = value;
  7338. } else if (!strcmp(name, "nonce")) {
  7339. ah->nonce = value;
  7340. }
  7341. }
  7342. #if !defined(NO_NONCE_CHECK)
  7343. /* Read the nonce from the response. */
  7344. if (ah->nonce == NULL) {
  7345. return 0;
  7346. }
  7347. s = NULL;
  7348. nonce = strtoull(ah->nonce, &s, 10);
  7349. if ((s == NULL) || (*s != 0)) {
  7350. return 0;
  7351. }
  7352. /* Convert the nonce from the client to a number. */
  7353. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7354. /* The converted number corresponds to the time the nounce has been
  7355. * created. This should not be earlier than the server start. */
  7356. /* Server side nonce check is valuable in all situations but one:
  7357. * if the server restarts frequently, but the client should not see
  7358. * that, so the server should accept nonces from previous starts. */
  7359. /* However, the reasonable default is to not accept a nonce from a
  7360. * previous start, so if anyone changed the access rights between
  7361. * two restarts, a new login is required. */
  7362. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7363. /* nonce is from a previous start of the server and no longer valid
  7364. * (replay attack?) */
  7365. return 0;
  7366. }
  7367. /* Check if the nonce is too high, so it has not (yet) been used by the
  7368. * server. */
  7369. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7370. + conn->dom_ctx->nonce_count)) {
  7371. return 0;
  7372. }
  7373. #else
  7374. (void)nonce;
  7375. #endif
  7376. /* CGI needs it as REMOTE_USER */
  7377. if (ah->user != NULL) {
  7378. conn->request_info.remote_user =
  7379. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7380. } else {
  7381. return 0;
  7382. }
  7383. return 1;
  7384. }
  7385. static const char *
  7386. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7387. {
  7388. if (!filep) {
  7389. return NULL;
  7390. }
  7391. if (filep->access.fp != NULL) {
  7392. return fgets(buf, (int)size, filep->access.fp);
  7393. } else {
  7394. return NULL;
  7395. }
  7396. }
  7397. /* Define the initial recursion depth for procesesing htpasswd files that
  7398. * include other htpasswd
  7399. * (or even the same) files. It is not difficult to provide a file or files
  7400. * s.t. they force civetweb
  7401. * to infinitely recurse and then crash.
  7402. */
  7403. #define INITIAL_DEPTH 9
  7404. #if INITIAL_DEPTH <= 0
  7405. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7406. #endif
  7407. #if !defined(NO_FILESYSTEMS)
  7408. struct read_auth_file_struct {
  7409. struct mg_connection *conn;
  7410. struct ah ah;
  7411. const char *domain;
  7412. char buf[256 + 256 + 40];
  7413. const char *f_user;
  7414. const char *f_domain;
  7415. const char *f_ha1;
  7416. };
  7417. static int
  7418. read_auth_file(struct mg_file *filep,
  7419. struct read_auth_file_struct *workdata,
  7420. int depth)
  7421. {
  7422. int is_authorized = 0;
  7423. struct mg_file fp;
  7424. size_t l;
  7425. if (!filep || !workdata || (0 == depth)) {
  7426. return 0;
  7427. }
  7428. /* Loop over passwords file */
  7429. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7430. l = strlen(workdata->buf);
  7431. while (l > 0) {
  7432. if (isspace((unsigned char)workdata->buf[l - 1])
  7433. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7434. l--;
  7435. workdata->buf[l] = 0;
  7436. } else
  7437. break;
  7438. }
  7439. if (l < 1) {
  7440. continue;
  7441. }
  7442. workdata->f_user = workdata->buf;
  7443. if (workdata->f_user[0] == ':') {
  7444. /* user names may not contain a ':' and may not be empty,
  7445. * so lines starting with ':' may be used for a special purpose
  7446. */
  7447. if (workdata->f_user[1] == '#') {
  7448. /* :# is a comment */
  7449. continue;
  7450. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7451. if (mg_fopen(workdata->conn,
  7452. workdata->f_user + 9,
  7453. MG_FOPEN_MODE_READ,
  7454. &fp)) {
  7455. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7456. (void)mg_fclose(
  7457. &fp.access); /* ignore error on read only file */
  7458. /* No need to continue processing files once we have a
  7459. * match, since nothing will reset it back
  7460. * to 0.
  7461. */
  7462. if (is_authorized) {
  7463. return is_authorized;
  7464. }
  7465. } else {
  7466. mg_cry_internal(workdata->conn,
  7467. "%s: cannot open authorization file: %s",
  7468. __func__,
  7469. workdata->buf);
  7470. }
  7471. continue;
  7472. }
  7473. /* everything is invalid for the moment (might change in the
  7474. * future) */
  7475. mg_cry_internal(workdata->conn,
  7476. "%s: syntax error in authorization file: %s",
  7477. __func__,
  7478. workdata->buf);
  7479. continue;
  7480. }
  7481. workdata->f_domain = strchr(workdata->f_user, ':');
  7482. if (workdata->f_domain == NULL) {
  7483. mg_cry_internal(workdata->conn,
  7484. "%s: syntax error in authorization file: %s",
  7485. __func__,
  7486. workdata->buf);
  7487. continue;
  7488. }
  7489. *(char *)(workdata->f_domain) = 0;
  7490. (workdata->f_domain)++;
  7491. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7492. if (workdata->f_ha1 == NULL) {
  7493. mg_cry_internal(workdata->conn,
  7494. "%s: syntax error in authorization file: %s",
  7495. __func__,
  7496. workdata->buf);
  7497. continue;
  7498. }
  7499. *(char *)(workdata->f_ha1) = 0;
  7500. (workdata->f_ha1)++;
  7501. if (!strcmp(workdata->ah.user, workdata->f_user)
  7502. && !strcmp(workdata->domain, workdata->f_domain)) {
  7503. return check_password(workdata->conn->request_info.request_method,
  7504. workdata->f_ha1,
  7505. workdata->ah.uri,
  7506. workdata->ah.nonce,
  7507. workdata->ah.nc,
  7508. workdata->ah.cnonce,
  7509. workdata->ah.qop,
  7510. workdata->ah.response);
  7511. }
  7512. }
  7513. return is_authorized;
  7514. }
  7515. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7516. static int
  7517. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7518. {
  7519. struct read_auth_file_struct workdata;
  7520. char buf[MG_BUF_LEN];
  7521. if (!conn || !conn->dom_ctx) {
  7522. return 0;
  7523. }
  7524. memset(&workdata, 0, sizeof(workdata));
  7525. workdata.conn = conn;
  7526. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7527. return 0;
  7528. }
  7529. if (realm) {
  7530. workdata.domain = realm;
  7531. } else {
  7532. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7533. }
  7534. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7535. }
  7536. /* Public function to check http digest authentication header */
  7537. int
  7538. mg_check_digest_access_authentication(struct mg_connection *conn,
  7539. const char *realm,
  7540. const char *filename)
  7541. {
  7542. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7543. int auth;
  7544. if (!conn || !filename) {
  7545. return -1;
  7546. }
  7547. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7548. return -2;
  7549. }
  7550. auth = authorize(conn, &file, realm);
  7551. mg_fclose(&file.access);
  7552. return auth;
  7553. }
  7554. #endif /* NO_FILESYSTEMS */
  7555. /* Return 1 if request is authorised, 0 otherwise. */
  7556. static int
  7557. check_authorization(struct mg_connection *conn, const char *path)
  7558. {
  7559. #if !defined(NO_FILESYSTEMS)
  7560. char fname[UTF8_PATH_MAX];
  7561. struct vec uri_vec, filename_vec;
  7562. const char *list;
  7563. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7564. int authorized = 1, truncated;
  7565. if (!conn || !conn->dom_ctx) {
  7566. return 0;
  7567. }
  7568. list = conn->dom_ctx->config[PROTECT_URI];
  7569. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7570. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7571. mg_snprintf(conn,
  7572. &truncated,
  7573. fname,
  7574. sizeof(fname),
  7575. "%.*s",
  7576. (int)filename_vec.len,
  7577. filename_vec.ptr);
  7578. if (truncated
  7579. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7580. mg_cry_internal(conn,
  7581. "%s: cannot open %s: %s",
  7582. __func__,
  7583. fname,
  7584. strerror(errno));
  7585. }
  7586. break;
  7587. }
  7588. }
  7589. if (!is_file_opened(&file.access)) {
  7590. open_auth_file(conn, path, &file);
  7591. }
  7592. if (is_file_opened(&file.access)) {
  7593. authorized = authorize(conn, &file, NULL);
  7594. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7595. }
  7596. return authorized;
  7597. #else
  7598. (void)conn;
  7599. (void)path;
  7600. return 1;
  7601. #endif /* NO_FILESYSTEMS */
  7602. }
  7603. /* Internal function. Assumes conn is valid */
  7604. static void
  7605. send_authorization_request(struct mg_connection *conn, const char *realm)
  7606. {
  7607. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7608. int trunc = 0;
  7609. char buf[128];
  7610. if (!realm) {
  7611. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7612. }
  7613. mg_lock_context(conn->phys_ctx);
  7614. nonce += conn->dom_ctx->nonce_count;
  7615. ++conn->dom_ctx->nonce_count;
  7616. mg_unlock_context(conn->phys_ctx);
  7617. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7618. conn->must_close = 1;
  7619. /* Create 401 response */
  7620. mg_response_header_start(conn, 401);
  7621. send_no_cache_header(conn);
  7622. send_additional_header(conn);
  7623. mg_response_header_add(conn, "Content-Length", "0", -1);
  7624. /* Content for "WWW-Authenticate" header */
  7625. mg_snprintf(conn,
  7626. &trunc,
  7627. buf,
  7628. sizeof(buf),
  7629. "Digest qop=\"auth\", realm=\"%s\", "
  7630. "nonce=\"%" UINT64_FMT "\"",
  7631. realm,
  7632. nonce);
  7633. if (!trunc) {
  7634. /* !trunc should always be true */
  7635. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7636. }
  7637. /* Send all headers */
  7638. mg_response_header_send(conn);
  7639. }
  7640. /* Interface function. Parameters are provided by the user, so do
  7641. * at least some basic checks.
  7642. */
  7643. int
  7644. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7645. const char *realm)
  7646. {
  7647. if (conn && conn->dom_ctx) {
  7648. send_authorization_request(conn, realm);
  7649. return 0;
  7650. }
  7651. return -1;
  7652. }
  7653. #if !defined(NO_FILES)
  7654. static int
  7655. is_authorized_for_put(struct mg_connection *conn)
  7656. {
  7657. int ret = 0;
  7658. if (conn) {
  7659. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7660. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7661. if (passfile != NULL
  7662. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7663. ret = authorize(conn, &file, NULL);
  7664. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7665. }
  7666. }
  7667. DEBUG_TRACE("file write autorization: %i", ret);
  7668. return ret;
  7669. }
  7670. #endif
  7671. int
  7672. mg_modify_passwords_file_ha1(const char *fname,
  7673. const char *domain,
  7674. const char *user,
  7675. const char *ha1)
  7676. {
  7677. int found = 0, i, result = 1;
  7678. char line[512], u[256], d[256], h[256];
  7679. struct stat st = {0};
  7680. FILE *fp = NULL;
  7681. char *temp_file = NULL;
  7682. int temp_file_offs = 0;
  7683. /* Regard empty password as no password - remove user record. */
  7684. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7685. ha1 = NULL;
  7686. }
  7687. /* Other arguments must not be empty */
  7688. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7689. return 0;
  7690. }
  7691. /* Using the given file format, user name and domain must not contain
  7692. * the ':' character */
  7693. if (strchr(user, ':') != NULL) {
  7694. return 0;
  7695. }
  7696. if (strchr(domain, ':') != NULL) {
  7697. return 0;
  7698. }
  7699. /* Do not allow control characters like newline in user name and domain.
  7700. * Do not allow excessively long names either. */
  7701. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7702. if (iscntrl((unsigned char)user[i])) {
  7703. return 0;
  7704. }
  7705. }
  7706. if (user[i]) {
  7707. return 0; /* user name too long */
  7708. }
  7709. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7710. if (iscntrl((unsigned char)domain[i])) {
  7711. return 0;
  7712. }
  7713. }
  7714. if (domain[i]) {
  7715. return 0; /* domain name too long */
  7716. }
  7717. /* The maximum length of the path to the password file is limited */
  7718. if (strlen(fname) >= UTF8_PATH_MAX) {
  7719. return 0;
  7720. }
  7721. /* Check if the file exists, and get file size */
  7722. if (0 == stat(fname, &st)) {
  7723. int temp_buf_len = (int)st.st_size + 1024;
  7724. /* Allocate memory (instead of using a temporary file) */
  7725. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7726. if (!temp_file) {
  7727. /* Out of memory */
  7728. return 0;
  7729. }
  7730. /* File exists. Read it into a memory buffer. */
  7731. fp = fopen(fname, "r");
  7732. if (fp == NULL) {
  7733. /* Cannot read file. No permission? */
  7734. mg_free(temp_file);
  7735. return 0;
  7736. }
  7737. /* Read content and store in memory */
  7738. while ((fgets(line, sizeof(line), fp) != NULL)
  7739. && ((temp_file_offs + 600) < temp_buf_len)) {
  7740. /* file format is "user:domain:hash\n" */
  7741. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7742. continue;
  7743. }
  7744. u[255] = 0;
  7745. d[255] = 0;
  7746. h[255] = 0;
  7747. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7748. /* Found the user: change the password hash or drop the user
  7749. */
  7750. if ((ha1 != NULL) && (!found)) {
  7751. i = sprintf(temp_file + temp_file_offs,
  7752. "%s:%s:%s\n",
  7753. user,
  7754. domain,
  7755. ha1);
  7756. if (i < 1) {
  7757. fclose(fp);
  7758. mg_free(temp_file);
  7759. return 0;
  7760. }
  7761. temp_file_offs += i;
  7762. }
  7763. found = 1;
  7764. } else {
  7765. /* Copy existing user, including password hash */
  7766. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7767. if (i < 1) {
  7768. fclose(fp);
  7769. mg_free(temp_file);
  7770. return 0;
  7771. }
  7772. temp_file_offs += i;
  7773. }
  7774. }
  7775. fclose(fp);
  7776. }
  7777. /* Create new file */
  7778. fp = fopen(fname, "w");
  7779. if (!fp) {
  7780. mg_free(temp_file);
  7781. return 0;
  7782. }
  7783. #if !defined(_WIN32)
  7784. /* On Linux & co., restrict file read/write permissions to the owner */
  7785. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7786. result = 0;
  7787. }
  7788. #endif
  7789. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7790. /* Store buffered content of old file */
  7791. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7792. != (size_t)temp_file_offs) {
  7793. result = 0;
  7794. }
  7795. }
  7796. /* If new user, just add it */
  7797. if ((ha1 != NULL) && (!found)) {
  7798. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7799. result = 0;
  7800. }
  7801. }
  7802. /* All data written */
  7803. if (fclose(fp) != 0) {
  7804. result = 0;
  7805. }
  7806. mg_free(temp_file);
  7807. return result;
  7808. }
  7809. int
  7810. mg_modify_passwords_file(const char *fname,
  7811. const char *domain,
  7812. const char *user,
  7813. const char *pass)
  7814. {
  7815. char ha1buf[33];
  7816. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7817. return 0;
  7818. }
  7819. if ((pass == NULL) || (pass[0] == 0)) {
  7820. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7821. }
  7822. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7823. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7824. }
  7825. static int
  7826. is_valid_port(unsigned long port)
  7827. {
  7828. return (port <= 0xffff);
  7829. }
  7830. static int
  7831. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7832. {
  7833. struct addrinfo hints, *res, *ressave;
  7834. int func_ret = 0;
  7835. int gai_ret;
  7836. memset(&hints, 0, sizeof(struct addrinfo));
  7837. hints.ai_family = af;
  7838. if (!resolve_src) {
  7839. hints.ai_flags = AI_NUMERICHOST;
  7840. }
  7841. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7842. if (gai_ret != 0) {
  7843. /* gai_strerror could be used to convert gai_ret to a string */
  7844. /* POSIX return values: see
  7845. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7846. */
  7847. /* Windows return values: see
  7848. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7849. */
  7850. return 0;
  7851. }
  7852. ressave = res;
  7853. while (res) {
  7854. if ((dstlen >= (size_t)res->ai_addrlen)
  7855. && (res->ai_addr->sa_family == af)) {
  7856. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7857. func_ret = 1;
  7858. }
  7859. res = res->ai_next;
  7860. }
  7861. freeaddrinfo(ressave);
  7862. return func_ret;
  7863. }
  7864. static int
  7865. connect_socket(
  7866. struct mg_context *ctx /* may be NULL */,
  7867. const char *host,
  7868. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7869. int use_ssl, /* 0 or 1 */
  7870. char *ebuf,
  7871. size_t ebuf_len,
  7872. SOCKET *sock /* output: socket, must not be NULL */,
  7873. union usa *sa /* output: socket address, must not be NULL */
  7874. )
  7875. {
  7876. int ip_ver = 0;
  7877. int conn_ret = -1;
  7878. int sockerr = 0;
  7879. *sock = INVALID_SOCKET;
  7880. memset(sa, 0, sizeof(*sa));
  7881. if (ebuf_len > 0) {
  7882. *ebuf = 0;
  7883. }
  7884. if (host == NULL) {
  7885. mg_snprintf(NULL,
  7886. NULL, /* No truncation check for ebuf */
  7887. ebuf,
  7888. ebuf_len,
  7889. "%s",
  7890. "NULL host");
  7891. return 0;
  7892. }
  7893. #if defined(USE_X_DOM_SOCKET)
  7894. if (port == -99) {
  7895. /* Unix domain socket */
  7896. size_t hostlen = strlen(host);
  7897. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7898. mg_snprintf(NULL,
  7899. NULL, /* No truncation check for ebuf */
  7900. ebuf,
  7901. ebuf_len,
  7902. "%s",
  7903. "host length exceeds limit");
  7904. return 0;
  7905. }
  7906. } else
  7907. #endif
  7908. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7909. mg_snprintf(NULL,
  7910. NULL, /* No truncation check for ebuf */
  7911. ebuf,
  7912. ebuf_len,
  7913. "%s",
  7914. "invalid port");
  7915. return 0;
  7916. }
  7917. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7918. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7919. if (use_ssl && (TLS_client_method == NULL)) {
  7920. mg_snprintf(NULL,
  7921. NULL, /* No truncation check for ebuf */
  7922. ebuf,
  7923. ebuf_len,
  7924. "%s",
  7925. "SSL is not initialized");
  7926. return 0;
  7927. }
  7928. #else
  7929. if (use_ssl && (SSLv23_client_method == NULL)) {
  7930. mg_snprintf(NULL,
  7931. NULL, /* No truncation check for ebuf */
  7932. ebuf,
  7933. ebuf_len,
  7934. "%s",
  7935. "SSL is not initialized");
  7936. return 0;
  7937. }
  7938. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7939. #else
  7940. (void)use_ssl;
  7941. #endif /* NO SSL */
  7942. #if defined(USE_X_DOM_SOCKET)
  7943. if (port == -99) {
  7944. size_t hostlen = strlen(host);
  7945. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7946. ip_ver = -99;
  7947. sa->sun.sun_family = AF_UNIX;
  7948. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7949. memcpy(sa->sun.sun_path, host, hostlen);
  7950. } else
  7951. #endif
  7952. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7953. sa->sin.sin_port = htons((uint16_t)port);
  7954. ip_ver = 4;
  7955. #if defined(USE_IPV6)
  7956. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7957. sa->sin6.sin6_port = htons((uint16_t)port);
  7958. ip_ver = 6;
  7959. } else if (host[0] == '[') {
  7960. /* While getaddrinfo on Windows will work with [::1],
  7961. * getaddrinfo on Linux only works with ::1 (without []). */
  7962. size_t l = strlen(host + 1);
  7963. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7964. if (h) {
  7965. h[l - 1] = 0;
  7966. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7967. sa->sin6.sin6_port = htons((uint16_t)port);
  7968. ip_ver = 6;
  7969. }
  7970. mg_free(h);
  7971. }
  7972. #endif
  7973. }
  7974. if (ip_ver == 0) {
  7975. mg_snprintf(NULL,
  7976. NULL, /* No truncation check for ebuf */
  7977. ebuf,
  7978. ebuf_len,
  7979. "%s",
  7980. "host not found");
  7981. return 0;
  7982. }
  7983. if (ip_ver == 4) {
  7984. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7985. }
  7986. #if defined(USE_IPV6)
  7987. else if (ip_ver == 6) {
  7988. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7989. }
  7990. #endif
  7991. #if defined(USE_X_DOM_SOCKET)
  7992. else if (ip_ver == -99) {
  7993. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7994. }
  7995. #endif
  7996. if (*sock == INVALID_SOCKET) {
  7997. mg_snprintf(NULL,
  7998. NULL, /* No truncation check for ebuf */
  7999. ebuf,
  8000. ebuf_len,
  8001. "socket(): %s",
  8002. strerror(ERRNO));
  8003. return 0;
  8004. }
  8005. if (0 != set_non_blocking_mode(*sock)) {
  8006. mg_snprintf(NULL,
  8007. NULL, /* No truncation check for ebuf */
  8008. ebuf,
  8009. ebuf_len,
  8010. "Cannot set socket to non-blocking: %s",
  8011. strerror(ERRNO));
  8012. closesocket(*sock);
  8013. *sock = INVALID_SOCKET;
  8014. return 0;
  8015. }
  8016. set_close_on_exec(*sock, NULL, ctx);
  8017. if (ip_ver == 4) {
  8018. /* connected with IPv4 */
  8019. conn_ret = connect(*sock,
  8020. (struct sockaddr *)((void *)&sa->sin),
  8021. sizeof(sa->sin));
  8022. }
  8023. #if defined(USE_IPV6)
  8024. else if (ip_ver == 6) {
  8025. /* connected with IPv6 */
  8026. conn_ret = connect(*sock,
  8027. (struct sockaddr *)((void *)&sa->sin6),
  8028. sizeof(sa->sin6));
  8029. }
  8030. #endif
  8031. #if defined(USE_X_DOM_SOCKET)
  8032. else if (ip_ver == -99) {
  8033. /* connected to domain socket */
  8034. conn_ret = connect(*sock,
  8035. (struct sockaddr *)((void *)&sa->sun),
  8036. sizeof(sa->sun));
  8037. }
  8038. #endif
  8039. if (conn_ret != 0) {
  8040. sockerr = ERRNO;
  8041. }
  8042. #if defined(_WIN32)
  8043. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8044. #else
  8045. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8046. #endif
  8047. /* Data for getsockopt */
  8048. void *psockerr = &sockerr;
  8049. int ret;
  8050. #if defined(_WIN32)
  8051. int len = (int)sizeof(sockerr);
  8052. #else
  8053. socklen_t len = (socklen_t)sizeof(sockerr);
  8054. #endif
  8055. /* Data for poll */
  8056. struct mg_pollfd pfd[1];
  8057. int pollres;
  8058. int ms_wait = 10000; /* 10 second timeout */
  8059. stop_flag_t nonstop;
  8060. STOP_FLAG_ASSIGN(&nonstop, 0);
  8061. /* For a non-blocking socket, the connect sequence is:
  8062. * 1) call connect (will not block)
  8063. * 2) wait until the socket is ready for writing (select or poll)
  8064. * 3) check connection state with getsockopt
  8065. */
  8066. pfd[0].fd = *sock;
  8067. pfd[0].events = POLLOUT;
  8068. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8069. if (pollres != 1) {
  8070. /* Not connected */
  8071. mg_snprintf(NULL,
  8072. NULL, /* No truncation check for ebuf */
  8073. ebuf,
  8074. ebuf_len,
  8075. "connect(%s:%d): timeout",
  8076. host,
  8077. port);
  8078. closesocket(*sock);
  8079. *sock = INVALID_SOCKET;
  8080. return 0;
  8081. }
  8082. #if defined(_WIN32)
  8083. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8084. #else
  8085. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8086. #endif
  8087. if ((ret == 0) && (sockerr == 0)) {
  8088. conn_ret = 0;
  8089. }
  8090. }
  8091. if (conn_ret != 0) {
  8092. /* Not connected */
  8093. mg_snprintf(NULL,
  8094. NULL, /* No truncation check for ebuf */
  8095. ebuf,
  8096. ebuf_len,
  8097. "connect(%s:%d): error %s",
  8098. host,
  8099. port,
  8100. strerror(sockerr));
  8101. closesocket(*sock);
  8102. *sock = INVALID_SOCKET;
  8103. return 0;
  8104. }
  8105. return 1;
  8106. }
  8107. int
  8108. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8109. {
  8110. static const char *dont_escape = "._-$,;~()";
  8111. static const char *hex = "0123456789abcdef";
  8112. char *pos = dst;
  8113. const char *end = dst + dst_len - 1;
  8114. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8115. if (isalnum((unsigned char)*src)
  8116. || (strchr(dont_escape, *src) != NULL)) {
  8117. *pos = *src;
  8118. } else if (pos + 2 < end) {
  8119. pos[0] = '%';
  8120. pos[1] = hex[(unsigned char)*src >> 4];
  8121. pos[2] = hex[(unsigned char)*src & 0xf];
  8122. pos += 2;
  8123. } else {
  8124. break;
  8125. }
  8126. }
  8127. *pos = '\0';
  8128. return (*src == '\0') ? (int)(pos - dst) : -1;
  8129. }
  8130. /* Return 0 on success, non-zero if an error occurs. */
  8131. static int
  8132. print_dir_entry(struct mg_connection *conn, struct de *de)
  8133. {
  8134. size_t namesize, escsize, i;
  8135. char *href, *esc, *p;
  8136. char size[64], mod[64];
  8137. #if defined(REENTRANT_TIME)
  8138. struct tm _tm;
  8139. struct tm *tm = &_tm;
  8140. #else
  8141. struct tm *tm;
  8142. #endif
  8143. /* Estimate worst case size for encoding and escaping */
  8144. namesize = strlen(de->file_name) + 1;
  8145. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8146. href = (char *)mg_malloc(namesize * 3 + escsize);
  8147. if (href == NULL) {
  8148. return -1;
  8149. }
  8150. mg_url_encode(de->file_name, href, namesize * 3);
  8151. esc = NULL;
  8152. if (escsize > 0) {
  8153. /* HTML escaping needed */
  8154. esc = href + namesize * 3;
  8155. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8156. mg_strlcpy(p, de->file_name + i, 2);
  8157. if (*p == '&') {
  8158. strcpy(p, "&amp;");
  8159. } else if (*p == '<') {
  8160. strcpy(p, "&lt;");
  8161. } else if (*p == '>') {
  8162. strcpy(p, "&gt;");
  8163. }
  8164. }
  8165. }
  8166. if (de->file.is_directory) {
  8167. mg_snprintf(conn,
  8168. NULL, /* Buffer is big enough */
  8169. size,
  8170. sizeof(size),
  8171. "%s",
  8172. "[DIRECTORY]");
  8173. } else {
  8174. /* We use (signed) cast below because MSVC 6 compiler cannot
  8175. * convert unsigned __int64 to double. Sigh. */
  8176. if (de->file.size < 1024) {
  8177. mg_snprintf(conn,
  8178. NULL, /* Buffer is big enough */
  8179. size,
  8180. sizeof(size),
  8181. "%d",
  8182. (int)de->file.size);
  8183. } else if (de->file.size < 0x100000) {
  8184. mg_snprintf(conn,
  8185. NULL, /* Buffer is big enough */
  8186. size,
  8187. sizeof(size),
  8188. "%.1fk",
  8189. (double)de->file.size / 1024.0);
  8190. } else if (de->file.size < 0x40000000) {
  8191. mg_snprintf(conn,
  8192. NULL, /* Buffer is big enough */
  8193. size,
  8194. sizeof(size),
  8195. "%.1fM",
  8196. (double)de->file.size / 1048576);
  8197. } else {
  8198. mg_snprintf(conn,
  8199. NULL, /* Buffer is big enough */
  8200. size,
  8201. sizeof(size),
  8202. "%.1fG",
  8203. (double)de->file.size / 1073741824);
  8204. }
  8205. }
  8206. /* Note: mg_snprintf will not cause a buffer overflow above.
  8207. * So, string truncation checks are not required here. */
  8208. #if defined(REENTRANT_TIME)
  8209. localtime_r(&de->file.last_modified, tm);
  8210. #else
  8211. tm = localtime(&de->file.last_modified);
  8212. #endif
  8213. if (tm != NULL) {
  8214. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8215. } else {
  8216. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8217. mod[sizeof(mod) - 1] = '\0';
  8218. }
  8219. mg_printf(conn,
  8220. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8221. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8222. href,
  8223. de->file.is_directory ? "/" : "",
  8224. esc ? esc : de->file_name,
  8225. de->file.is_directory ? "/" : "",
  8226. mod,
  8227. size);
  8228. mg_free(href);
  8229. return 0;
  8230. }
  8231. /* This function is called from send_directory() and used for
  8232. * sorting directory entries by size, or name, or modification time.
  8233. * On windows, __cdecl specification is needed in case if project is built
  8234. * with __stdcall convention. qsort always requires __cdels callback. */
  8235. static int WINCDECL
  8236. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8237. {
  8238. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8239. if (p1 && p2) {
  8240. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8241. int cmp_result = 0;
  8242. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8243. query_string = "n";
  8244. }
  8245. if (a->file.is_directory && !b->file.is_directory) {
  8246. return -1; /* Always put directories on top */
  8247. } else if (!a->file.is_directory && b->file.is_directory) {
  8248. return 1; /* Always put directories on top */
  8249. } else if (*query_string == 'n') {
  8250. cmp_result = strcmp(a->file_name, b->file_name);
  8251. } else if (*query_string == 's') {
  8252. cmp_result = (a->file.size == b->file.size)
  8253. ? 0
  8254. : ((a->file.size > b->file.size) ? 1 : -1);
  8255. } else if (*query_string == 'd') {
  8256. cmp_result =
  8257. (a->file.last_modified == b->file.last_modified)
  8258. ? 0
  8259. : ((a->file.last_modified > b->file.last_modified) ? 1
  8260. : -1);
  8261. }
  8262. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8263. }
  8264. return 0;
  8265. }
  8266. static int
  8267. must_hide_file(struct mg_connection *conn, const char *path)
  8268. {
  8269. if (conn && conn->dom_ctx) {
  8270. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8271. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8272. return (match_prefix_strlen(pw_pattern, path) > 0)
  8273. || (match_prefix_strlen(pattern, path) > 0);
  8274. }
  8275. return 0;
  8276. }
  8277. #if !defined(NO_FILESYSTEMS)
  8278. static int
  8279. scan_directory(struct mg_connection *conn,
  8280. const char *dir,
  8281. void *data,
  8282. int (*cb)(struct de *, void *))
  8283. {
  8284. char path[UTF8_PATH_MAX];
  8285. struct dirent *dp;
  8286. DIR *dirp;
  8287. struct de de;
  8288. int truncated;
  8289. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8290. return 0;
  8291. } else {
  8292. while ((dp = mg_readdir(dirp)) != NULL) {
  8293. /* Do not show current dir and hidden files */
  8294. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8295. || must_hide_file(conn, dp->d_name)) {
  8296. continue;
  8297. }
  8298. mg_snprintf(
  8299. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8300. /* If we don't memset stat structure to zero, mtime will have
  8301. * garbage and strftime() will segfault later on in
  8302. * print_dir_entry(). memset is required only if mg_stat()
  8303. * fails. For more details, see
  8304. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8305. memset(&de.file, 0, sizeof(de.file));
  8306. if (truncated) {
  8307. /* If the path is not complete, skip processing. */
  8308. continue;
  8309. }
  8310. if (!mg_stat(conn, path, &de.file)) {
  8311. mg_cry_internal(conn,
  8312. "%s: mg_stat(%s) failed: %s",
  8313. __func__,
  8314. path,
  8315. strerror(ERRNO));
  8316. }
  8317. de.file_name = dp->d_name;
  8318. if (cb(&de, data)) {
  8319. /* stopped */
  8320. break;
  8321. }
  8322. }
  8323. (void)mg_closedir(dirp);
  8324. }
  8325. return 1;
  8326. }
  8327. #endif /* NO_FILESYSTEMS */
  8328. #if !defined(NO_FILES)
  8329. static int
  8330. remove_directory(struct mg_connection *conn, const char *dir)
  8331. {
  8332. char path[UTF8_PATH_MAX];
  8333. struct dirent *dp;
  8334. DIR *dirp;
  8335. struct de de;
  8336. int truncated;
  8337. int ok = 1;
  8338. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8339. return 0;
  8340. } else {
  8341. while ((dp = mg_readdir(dirp)) != NULL) {
  8342. /* Do not show current dir (but show hidden files as they will
  8343. * also be removed) */
  8344. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8345. continue;
  8346. }
  8347. mg_snprintf(
  8348. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8349. /* If we don't memset stat structure to zero, mtime will have
  8350. * garbage and strftime() will segfault later on in
  8351. * print_dir_entry(). memset is required only if mg_stat()
  8352. * fails. For more details, see
  8353. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8354. memset(&de.file, 0, sizeof(de.file));
  8355. if (truncated) {
  8356. /* Do not delete anything shorter */
  8357. ok = 0;
  8358. continue;
  8359. }
  8360. if (!mg_stat(conn, path, &de.file)) {
  8361. mg_cry_internal(conn,
  8362. "%s: mg_stat(%s) failed: %s",
  8363. __func__,
  8364. path,
  8365. strerror(ERRNO));
  8366. ok = 0;
  8367. }
  8368. if (de.file.is_directory) {
  8369. if (remove_directory(conn, path) == 0) {
  8370. ok = 0;
  8371. }
  8372. } else {
  8373. /* This will fail file is the file is in memory */
  8374. if (mg_remove(conn, path) == 0) {
  8375. ok = 0;
  8376. }
  8377. }
  8378. }
  8379. (void)mg_closedir(dirp);
  8380. IGNORE_UNUSED_RESULT(rmdir(dir));
  8381. }
  8382. return ok;
  8383. }
  8384. #endif
  8385. struct dir_scan_data {
  8386. struct de *entries;
  8387. size_t num_entries;
  8388. size_t arr_size;
  8389. };
  8390. #if !defined(NO_FILESYSTEMS)
  8391. static int
  8392. dir_scan_callback(struct de *de, void *data)
  8393. {
  8394. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8395. struct de *entries = dsd->entries;
  8396. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8397. /* Here "entries" is a temporary pointer and can be replaced,
  8398. * "dsd->entries" is the original pointer */
  8399. entries =
  8400. (struct de *)mg_realloc(entries,
  8401. dsd->arr_size * 2 * sizeof(entries[0]));
  8402. if (entries == NULL) {
  8403. /* stop scan */
  8404. return 1;
  8405. }
  8406. dsd->entries = entries;
  8407. dsd->arr_size *= 2;
  8408. }
  8409. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8410. if (entries[dsd->num_entries].file_name == NULL) {
  8411. /* stop scan */
  8412. return 1;
  8413. }
  8414. entries[dsd->num_entries].file = de->file;
  8415. dsd->num_entries++;
  8416. return 0;
  8417. }
  8418. static void
  8419. handle_directory_request(struct mg_connection *conn, const char *dir)
  8420. {
  8421. size_t i;
  8422. int sort_direction;
  8423. struct dir_scan_data data = {NULL, 0, 128};
  8424. char date[64], *esc, *p;
  8425. const char *title;
  8426. time_t curtime = time(NULL);
  8427. if (!conn) {
  8428. return;
  8429. }
  8430. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8431. mg_send_http_error(conn,
  8432. 500,
  8433. "Error: Cannot open directory\nopendir(%s): %s",
  8434. dir,
  8435. strerror(ERRNO));
  8436. return;
  8437. }
  8438. gmt_time_string(date, sizeof(date), &curtime);
  8439. esc = NULL;
  8440. title = conn->request_info.local_uri;
  8441. if (title[strcspn(title, "&<>")]) {
  8442. /* HTML escaping needed */
  8443. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8444. if (esc) {
  8445. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8446. mg_strlcpy(p, title + i, 2);
  8447. if (*p == '&') {
  8448. strcpy(p, "&amp;");
  8449. } else if (*p == '<') {
  8450. strcpy(p, "&lt;");
  8451. } else if (*p == '>') {
  8452. strcpy(p, "&gt;");
  8453. }
  8454. }
  8455. } else {
  8456. title = "";
  8457. }
  8458. }
  8459. sort_direction = ((conn->request_info.query_string != NULL)
  8460. && (conn->request_info.query_string[0] != '\0')
  8461. && (conn->request_info.query_string[1] == 'd'))
  8462. ? 'a'
  8463. : 'd';
  8464. conn->must_close = 1;
  8465. /* Create 200 OK response */
  8466. mg_response_header_start(conn, 200);
  8467. send_static_cache_header(conn);
  8468. send_additional_header(conn);
  8469. mg_response_header_add(conn,
  8470. "Content-Type",
  8471. "text/html; charset=utf-8",
  8472. -1);
  8473. /* Send all headers */
  8474. mg_response_header_send(conn);
  8475. /* Body */
  8476. mg_printf(conn,
  8477. "<html><head><title>Index of %s</title>"
  8478. "<style>th {text-align: left;}</style></head>"
  8479. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8480. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8481. "<th><a href=\"?d%c\">Modified</a></th>"
  8482. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8483. "<tr><td colspan=\"3\"><hr></td></tr>",
  8484. esc ? esc : title,
  8485. esc ? esc : title,
  8486. sort_direction,
  8487. sort_direction,
  8488. sort_direction);
  8489. mg_free(esc);
  8490. /* Print first entry - link to a parent directory */
  8491. mg_printf(conn,
  8492. "<tr><td><a href=\"%s\">%s</a></td>"
  8493. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8494. "..",
  8495. "Parent directory",
  8496. "-",
  8497. "-");
  8498. /* Sort and print directory entries */
  8499. if (data.entries != NULL) {
  8500. mg_qsort(data.entries,
  8501. data.num_entries,
  8502. sizeof(data.entries[0]),
  8503. compare_dir_entries,
  8504. (void *)conn->request_info.query_string);
  8505. for (i = 0; i < data.num_entries; i++) {
  8506. print_dir_entry(conn, &data.entries[i]);
  8507. mg_free(data.entries[i].file_name);
  8508. }
  8509. mg_free(data.entries);
  8510. }
  8511. mg_printf(conn, "%s", "</table></pre></body></html>");
  8512. conn->status_code = 200;
  8513. }
  8514. #endif /* NO_FILESYSTEMS */
  8515. /* Send len bytes from the opened file to the client. */
  8516. static void
  8517. send_file_data(struct mg_connection *conn,
  8518. struct mg_file *filep,
  8519. int64_t offset,
  8520. int64_t len,
  8521. int no_buffering)
  8522. {
  8523. char buf[MG_BUF_LEN];
  8524. int to_read, num_read, num_written;
  8525. int64_t size;
  8526. if (!filep || !conn) {
  8527. return;
  8528. }
  8529. /* Sanity check the offset */
  8530. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8531. : (int64_t)(filep->stat.size);
  8532. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8533. if (len > 0 && filep->access.fp != NULL) {
  8534. /* file stored on disk */
  8535. #if defined(__linux__)
  8536. /* sendfile is only available for Linux */
  8537. if ((conn->ssl == 0) && (conn->throttle == 0)
  8538. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8539. "yes"))) {
  8540. off_t sf_offs = (off_t)offset;
  8541. ssize_t sf_sent;
  8542. int sf_file = fileno(filep->access.fp);
  8543. int loop_cnt = 0;
  8544. do {
  8545. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8546. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8547. size_t sf_tosend =
  8548. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8549. sf_sent =
  8550. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8551. if (sf_sent > 0) {
  8552. len -= sf_sent;
  8553. offset += sf_sent;
  8554. } else if (loop_cnt == 0) {
  8555. /* This file can not be sent using sendfile.
  8556. * This might be the case for pseudo-files in the
  8557. * /sys/ and /proc/ file system.
  8558. * Use the regular user mode copy code instead. */
  8559. break;
  8560. } else if (sf_sent == 0) {
  8561. /* No error, but 0 bytes sent. May be EOF? */
  8562. return;
  8563. }
  8564. loop_cnt++;
  8565. } while ((len > 0) && (sf_sent >= 0));
  8566. if (sf_sent > 0) {
  8567. return; /* OK */
  8568. }
  8569. /* sf_sent<0 means error, thus fall back to the classic way */
  8570. /* This is always the case, if sf_file is not a "normal" file,
  8571. * e.g., for sending data from the output of a CGI process. */
  8572. offset = (int64_t)sf_offs;
  8573. }
  8574. #endif
  8575. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8576. mg_cry_internal(conn,
  8577. "%s: fseeko() failed: %s",
  8578. __func__,
  8579. strerror(ERRNO));
  8580. mg_send_http_error(
  8581. conn,
  8582. 500,
  8583. "%s",
  8584. "Error: Unable to access file at requested position.");
  8585. } else {
  8586. while (len > 0) {
  8587. /* Calculate how much to read from the file into the buffer. */
  8588. /* If no_buffering is set, we should not wait until the
  8589. * CGI->Server buffer is filled, but send everything
  8590. * immediately. In theory buffering could be turned off using
  8591. * setbuf(filep->access.fp, NULL);
  8592. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8593. * but in practice this does not work. A "Linux only" solution
  8594. * may be to use select(). The only portable way is to read byte
  8595. * by byte, but this is quite inefficient from a performance
  8596. * point of view. */
  8597. to_read = no_buffering ? 1 : sizeof(buf);
  8598. if ((int64_t)to_read > len) {
  8599. to_read = (int)len;
  8600. }
  8601. /* Read from file, exit the loop on error */
  8602. if ((num_read =
  8603. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8604. <= 0) {
  8605. break;
  8606. }
  8607. /* Send read bytes to the client, exit the loop on error */
  8608. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8609. != num_read) {
  8610. break;
  8611. }
  8612. /* Both read and were successful, adjust counters */
  8613. len -= num_written;
  8614. }
  8615. }
  8616. }
  8617. }
  8618. static int
  8619. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8620. {
  8621. return sscanf(header,
  8622. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8623. a,
  8624. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8625. // to an integer value, but function will not report
  8626. // conversion errors; consider using 'strtol' instead
  8627. }
  8628. static void
  8629. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8630. {
  8631. if ((filestat != NULL) && (buf != NULL)) {
  8632. mg_snprintf(NULL,
  8633. NULL, /* All calls to construct_etag use 64 byte buffer */
  8634. buf,
  8635. buf_len,
  8636. "\"%lx.%" INT64_FMT "\"",
  8637. (unsigned long)filestat->last_modified,
  8638. filestat->size);
  8639. }
  8640. }
  8641. static void
  8642. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8643. {
  8644. if (filep != NULL && filep->fp != NULL) {
  8645. #if defined(_WIN32)
  8646. (void)conn; /* Unused. */
  8647. #else
  8648. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8649. mg_cry_internal(conn,
  8650. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8651. __func__,
  8652. strerror(ERRNO));
  8653. }
  8654. #endif
  8655. }
  8656. }
  8657. #if defined(USE_ZLIB)
  8658. #include "mod_zlib.inl"
  8659. #endif
  8660. #if !defined(NO_FILESYSTEMS)
  8661. static void
  8662. handle_static_file_request(struct mg_connection *conn,
  8663. const char *path,
  8664. struct mg_file *filep,
  8665. const char *mime_type,
  8666. const char *additional_headers)
  8667. {
  8668. char lm[64], etag[64];
  8669. char range[128]; /* large enough, so there will be no overflow */
  8670. const char *range_hdr;
  8671. int64_t cl, r1, r2;
  8672. struct vec mime_vec;
  8673. int n, truncated;
  8674. char gz_path[UTF8_PATH_MAX];
  8675. const char *encoding = 0;
  8676. int is_head_request;
  8677. #if defined(USE_ZLIB)
  8678. /* Compression is allowed, unless there is a reason not to use
  8679. * compression. If the file is already compressed, too small or a
  8680. * "range" request was made, on the fly compression is not possible. */
  8681. int allow_on_the_fly_compression = 1;
  8682. #endif
  8683. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8684. return;
  8685. }
  8686. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8687. if (mime_type == NULL) {
  8688. get_mime_type(conn, path, &mime_vec);
  8689. } else {
  8690. mime_vec.ptr = mime_type;
  8691. mime_vec.len = strlen(mime_type);
  8692. }
  8693. if (filep->stat.size > INT64_MAX) {
  8694. mg_send_http_error(conn,
  8695. 500,
  8696. "Error: File size is too large to send\n%" INT64_FMT,
  8697. filep->stat.size);
  8698. return;
  8699. }
  8700. cl = (int64_t)filep->stat.size;
  8701. conn->status_code = 200;
  8702. range[0] = '\0';
  8703. #if defined(USE_ZLIB)
  8704. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8705. * it's important to rewrite the filename after resolving
  8706. * the mime type from it, to preserve the actual file's type */
  8707. if (!conn->accept_gzip) {
  8708. allow_on_the_fly_compression = 0;
  8709. }
  8710. #endif
  8711. /* Check if there is a range header */
  8712. range_hdr = mg_get_header(conn, "Range");
  8713. /* For gzipped files, add *.gz */
  8714. if (filep->stat.is_gzipped) {
  8715. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8716. if (truncated) {
  8717. mg_send_http_error(conn,
  8718. 500,
  8719. "Error: Path of zipped file too long (%s)",
  8720. path);
  8721. return;
  8722. }
  8723. path = gz_path;
  8724. encoding = "gzip";
  8725. #if defined(USE_ZLIB)
  8726. /* File is already compressed. No "on the fly" compression. */
  8727. allow_on_the_fly_compression = 0;
  8728. #endif
  8729. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8730. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8731. struct mg_file_stat file_stat;
  8732. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8733. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8734. && !file_stat.is_directory) {
  8735. file_stat.is_gzipped = 1;
  8736. filep->stat = file_stat;
  8737. cl = (int64_t)filep->stat.size;
  8738. path = gz_path;
  8739. encoding = "gzip";
  8740. #if defined(USE_ZLIB)
  8741. /* File is already compressed. No "on the fly" compression. */
  8742. allow_on_the_fly_compression = 0;
  8743. #endif
  8744. }
  8745. }
  8746. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8747. mg_send_http_error(conn,
  8748. 500,
  8749. "Error: Cannot open file\nfopen(%s): %s",
  8750. path,
  8751. strerror(ERRNO));
  8752. return;
  8753. }
  8754. fclose_on_exec(&filep->access, conn);
  8755. /* If "Range" request was made: parse header, send only selected part
  8756. * of the file. */
  8757. r1 = r2 = 0;
  8758. if ((range_hdr != NULL)
  8759. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8760. && (r2 >= 0)) {
  8761. /* actually, range requests don't play well with a pre-gzipped
  8762. * file (since the range is specified in the uncompressed space) */
  8763. if (filep->stat.is_gzipped) {
  8764. mg_send_http_error(
  8765. conn,
  8766. 416, /* 416 = Range Not Satisfiable */
  8767. "%s",
  8768. "Error: Range requests in gzipped files are not supported");
  8769. (void)mg_fclose(
  8770. &filep->access); /* ignore error on read only file */
  8771. return;
  8772. }
  8773. conn->status_code = 206;
  8774. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8775. mg_snprintf(conn,
  8776. NULL, /* range buffer is big enough */
  8777. range,
  8778. sizeof(range),
  8779. "bytes "
  8780. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8781. r1,
  8782. r1 + cl - 1,
  8783. filep->stat.size);
  8784. #if defined(USE_ZLIB)
  8785. /* Do not compress ranges. */
  8786. allow_on_the_fly_compression = 0;
  8787. #endif
  8788. }
  8789. /* Do not compress small files. Small files do not benefit from file
  8790. * compression, but there is still some overhead. */
  8791. #if defined(USE_ZLIB)
  8792. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8793. /* File is below the size limit. */
  8794. allow_on_the_fly_compression = 0;
  8795. }
  8796. #endif
  8797. /* Prepare Etag, and Last-Modified headers. */
  8798. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8799. construct_etag(etag, sizeof(etag), &filep->stat);
  8800. /* Create 2xx (200, 206) response */
  8801. mg_response_header_start(conn, conn->status_code);
  8802. send_static_cache_header(conn);
  8803. send_additional_header(conn);
  8804. send_cors_header(conn);
  8805. mg_response_header_add(conn,
  8806. "Content-Type",
  8807. mime_vec.ptr,
  8808. (int)mime_vec.len);
  8809. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8810. mg_response_header_add(conn, "Etag", etag, -1);
  8811. #if defined(USE_ZLIB)
  8812. /* On the fly compression allowed */
  8813. if (allow_on_the_fly_compression) {
  8814. /* For on the fly compression, we don't know the content size in
  8815. * advance, so we have to use chunked encoding */
  8816. encoding = "gzip";
  8817. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8818. /* HTTP/2 is always using "chunks" (frames) */
  8819. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8820. }
  8821. } else
  8822. #endif
  8823. {
  8824. /* Without on-the-fly compression, we know the content-length
  8825. * and we can use ranges (with on-the-fly compression we cannot).
  8826. * So we send these response headers only in this case. */
  8827. char len[32];
  8828. int trunc = 0;
  8829. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8830. if (!trunc) {
  8831. mg_response_header_add(conn, "Content-Length", len, -1);
  8832. }
  8833. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8834. }
  8835. if (encoding) {
  8836. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8837. }
  8838. if (range[0] != 0) {
  8839. mg_response_header_add(conn, "Content-Range", range, -1);
  8840. }
  8841. /* The code above does not add any header starting with X- to make
  8842. * sure no one of the additional_headers is included twice */
  8843. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8844. mg_response_header_add_lines(conn, additional_headers);
  8845. }
  8846. /* Send all headers */
  8847. mg_response_header_send(conn);
  8848. if (!is_head_request) {
  8849. #if defined(USE_ZLIB)
  8850. if (allow_on_the_fly_compression) {
  8851. /* Compress and send */
  8852. send_compressed_data(conn, filep);
  8853. } else
  8854. #endif
  8855. {
  8856. /* Send file directly */
  8857. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8858. }
  8859. }
  8860. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8861. }
  8862. int
  8863. mg_send_file_body(struct mg_connection *conn, const char *path)
  8864. {
  8865. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8866. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8867. return -1;
  8868. }
  8869. fclose_on_exec(&file.access, conn);
  8870. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8871. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8872. return 0; /* >= 0 for OK */
  8873. }
  8874. #endif /* NO_FILESYSTEMS */
  8875. #if !defined(NO_CACHING)
  8876. /* Return True if we should reply 304 Not Modified. */
  8877. static int
  8878. is_not_modified(const struct mg_connection *conn,
  8879. const struct mg_file_stat *filestat)
  8880. {
  8881. char etag[64];
  8882. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8883. const char *inm = mg_get_header(conn, "If-None-Match");
  8884. construct_etag(etag, sizeof(etag), filestat);
  8885. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8886. || ((ims != NULL)
  8887. && (filestat->last_modified <= parse_date_string(ims)));
  8888. }
  8889. static void
  8890. handle_not_modified_static_file_request(struct mg_connection *conn,
  8891. struct mg_file *filep)
  8892. {
  8893. char lm[64], etag[64];
  8894. if ((conn == NULL) || (filep == NULL)) {
  8895. return;
  8896. }
  8897. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8898. construct_etag(etag, sizeof(etag), &filep->stat);
  8899. /* Create 304 "not modified" response */
  8900. mg_response_header_start(conn, 304);
  8901. send_static_cache_header(conn);
  8902. send_additional_header(conn);
  8903. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8904. mg_response_header_add(conn, "Etag", etag, -1);
  8905. /* Send all headers */
  8906. mg_response_header_send(conn);
  8907. }
  8908. #endif
  8909. #if !defined(NO_FILESYSTEMS)
  8910. void
  8911. mg_send_file(struct mg_connection *conn, const char *path)
  8912. {
  8913. mg_send_mime_file2(conn, path, NULL, NULL);
  8914. }
  8915. void
  8916. mg_send_mime_file(struct mg_connection *conn,
  8917. const char *path,
  8918. const char *mime_type)
  8919. {
  8920. mg_send_mime_file2(conn, path, mime_type, NULL);
  8921. }
  8922. void
  8923. mg_send_mime_file2(struct mg_connection *conn,
  8924. const char *path,
  8925. const char *mime_type,
  8926. const char *additional_headers)
  8927. {
  8928. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8929. if (!conn) {
  8930. /* No conn */
  8931. return;
  8932. }
  8933. if (mg_stat(conn, path, &file.stat)) {
  8934. #if !defined(NO_CACHING)
  8935. if (is_not_modified(conn, &file.stat)) {
  8936. /* Send 304 "Not Modified" - this must not send any body data */
  8937. handle_not_modified_static_file_request(conn, &file);
  8938. } else
  8939. #endif /* NO_CACHING */
  8940. if (file.stat.is_directory) {
  8941. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8942. "yes")) {
  8943. handle_directory_request(conn, path);
  8944. } else {
  8945. mg_send_http_error(conn,
  8946. 403,
  8947. "%s",
  8948. "Error: Directory listing denied");
  8949. }
  8950. } else {
  8951. handle_static_file_request(
  8952. conn, path, &file, mime_type, additional_headers);
  8953. }
  8954. } else {
  8955. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8956. }
  8957. }
  8958. /* For a given PUT path, create all intermediate subdirectories.
  8959. * Return 0 if the path itself is a directory.
  8960. * Return 1 if the path leads to a file.
  8961. * Return -1 for if the path is too long.
  8962. * Return -2 if path can not be created.
  8963. */
  8964. static int
  8965. put_dir(struct mg_connection *conn, const char *path)
  8966. {
  8967. char buf[UTF8_PATH_MAX];
  8968. const char *s, *p;
  8969. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8970. size_t len;
  8971. int res = 1;
  8972. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8973. len = (size_t)(p - path);
  8974. if (len >= sizeof(buf)) {
  8975. /* path too long */
  8976. res = -1;
  8977. break;
  8978. }
  8979. memcpy(buf, path, len);
  8980. buf[len] = '\0';
  8981. /* Try to create intermediate directory */
  8982. DEBUG_TRACE("mkdir(%s)", buf);
  8983. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8984. /* path does not exixt and can not be created */
  8985. res = -2;
  8986. break;
  8987. }
  8988. /* Is path itself a directory? */
  8989. if (p[1] == '\0') {
  8990. res = 0;
  8991. }
  8992. }
  8993. return res;
  8994. }
  8995. static void
  8996. remove_bad_file(const struct mg_connection *conn, const char *path)
  8997. {
  8998. int r = mg_remove(conn, path);
  8999. if (r != 0) {
  9000. mg_cry_internal(conn,
  9001. "%s: Cannot remove invalid file %s",
  9002. __func__,
  9003. path);
  9004. }
  9005. }
  9006. long long
  9007. mg_store_body(struct mg_connection *conn, const char *path)
  9008. {
  9009. char buf[MG_BUF_LEN];
  9010. long long len = 0;
  9011. int ret, n;
  9012. struct mg_file fi;
  9013. if (conn->consumed_content != 0) {
  9014. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9015. return -11;
  9016. }
  9017. ret = put_dir(conn, path);
  9018. if (ret < 0) {
  9019. /* -1 for path too long,
  9020. * -2 for path can not be created. */
  9021. return ret;
  9022. }
  9023. if (ret != 1) {
  9024. /* Return 0 means, path itself is a directory. */
  9025. return 0;
  9026. }
  9027. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9028. return -12;
  9029. }
  9030. ret = mg_read(conn, buf, sizeof(buf));
  9031. while (ret > 0) {
  9032. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9033. if (n != ret) {
  9034. (void)mg_fclose(
  9035. &fi.access); /* File is bad and will be removed anyway. */
  9036. remove_bad_file(conn, path);
  9037. return -13;
  9038. }
  9039. len += ret;
  9040. ret = mg_read(conn, buf, sizeof(buf));
  9041. }
  9042. /* File is open for writing. If fclose fails, there was probably an
  9043. * error flushing the buffer to disk, so the file on disk might be
  9044. * broken. Delete it and return an error to the caller. */
  9045. if (mg_fclose(&fi.access) != 0) {
  9046. remove_bad_file(conn, path);
  9047. return -14;
  9048. }
  9049. return len;
  9050. }
  9051. #endif /* NO_FILESYSTEMS */
  9052. /* Parse a buffer:
  9053. * Forward the string pointer till the end of a word, then
  9054. * terminate it and forward till the begin of the next word.
  9055. */
  9056. static int
  9057. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9058. {
  9059. /* Forward until a space is found - use isgraph here */
  9060. /* See http://www.cplusplus.com/reference/cctype/ */
  9061. while (isgraph((unsigned char)**ppw)) {
  9062. (*ppw)++;
  9063. }
  9064. /* Check end of word */
  9065. if (eol) {
  9066. /* must be a end of line */
  9067. if ((**ppw != '\r') && (**ppw != '\n')) {
  9068. return -1;
  9069. }
  9070. } else {
  9071. /* must be a end of a word, but not a line */
  9072. if (**ppw != ' ') {
  9073. return -1;
  9074. }
  9075. }
  9076. /* Terminate and forward to the next word */
  9077. do {
  9078. **ppw = 0;
  9079. (*ppw)++;
  9080. } while (isspace((unsigned char)**ppw));
  9081. /* Check after term */
  9082. if (!eol) {
  9083. /* if it's not the end of line, there must be a next word */
  9084. if (!isgraph((unsigned char)**ppw)) {
  9085. return -1;
  9086. }
  9087. }
  9088. /* ok */
  9089. return 1;
  9090. }
  9091. /* Parse HTTP headers from the given buffer, advance buf pointer
  9092. * to the point where parsing stopped.
  9093. * All parameters must be valid pointers (not NULL).
  9094. * Return <0 on error. */
  9095. static int
  9096. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9097. {
  9098. int i;
  9099. int num_headers = 0;
  9100. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9101. char *dp = *buf;
  9102. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9103. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9104. dp++;
  9105. }
  9106. if (dp == *buf) {
  9107. /* End of headers reached. */
  9108. break;
  9109. }
  9110. /* Drop all spaces after header name before : */
  9111. while (*dp == ' ') {
  9112. *dp = 0;
  9113. dp++;
  9114. }
  9115. if (*dp != ':') {
  9116. /* This is not a valid field. */
  9117. return -1;
  9118. }
  9119. /* End of header key (*dp == ':') */
  9120. /* Truncate here and set the key name */
  9121. *dp = 0;
  9122. hdr[i].name = *buf;
  9123. /* Skip all spaces */
  9124. do {
  9125. dp++;
  9126. } while ((*dp == ' ') || (*dp == '\t'));
  9127. /* The rest of the line is the value */
  9128. hdr[i].value = dp;
  9129. /* Find end of line */
  9130. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9131. dp++;
  9132. };
  9133. /* eliminate \r */
  9134. if (*dp == '\r') {
  9135. *dp = 0;
  9136. dp++;
  9137. if (*dp != '\n') {
  9138. /* This is not a valid line. */
  9139. return -1;
  9140. }
  9141. }
  9142. /* here *dp is either 0 or '\n' */
  9143. /* in any case, we have a new header */
  9144. num_headers = i + 1;
  9145. if (*dp) {
  9146. *dp = 0;
  9147. dp++;
  9148. *buf = dp;
  9149. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9150. /* This is the end of the header */
  9151. break;
  9152. }
  9153. } else {
  9154. *buf = dp;
  9155. break;
  9156. }
  9157. }
  9158. return num_headers;
  9159. }
  9160. struct mg_http_method_info {
  9161. const char *name;
  9162. int request_has_body;
  9163. int response_has_body;
  9164. int is_safe;
  9165. int is_idempotent;
  9166. int is_cacheable;
  9167. };
  9168. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9169. static const struct mg_http_method_info http_methods[] = {
  9170. /* HTTP (RFC 2616) */
  9171. {"GET", 0, 1, 1, 1, 1},
  9172. {"POST", 1, 1, 0, 0, 0},
  9173. {"PUT", 1, 0, 0, 1, 0},
  9174. {"DELETE", 0, 0, 0, 1, 0},
  9175. {"HEAD", 0, 0, 1, 1, 1},
  9176. {"OPTIONS", 0, 0, 1, 1, 0},
  9177. {"CONNECT", 1, 1, 0, 0, 0},
  9178. /* TRACE method (RFC 2616) is not supported for security reasons */
  9179. /* PATCH method (RFC 5789) */
  9180. {"PATCH", 1, 0, 0, 0, 0},
  9181. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9182. /* WEBDAV (RFC 2518) */
  9183. {"PROPFIND", 0, 1, 1, 1, 0},
  9184. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9185. * Some PROPFIND results MAY be cached, with care,
  9186. * as there is no cache validation mechanism for
  9187. * most properties. This method is both safe and
  9188. * idempotent (see Section 9.1 of [RFC2616]). */
  9189. {"MKCOL", 0, 0, 0, 1, 0},
  9190. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9191. * When MKCOL is invoked without a request body,
  9192. * the newly created collection SHOULD have no
  9193. * members. A MKCOL request message may contain
  9194. * a message body. The precise behavior of a MKCOL
  9195. * request when the body is present is undefined,
  9196. * ... ==> We do not support MKCOL with body data.
  9197. * This method is idempotent, but not safe (see
  9198. * Section 9.1 of [RFC2616]). Responses to this
  9199. * method MUST NOT be cached. */
  9200. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9201. {"LOCK", 1, 1, 0, 0, 0},
  9202. {"UNLOCK", 1, 0, 0, 0, 0},
  9203. {"PROPPATCH", 1, 1, 0, 0, 0},
  9204. {"COPY", 1, 0, 0, 0, 0},
  9205. {"MOVE", 1, 1, 0, 0, 0},
  9206. /* Unsupported WEBDAV Methods: */
  9207. /* + 11 methods from RFC 3253 */
  9208. /* ORDERPATCH (RFC 3648) */
  9209. /* ACL (RFC 3744) */
  9210. /* SEARCH (RFC 5323) */
  9211. /* + MicroSoft extensions
  9212. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9213. /* REPORT method (RFC 3253) */
  9214. {"REPORT", 1, 1, 1, 1, 1},
  9215. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9216. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9217. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9218. * to be useful for REST in case a "GET request with body" is
  9219. * required. */
  9220. {NULL, 0, 0, 0, 0, 0}
  9221. /* end of list */
  9222. };
  9223. /* All method names */
  9224. static char *all_methods = NULL; /* Built by mg_init_library */
  9225. static const struct mg_http_method_info *
  9226. get_http_method_info(const char *method)
  9227. {
  9228. /* Check if the method is known to the server. The list of all known
  9229. * HTTP methods can be found here at
  9230. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9231. */
  9232. const struct mg_http_method_info *m = http_methods;
  9233. while (m->name) {
  9234. if (!strcmp(m->name, method)) {
  9235. return m;
  9236. }
  9237. m++;
  9238. }
  9239. return NULL;
  9240. }
  9241. static int
  9242. is_valid_http_method(const char *method)
  9243. {
  9244. return (get_http_method_info(method) != NULL);
  9245. }
  9246. /* Parse HTTP request, fill in mg_request_info structure.
  9247. * This function modifies the buffer by NUL-terminating
  9248. * HTTP request components, header names and header values.
  9249. * Parameters:
  9250. * buf (in/out): pointer to the HTTP header to parse and split
  9251. * len (in): length of HTTP header buffer
  9252. * re (out): parsed header as mg_request_info
  9253. * buf and ri must be valid pointers (not NULL), len>0.
  9254. * Returns <0 on error. */
  9255. static int
  9256. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9257. {
  9258. int request_length;
  9259. int init_skip = 0;
  9260. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9261. * remote_port */
  9262. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9263. NULL;
  9264. ri->num_headers = 0;
  9265. /* RFC says that all initial whitespaces should be ignored */
  9266. /* This included all leading \r and \n (isspace) */
  9267. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9268. while ((len > 0) && isspace((unsigned char)*buf)) {
  9269. buf++;
  9270. len--;
  9271. init_skip++;
  9272. }
  9273. if (len == 0) {
  9274. /* Incomplete request */
  9275. return 0;
  9276. }
  9277. /* Control characters are not allowed, including zero */
  9278. if (iscntrl((unsigned char)*buf)) {
  9279. return -1;
  9280. }
  9281. /* Find end of HTTP header */
  9282. request_length = get_http_header_len(buf, len);
  9283. if (request_length <= 0) {
  9284. return request_length;
  9285. }
  9286. buf[request_length - 1] = '\0';
  9287. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9288. return -1;
  9289. }
  9290. /* The first word has to be the HTTP method */
  9291. ri->request_method = buf;
  9292. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9293. return -1;
  9294. }
  9295. /* The second word is the URI */
  9296. ri->request_uri = buf;
  9297. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9298. return -1;
  9299. }
  9300. /* Next would be the HTTP version */
  9301. ri->http_version = buf;
  9302. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9303. return -1;
  9304. }
  9305. /* Check for a valid HTTP version key */
  9306. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9307. /* Invalid request */
  9308. return -1;
  9309. }
  9310. ri->http_version += 5;
  9311. /* Check for a valid http method */
  9312. if (!is_valid_http_method(ri->request_method)) {
  9313. return -1;
  9314. }
  9315. /* Parse all HTTP headers */
  9316. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9317. if (ri->num_headers < 0) {
  9318. /* Error while parsing headers */
  9319. return -1;
  9320. }
  9321. return request_length + init_skip;
  9322. }
  9323. static int
  9324. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9325. {
  9326. int response_length;
  9327. int init_skip = 0;
  9328. char *tmp, *tmp2;
  9329. long l;
  9330. /* Initialize elements. */
  9331. ri->http_version = ri->status_text = NULL;
  9332. ri->num_headers = ri->status_code = 0;
  9333. /* RFC says that all initial whitespaces should be ingored */
  9334. /* This included all leading \r and \n (isspace) */
  9335. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9336. while ((len > 0) && isspace((unsigned char)*buf)) {
  9337. buf++;
  9338. len--;
  9339. init_skip++;
  9340. }
  9341. if (len == 0) {
  9342. /* Incomplete request */
  9343. return 0;
  9344. }
  9345. /* Control characters are not allowed, including zero */
  9346. if (iscntrl((unsigned char)*buf)) {
  9347. return -1;
  9348. }
  9349. /* Find end of HTTP header */
  9350. response_length = get_http_header_len(buf, len);
  9351. if (response_length <= 0) {
  9352. return response_length;
  9353. }
  9354. buf[response_length - 1] = '\0';
  9355. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9356. return -1;
  9357. }
  9358. /* The first word is the HTTP version */
  9359. /* Check for a valid HTTP version key */
  9360. if (strncmp(buf, "HTTP/", 5) != 0) {
  9361. /* Invalid request */
  9362. return -1;
  9363. }
  9364. buf += 5;
  9365. if (!isgraph((unsigned char)buf[0])) {
  9366. /* Invalid request */
  9367. return -1;
  9368. }
  9369. ri->http_version = buf;
  9370. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9371. return -1;
  9372. }
  9373. /* The second word is the status as a number */
  9374. tmp = buf;
  9375. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9376. return -1;
  9377. }
  9378. l = strtol(tmp, &tmp2, 10);
  9379. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9380. /* Everything else but a 3 digit code is invalid */
  9381. return -1;
  9382. }
  9383. ri->status_code = (int)l;
  9384. /* The rest of the line is the status text */
  9385. ri->status_text = buf;
  9386. /* Find end of status text */
  9387. /* isgraph or isspace = isprint */
  9388. while (isprint((unsigned char)*buf)) {
  9389. buf++;
  9390. }
  9391. if ((*buf != '\r') && (*buf != '\n')) {
  9392. return -1;
  9393. }
  9394. /* Terminate string and forward buf to next line */
  9395. do {
  9396. *buf = 0;
  9397. buf++;
  9398. } while (isspace((unsigned char)*buf));
  9399. /* Parse all HTTP headers */
  9400. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9401. if (ri->num_headers < 0) {
  9402. /* Error while parsing headers */
  9403. return -1;
  9404. }
  9405. return response_length + init_skip;
  9406. }
  9407. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9408. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9409. * buffer (which marks the end of HTTP request). Buffer buf may already
  9410. * have some data. The length of the data is stored in nread.
  9411. * Upon every read operation, increase nread by the number of bytes read. */
  9412. static int
  9413. read_message(FILE *fp,
  9414. struct mg_connection *conn,
  9415. char *buf,
  9416. int bufsiz,
  9417. int *nread)
  9418. {
  9419. int request_len, n = 0;
  9420. struct timespec last_action_time;
  9421. double request_timeout;
  9422. if (!conn) {
  9423. return 0;
  9424. }
  9425. memset(&last_action_time, 0, sizeof(last_action_time));
  9426. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9427. /* value of request_timeout is in seconds, config in milliseconds */
  9428. request_timeout =
  9429. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9430. } else {
  9431. request_timeout =
  9432. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9433. / 1000.0;
  9434. }
  9435. if (conn->handled_requests > 0) {
  9436. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9437. request_timeout =
  9438. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9439. / 1000.0;
  9440. }
  9441. }
  9442. request_len = get_http_header_len(buf, *nread);
  9443. while (request_len == 0) {
  9444. /* Full request not yet received */
  9445. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9446. /* Server is to be stopped. */
  9447. return -1;
  9448. }
  9449. if (*nread >= bufsiz) {
  9450. /* Request too long */
  9451. return -2;
  9452. }
  9453. n = pull_inner(
  9454. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9455. if (n == -2) {
  9456. /* Receive error */
  9457. return -1;
  9458. }
  9459. /* update clock after every read request */
  9460. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9461. if (n > 0) {
  9462. *nread += n;
  9463. request_len = get_http_header_len(buf, *nread);
  9464. }
  9465. if ((request_len == 0) && (request_timeout >= 0)) {
  9466. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9467. > request_timeout) {
  9468. /* Timeout */
  9469. return -1;
  9470. }
  9471. }
  9472. }
  9473. return request_len;
  9474. }
  9475. #if !defined(NO_CGI) || !defined(NO_FILES)
  9476. static int
  9477. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9478. {
  9479. const char *expect;
  9480. char buf[MG_BUF_LEN];
  9481. int success = 0;
  9482. if (!conn) {
  9483. return 0;
  9484. }
  9485. expect = mg_get_header(conn, "Expect");
  9486. DEBUG_ASSERT(fp != NULL);
  9487. if (!fp) {
  9488. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9489. return 0;
  9490. }
  9491. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9492. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9493. */
  9494. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9495. } else {
  9496. if (expect != NULL) {
  9497. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9498. conn->status_code = 100;
  9499. } else {
  9500. conn->status_code = 200;
  9501. }
  9502. DEBUG_ASSERT(conn->consumed_content == 0);
  9503. if (conn->consumed_content != 0) {
  9504. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9505. return 0;
  9506. }
  9507. for (;;) {
  9508. int nread = mg_read(conn, buf, sizeof(buf));
  9509. if (nread <= 0) {
  9510. success = (nread == 0);
  9511. break;
  9512. }
  9513. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9514. break;
  9515. }
  9516. }
  9517. /* Each error code path in this function must send an error */
  9518. if (!success) {
  9519. /* NOTE: Maybe some data has already been sent. */
  9520. /* TODO (low): If some data has been sent, a correct error
  9521. * reply can no longer be sent, so just close the connection */
  9522. mg_send_http_error(conn, 500, "%s", "");
  9523. }
  9524. }
  9525. return success;
  9526. }
  9527. #endif
  9528. #if defined(USE_TIMERS)
  9529. #define TIMER_API static
  9530. #include "timer.inl"
  9531. #endif /* USE_TIMERS */
  9532. #if !defined(NO_CGI)
  9533. /* This structure helps to create an environment for the spawned CGI
  9534. * program.
  9535. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9536. * last element must be NULL.
  9537. * However, on Windows there is a requirement that all these
  9538. * VARIABLE=VALUE\0
  9539. * strings must reside in a contiguous buffer. The end of the buffer is
  9540. * marked by two '\0' characters.
  9541. * We satisfy both worlds: we create an envp array (which is vars), all
  9542. * entries are actually pointers inside buf. */
  9543. struct cgi_environment {
  9544. struct mg_connection *conn;
  9545. /* Data block */
  9546. char *buf; /* Environment buffer */
  9547. size_t buflen; /* Space available in buf */
  9548. size_t bufused; /* Space taken in buf */
  9549. /* Index block */
  9550. char **var; /* char **envp */
  9551. size_t varlen; /* Number of variables available in var */
  9552. size_t varused; /* Number of variables stored in var */
  9553. };
  9554. static void addenv(struct cgi_environment *env,
  9555. PRINTF_FORMAT_STRING(const char *fmt),
  9556. ...) PRINTF_ARGS(2, 3);
  9557. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9558. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9559. static void
  9560. addenv(struct cgi_environment *env, const char *fmt, ...)
  9561. {
  9562. size_t i, n, space;
  9563. int truncated = 0;
  9564. char *added;
  9565. va_list ap;
  9566. if ((env->varlen - env->varused) < 2) {
  9567. mg_cry_internal(env->conn,
  9568. "%s: Cannot register CGI variable [%s]",
  9569. __func__,
  9570. fmt);
  9571. return;
  9572. }
  9573. /* Calculate how much space is left in the buffer */
  9574. space = (env->buflen - env->bufused);
  9575. do {
  9576. /* Space for "\0\0" is always needed. */
  9577. if (space <= 2) {
  9578. /* Allocate new buffer */
  9579. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9580. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9581. if (!added) {
  9582. /* Out of memory */
  9583. mg_cry_internal(
  9584. env->conn,
  9585. "%s: Cannot allocate memory for CGI variable [%s]",
  9586. __func__,
  9587. fmt);
  9588. return;
  9589. }
  9590. /* Retarget pointers */
  9591. env->buf = added;
  9592. env->buflen = n;
  9593. for (i = 0, n = 0; i < env->varused; i++) {
  9594. env->var[i] = added + n;
  9595. n += strlen(added + n) + 1;
  9596. }
  9597. space = (env->buflen - env->bufused);
  9598. }
  9599. /* Make a pointer to the free space int the buffer */
  9600. added = env->buf + env->bufused;
  9601. /* Copy VARIABLE=VALUE\0 string into the free space */
  9602. va_start(ap, fmt);
  9603. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9604. va_end(ap);
  9605. /* Do not add truncated strings to the environment */
  9606. if (truncated) {
  9607. /* Reallocate the buffer */
  9608. space = 0;
  9609. }
  9610. } while (truncated);
  9611. /* Calculate number of bytes added to the environment */
  9612. n = strlen(added) + 1;
  9613. env->bufused += n;
  9614. /* Append a pointer to the added string into the envp array */
  9615. env->var[env->varused] = added;
  9616. env->varused++;
  9617. }
  9618. /* Return 0 on success, non-zero if an error occurs. */
  9619. static int
  9620. prepare_cgi_environment(struct mg_connection *conn,
  9621. const char *prog,
  9622. struct cgi_environment *env,
  9623. unsigned char cgi_config_idx)
  9624. {
  9625. const char *s;
  9626. struct vec var_vec;
  9627. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9628. int i, truncated, uri_len;
  9629. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9630. return -1;
  9631. }
  9632. env->conn = conn;
  9633. env->buflen = CGI_ENVIRONMENT_SIZE;
  9634. env->bufused = 0;
  9635. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9636. if (env->buf == NULL) {
  9637. mg_cry_internal(conn,
  9638. "%s: Not enough memory for environmental buffer",
  9639. __func__);
  9640. return -1;
  9641. }
  9642. env->varlen = MAX_CGI_ENVIR_VARS;
  9643. env->varused = 0;
  9644. env->var =
  9645. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9646. if (env->var == NULL) {
  9647. mg_cry_internal(conn,
  9648. "%s: Not enough memory for environmental variables",
  9649. __func__);
  9650. mg_free(env->buf);
  9651. return -1;
  9652. }
  9653. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9654. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9655. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9656. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9657. /* Prepare the environment block */
  9658. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9659. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9660. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9661. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9662. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9663. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9664. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9665. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9666. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9667. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9668. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9669. /* SCRIPT_NAME */
  9670. uri_len = (int)strlen(conn->request_info.local_uri);
  9671. if (conn->path_info == NULL) {
  9672. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9673. /* URI: /path_to_script/script.cgi */
  9674. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9675. } else {
  9676. /* URI: /path_to_script/ ... using index.cgi */
  9677. const char *index_file = strrchr(prog, '/');
  9678. if (index_file) {
  9679. addenv(env,
  9680. "SCRIPT_NAME=%s%s",
  9681. conn->request_info.local_uri,
  9682. index_file + 1);
  9683. }
  9684. }
  9685. } else {
  9686. /* URI: /path_to_script/script.cgi/path_info */
  9687. addenv(env,
  9688. "SCRIPT_NAME=%.*s",
  9689. uri_len - (int)strlen(conn->path_info),
  9690. conn->request_info.local_uri);
  9691. }
  9692. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9693. if (conn->path_info == NULL) {
  9694. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9695. } else {
  9696. addenv(env,
  9697. "PATH_TRANSLATED=%s%s",
  9698. conn->dom_ctx->config[DOCUMENT_ROOT],
  9699. conn->path_info);
  9700. }
  9701. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9702. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9703. addenv(env, "CONTENT_TYPE=%s", s);
  9704. }
  9705. if (conn->request_info.query_string != NULL) {
  9706. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9707. }
  9708. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9709. addenv(env, "CONTENT_LENGTH=%s", s);
  9710. }
  9711. if ((s = getenv("PATH")) != NULL) {
  9712. addenv(env, "PATH=%s", s);
  9713. }
  9714. if (conn->path_info != NULL) {
  9715. addenv(env, "PATH_INFO=%s", conn->path_info);
  9716. }
  9717. if (conn->status_code > 0) {
  9718. /* CGI error handler should show the status code */
  9719. addenv(env, "STATUS=%d", conn->status_code);
  9720. }
  9721. #if defined(_WIN32)
  9722. if ((s = getenv("COMSPEC")) != NULL) {
  9723. addenv(env, "COMSPEC=%s", s);
  9724. }
  9725. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9726. addenv(env, "SYSTEMROOT=%s", s);
  9727. }
  9728. if ((s = getenv("SystemDrive")) != NULL) {
  9729. addenv(env, "SystemDrive=%s", s);
  9730. }
  9731. if ((s = getenv("ProgramFiles")) != NULL) {
  9732. addenv(env, "ProgramFiles=%s", s);
  9733. }
  9734. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9735. addenv(env, "ProgramFiles(x86)=%s", s);
  9736. }
  9737. #else
  9738. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9739. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9740. }
  9741. #endif /* _WIN32 */
  9742. if ((s = getenv("PERLLIB")) != NULL) {
  9743. addenv(env, "PERLLIB=%s", s);
  9744. }
  9745. if (conn->request_info.remote_user != NULL) {
  9746. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9747. addenv(env, "%s", "AUTH_TYPE=Digest");
  9748. }
  9749. /* Add all headers as HTTP_* variables */
  9750. for (i = 0; i < conn->request_info.num_headers; i++) {
  9751. (void)mg_snprintf(conn,
  9752. &truncated,
  9753. http_var_name,
  9754. sizeof(http_var_name),
  9755. "HTTP_%s",
  9756. conn->request_info.http_headers[i].name);
  9757. if (truncated) {
  9758. mg_cry_internal(conn,
  9759. "%s: HTTP header variable too long [%s]",
  9760. __func__,
  9761. conn->request_info.http_headers[i].name);
  9762. continue;
  9763. }
  9764. /* Convert variable name into uppercase, and change - to _ */
  9765. for (p = http_var_name; *p != '\0'; p++) {
  9766. if (*p == '-') {
  9767. *p = '_';
  9768. }
  9769. *p = (char)toupper((unsigned char)*p);
  9770. }
  9771. addenv(env,
  9772. "%s=%s",
  9773. http_var_name,
  9774. conn->request_info.http_headers[i].value);
  9775. }
  9776. /* Add user-specified variables */
  9777. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9778. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9779. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9780. }
  9781. env->var[env->varused] = NULL;
  9782. env->buf[env->bufused] = '\0';
  9783. return 0;
  9784. }
  9785. /* Data for CGI process control: PID and number of references */
  9786. struct process_control_data {
  9787. pid_t pid;
  9788. ptrdiff_t references;
  9789. };
  9790. static int
  9791. abort_cgi_process(void *data)
  9792. {
  9793. /* Waitpid checks for child status and won't work for a pid that does
  9794. * not identify a child of the current process. Thus, if the pid is
  9795. * reused, we will not affect a different process. */
  9796. struct process_control_data *proc = (struct process_control_data *)data;
  9797. int status = 0;
  9798. ptrdiff_t refs;
  9799. pid_t ret_pid;
  9800. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9801. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9802. /* Stop child process */
  9803. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9804. kill(proc->pid, SIGABRT);
  9805. /* Wait until process is terminated (don't leave zombies) */
  9806. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9807. ;
  9808. } else {
  9809. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9810. }
  9811. /* Dec reference counter */
  9812. refs = mg_atomic_dec(&proc->references);
  9813. if (refs == 0) {
  9814. /* no more references - free data */
  9815. mg_free(data);
  9816. }
  9817. return 0;
  9818. }
  9819. /* Local (static) function assumes all arguments are valid. */
  9820. static void
  9821. handle_cgi_request(struct mg_connection *conn,
  9822. const char *prog,
  9823. unsigned char cgi_config_idx)
  9824. {
  9825. char *buf;
  9826. size_t buflen;
  9827. int headers_len, data_len, i, truncated;
  9828. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9829. const char *status, *status_text, *connection_state;
  9830. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9831. struct mg_request_info ri;
  9832. struct cgi_environment blk;
  9833. FILE *in = NULL, *out = NULL, *err = NULL;
  9834. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9835. pid_t pid = (pid_t)-1;
  9836. struct process_control_data *proc = NULL;
  9837. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9838. int no_buffering = 0;
  9839. #if defined(USE_TIMERS)
  9840. double cgi_timeout;
  9841. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9842. /* Get timeout in seconds */
  9843. cgi_timeout =
  9844. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9845. } else {
  9846. cgi_timeout =
  9847. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9848. }
  9849. #endif
  9850. if (cfg_buffering != NULL) {
  9851. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9852. no_buffering = 1;
  9853. }
  9854. }
  9855. buf = NULL;
  9856. buflen = conn->phys_ctx->max_request_size;
  9857. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9858. if (i != 0) {
  9859. blk.buf = NULL;
  9860. blk.var = NULL;
  9861. goto done;
  9862. }
  9863. /* CGI must be executed in its own directory. 'dir' must point to the
  9864. * directory containing executable program, 'p' must point to the
  9865. * executable program name relative to 'dir'. */
  9866. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9867. if (truncated) {
  9868. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9869. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9870. goto done;
  9871. }
  9872. if ((p = strrchr(dir, '/')) != NULL) {
  9873. *p++ = '\0';
  9874. } else {
  9875. dir[0] = '.';
  9876. dir[1] = '\0';
  9877. p = (char *)prog;
  9878. }
  9879. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9880. status = strerror(ERRNO);
  9881. mg_cry_internal(
  9882. conn,
  9883. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9884. prog,
  9885. status);
  9886. mg_send_http_error(conn,
  9887. 500,
  9888. "Error: Cannot create CGI pipe: %s",
  9889. status);
  9890. goto done;
  9891. }
  9892. proc = (struct process_control_data *)
  9893. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9894. if (proc == NULL) {
  9895. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9896. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9897. goto done;
  9898. }
  9899. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9900. pid = spawn_process(
  9901. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9902. if (pid == (pid_t)-1) {
  9903. status = strerror(ERRNO);
  9904. mg_cry_internal(
  9905. conn,
  9906. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9907. prog,
  9908. status);
  9909. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9910. mg_free(proc);
  9911. proc = NULL;
  9912. goto done;
  9913. }
  9914. /* Store data in shared process_control_data */
  9915. proc->pid = pid;
  9916. proc->references = 1;
  9917. #if defined(USE_TIMERS)
  9918. if (cgi_timeout > 0.0) {
  9919. proc->references = 2;
  9920. // Start a timer for CGI
  9921. timer_add(conn->phys_ctx,
  9922. cgi_timeout /* in seconds */,
  9923. 0.0,
  9924. 1,
  9925. abort_cgi_process,
  9926. (void *)proc,
  9927. NULL);
  9928. }
  9929. #endif
  9930. /* Parent closes only one side of the pipes.
  9931. * If we don't mark them as closed, close() attempt before
  9932. * return from this function throws an exception on Windows.
  9933. * Windows does not like when closed descriptor is closed again. */
  9934. (void)close(fdin[0]);
  9935. (void)close(fdout[1]);
  9936. (void)close(fderr[1]);
  9937. fdin[0] = fdout[1] = fderr[1] = -1;
  9938. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9939. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9940. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9941. status = strerror(ERRNO);
  9942. mg_cry_internal(conn,
  9943. "Error: CGI program \"%s\": Can not open fd: %s",
  9944. prog,
  9945. status);
  9946. mg_send_http_error(conn,
  9947. 500,
  9948. "Error: CGI can not open fd\nfdopen: %s",
  9949. status);
  9950. goto done;
  9951. }
  9952. setbuf(in, NULL);
  9953. setbuf(out, NULL);
  9954. setbuf(err, NULL);
  9955. fout.access.fp = out;
  9956. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9957. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9958. conn->content_len);
  9959. /* This is a POST/PUT request, or another request with body data. */
  9960. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9961. /* Error sending the body data */
  9962. mg_cry_internal(
  9963. conn,
  9964. "Error: CGI program \"%s\": Forward body data failed",
  9965. prog);
  9966. goto done;
  9967. }
  9968. }
  9969. /* Close so child gets an EOF. */
  9970. fclose(in);
  9971. in = NULL;
  9972. fdin[1] = -1;
  9973. /* Now read CGI reply into a buffer. We need to set correct
  9974. * status code, thus we need to see all HTTP headers first.
  9975. * Do not send anything back to client, until we buffer in all
  9976. * HTTP headers. */
  9977. data_len = 0;
  9978. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9979. if (buf == NULL) {
  9980. mg_send_http_error(conn,
  9981. 500,
  9982. "Error: Not enough memory for CGI buffer (%u bytes)",
  9983. (unsigned int)buflen);
  9984. mg_cry_internal(
  9985. conn,
  9986. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9987. "bytes)",
  9988. prog,
  9989. (unsigned int)buflen);
  9990. goto done;
  9991. }
  9992. DEBUG_TRACE("CGI: %s", "wait for response");
  9993. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9994. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9995. if (headers_len <= 0) {
  9996. /* Could not parse the CGI response. Check if some error message on
  9997. * stderr. */
  9998. i = pull_all(err, conn, buf, (int)buflen);
  9999. if (i > 0) {
  10000. /* CGI program explicitly sent an error */
  10001. /* Write the error message to the internal log */
  10002. mg_cry_internal(conn,
  10003. "Error: CGI program \"%s\" sent error "
  10004. "message: [%.*s]",
  10005. prog,
  10006. i,
  10007. buf);
  10008. /* Don't send the error message back to the client */
  10009. mg_send_http_error(conn,
  10010. 500,
  10011. "Error: CGI program \"%s\" failed.",
  10012. prog);
  10013. } else {
  10014. /* CGI program did not explicitly send an error, but a broken
  10015. * respon header */
  10016. mg_cry_internal(conn,
  10017. "Error: CGI program sent malformed or too big "
  10018. "(>%u bytes) HTTP headers: [%.*s]",
  10019. (unsigned)buflen,
  10020. data_len,
  10021. buf);
  10022. mg_send_http_error(conn,
  10023. 500,
  10024. "Error: CGI program sent malformed or too big "
  10025. "(>%u bytes) HTTP headers: [%.*s]",
  10026. (unsigned)buflen,
  10027. data_len,
  10028. buf);
  10029. }
  10030. /* in both cases, abort processing CGI */
  10031. goto done;
  10032. }
  10033. pbuf = buf;
  10034. buf[headers_len - 1] = '\0';
  10035. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10036. /* Make up and send the status line */
  10037. status_text = "OK";
  10038. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10039. != NULL) {
  10040. conn->status_code = atoi(status);
  10041. status_text = status;
  10042. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10043. status_text++;
  10044. }
  10045. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10046. != NULL) {
  10047. conn->status_code = 307;
  10048. } else {
  10049. conn->status_code = 200;
  10050. }
  10051. connection_state =
  10052. get_header(ri.http_headers, ri.num_headers, "Connection");
  10053. if (!header_has_option(connection_state, "keep-alive")) {
  10054. conn->must_close = 1;
  10055. }
  10056. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10057. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10058. /* Send headers */
  10059. for (i = 0; i < ri.num_headers; i++) {
  10060. DEBUG_TRACE("CGI header: %s: %s",
  10061. ri.http_headers[i].name,
  10062. ri.http_headers[i].value);
  10063. mg_printf(conn,
  10064. "%s: %s\r\n",
  10065. ri.http_headers[i].name,
  10066. ri.http_headers[i].value);
  10067. }
  10068. mg_write(conn, "\r\n", 2);
  10069. /* Send chunk of data that may have been read after the headers */
  10070. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10071. /* Read the rest of CGI output and send to the client */
  10072. DEBUG_TRACE("CGI: %s", "forward all data");
  10073. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10074. DEBUG_TRACE("CGI: %s", "all data sent");
  10075. done:
  10076. mg_free(blk.var);
  10077. mg_free(blk.buf);
  10078. if (pid != (pid_t)-1) {
  10079. abort_cgi_process((void *)proc);
  10080. }
  10081. if (fdin[0] != -1) {
  10082. close(fdin[0]);
  10083. }
  10084. if (fdout[1] != -1) {
  10085. close(fdout[1]);
  10086. }
  10087. if (fderr[1] != -1) {
  10088. close(fderr[1]);
  10089. }
  10090. if (in != NULL) {
  10091. fclose(in);
  10092. } else if (fdin[1] != -1) {
  10093. close(fdin[1]);
  10094. }
  10095. if (out != NULL) {
  10096. fclose(out);
  10097. } else if (fdout[0] != -1) {
  10098. close(fdout[0]);
  10099. }
  10100. if (err != NULL) {
  10101. fclose(err);
  10102. } else if (fderr[0] != -1) {
  10103. close(fderr[0]);
  10104. }
  10105. mg_free(buf);
  10106. }
  10107. #endif /* !NO_CGI */
  10108. #if !defined(NO_FILES)
  10109. static void
  10110. dav_mkcol(struct mg_connection *conn, const char *path)
  10111. {
  10112. int rc, body_len;
  10113. struct de de;
  10114. if (conn == NULL) {
  10115. return;
  10116. }
  10117. /* TODO (mid): Check the mg_send_http_error situations in this function
  10118. */
  10119. memset(&de.file, 0, sizeof(de.file));
  10120. if (!mg_stat(conn, path, &de.file)) {
  10121. mg_cry_internal(conn,
  10122. "%s: mg_stat(%s) failed: %s",
  10123. __func__,
  10124. path,
  10125. strerror(ERRNO));
  10126. }
  10127. if (de.file.last_modified) {
  10128. /* TODO (mid): This check does not seem to make any sense ! */
  10129. /* TODO (mid): Add a webdav unit test first, before changing
  10130. * anything here. */
  10131. mg_send_http_error(
  10132. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10133. return;
  10134. }
  10135. body_len = conn->data_len - conn->request_len;
  10136. if (body_len > 0) {
  10137. mg_send_http_error(
  10138. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10139. return;
  10140. }
  10141. rc = mg_mkdir(conn, path, 0755);
  10142. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10143. if (rc == 0) {
  10144. /* Create 201 "Created" response */
  10145. mg_response_header_start(conn, 201);
  10146. send_static_cache_header(conn);
  10147. send_additional_header(conn);
  10148. mg_response_header_add(conn, "Content-Length", "0", -1);
  10149. /* Send all headers - there is no body */
  10150. mg_response_header_send(conn);
  10151. } else {
  10152. int http_status = 500;
  10153. switch (errno) {
  10154. case EEXIST:
  10155. http_status = 405;
  10156. break;
  10157. case EACCES:
  10158. http_status = 403;
  10159. break;
  10160. case ENOENT:
  10161. http_status = 409;
  10162. break;
  10163. }
  10164. mg_send_http_error(conn,
  10165. http_status,
  10166. "Error processing %s: %s",
  10167. path,
  10168. strerror(ERRNO));
  10169. }
  10170. }
  10171. /* Forward decrlaration */
  10172. static int get_uri_type(const char *uri);
  10173. static const char *
  10174. get_rel_url_at_current_server(const char *uri,
  10175. const struct mg_connection *conn);
  10176. static void
  10177. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10178. {
  10179. const char *overwrite_hdr;
  10180. const char *destination_hdr;
  10181. const char *root;
  10182. int rc, dest_uri_type;
  10183. int http_status = 400;
  10184. int do_overwrite = 0;
  10185. int destination_ok = 0;
  10186. char dest_path[UTF8_PATH_MAX];
  10187. struct mg_file_stat ignored;
  10188. if (conn == NULL) {
  10189. return;
  10190. }
  10191. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10192. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10193. destination_hdr = mg_get_header(conn, "Destination");
  10194. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10195. do_overwrite = 1;
  10196. }
  10197. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10198. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10199. return;
  10200. }
  10201. if (root != NULL) {
  10202. char *local_dest = NULL;
  10203. dest_uri_type = get_uri_type(destination_hdr);
  10204. if (dest_uri_type == 2) {
  10205. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10206. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10207. const char *h =
  10208. get_rel_url_at_current_server(destination_hdr, conn);
  10209. if (h) {
  10210. int len = (int)strlen(h);
  10211. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10212. mg_url_decode(h, len, local_dest, len + 1, 0);
  10213. }
  10214. }
  10215. if (local_dest != NULL) {
  10216. remove_dot_segments(local_dest);
  10217. if (local_dest[0] == '/') {
  10218. int trunc_check = 0;
  10219. mg_snprintf(conn,
  10220. &trunc_check,
  10221. dest_path,
  10222. sizeof(dest_path),
  10223. "%s/%s",
  10224. root,
  10225. local_dest);
  10226. if (trunc_check == 0) {
  10227. destination_ok = 1;
  10228. }
  10229. }
  10230. mg_free(local_dest);
  10231. }
  10232. }
  10233. if (!destination_ok) {
  10234. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10235. return;
  10236. }
  10237. /* Check now if this file exists */
  10238. if (mg_stat(conn, dest_path, &ignored)) {
  10239. /* File exists */
  10240. if (do_overwrite) {
  10241. /* Overwrite allowed: delete the file first */
  10242. if (0 != remove(dest_path)) {
  10243. /* No overwrite: return error */
  10244. mg_send_http_error(conn,
  10245. 403,
  10246. "Cannot overwrite file: %s",
  10247. dest_path);
  10248. return;
  10249. }
  10250. } else {
  10251. /* No overwrite: return error */
  10252. mg_send_http_error(conn,
  10253. 412,
  10254. "Destination already exists: %s",
  10255. dest_path);
  10256. return;
  10257. }
  10258. }
  10259. /* Copy / Move / Rename operation. */
  10260. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10261. #if defined(_WIN32)
  10262. {
  10263. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10264. wchar_t wSource[UTF16_PATH_MAX];
  10265. wchar_t wDest[UTF16_PATH_MAX];
  10266. BOOL ok;
  10267. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10268. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10269. if (do_copy) {
  10270. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10271. } else {
  10272. ok = MoveFileExW(wSource,
  10273. wDest,
  10274. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10275. }
  10276. if (ok) {
  10277. rc = 0;
  10278. } else {
  10279. DWORD lastErr = GetLastError();
  10280. if (lastErr == ERROR_ALREADY_EXISTS) {
  10281. mg_send_http_error(conn,
  10282. 412,
  10283. "Destination already exists: %s",
  10284. dest_path);
  10285. return;
  10286. }
  10287. rc = -1;
  10288. http_status = 400;
  10289. }
  10290. }
  10291. #else
  10292. {
  10293. /* Linux uses already UTF-8, we don't need to convert file names. */
  10294. if (do_copy) {
  10295. /* TODO: COPY for Linux. */
  10296. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10297. return;
  10298. }
  10299. rc = rename(path, dest_path);
  10300. if (rc) {
  10301. switch (errno) {
  10302. case EEXIST:
  10303. http_status = 412;
  10304. break;
  10305. case EACCES:
  10306. http_status = 403;
  10307. break;
  10308. case ENOENT:
  10309. http_status = 409;
  10310. break;
  10311. }
  10312. }
  10313. }
  10314. #endif
  10315. if (rc == 0) {
  10316. /* Create 204 "No Content" response */
  10317. mg_response_header_start(conn, 204);
  10318. mg_response_header_add(conn, "Content-Length", "0", -1);
  10319. /* Send all headers - there is no body */
  10320. mg_response_header_send(conn);
  10321. } else {
  10322. mg_send_http_error(conn, http_status, "Operation failed");
  10323. }
  10324. }
  10325. static void
  10326. put_file(struct mg_connection *conn, const char *path)
  10327. {
  10328. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10329. const char *range;
  10330. int64_t r1, r2;
  10331. int rc;
  10332. if (conn == NULL) {
  10333. return;
  10334. }
  10335. DEBUG_TRACE("store %s", path);
  10336. if (mg_stat(conn, path, &file.stat)) {
  10337. /* File already exists */
  10338. conn->status_code = 200;
  10339. if (file.stat.is_directory) {
  10340. /* This is an already existing directory,
  10341. * so there is nothing to do for the server. */
  10342. rc = 0;
  10343. } else {
  10344. /* File exists and is not a directory. */
  10345. /* Can it be replaced? */
  10346. /* Check if the server may write this file */
  10347. if (access(path, W_OK) == 0) {
  10348. /* Access granted */
  10349. rc = 1;
  10350. } else {
  10351. mg_send_http_error(
  10352. conn,
  10353. 403,
  10354. "Error: Put not possible\nReplacing %s is not allowed",
  10355. path);
  10356. return;
  10357. }
  10358. }
  10359. } else {
  10360. /* File should be created */
  10361. conn->status_code = 201;
  10362. rc = put_dir(conn, path);
  10363. }
  10364. if (rc == 0) {
  10365. /* put_dir returns 0 if path is a directory */
  10366. /* Create response */
  10367. mg_response_header_start(conn, conn->status_code);
  10368. send_no_cache_header(conn);
  10369. send_additional_header(conn);
  10370. mg_response_header_add(conn, "Content-Length", "0", -1);
  10371. /* Send all headers - there is no body */
  10372. mg_response_header_send(conn);
  10373. /* Request to create a directory has been fulfilled successfully.
  10374. * No need to put a file. */
  10375. return;
  10376. }
  10377. if (rc == -1) {
  10378. /* put_dir returns -1 if the path is too long */
  10379. mg_send_http_error(conn,
  10380. 414,
  10381. "Error: Path too long\nput_dir(%s): %s",
  10382. path,
  10383. strerror(ERRNO));
  10384. return;
  10385. }
  10386. if (rc == -2) {
  10387. /* put_dir returns -2 if the directory can not be created */
  10388. mg_send_http_error(conn,
  10389. 500,
  10390. "Error: Can not create directory\nput_dir(%s): %s",
  10391. path,
  10392. strerror(ERRNO));
  10393. return;
  10394. }
  10395. /* A file should be created or overwritten. */
  10396. /* Currently CivetWeb does not nead read+write access. */
  10397. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10398. || file.access.fp == NULL) {
  10399. (void)mg_fclose(&file.access);
  10400. mg_send_http_error(conn,
  10401. 500,
  10402. "Error: Can not create file\nfopen(%s): %s",
  10403. path,
  10404. strerror(ERRNO));
  10405. return;
  10406. }
  10407. fclose_on_exec(&file.access, conn);
  10408. range = mg_get_header(conn, "Content-Range");
  10409. r1 = r2 = 0;
  10410. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10411. conn->status_code = 206; /* Partial content */
  10412. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10413. mg_send_http_error(conn,
  10414. 500,
  10415. "Error: Internal error processing file %s",
  10416. path);
  10417. return;
  10418. }
  10419. }
  10420. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10421. /* forward_body_data failed.
  10422. * The error code has already been sent to the client,
  10423. * and conn->status_code is already set. */
  10424. (void)mg_fclose(&file.access);
  10425. return;
  10426. }
  10427. if (mg_fclose(&file.access) != 0) {
  10428. /* fclose failed. This might have different reasons, but a likely
  10429. * one is "no space on disk", http 507. */
  10430. conn->status_code = 507;
  10431. }
  10432. /* Create response (status_code has been set before) */
  10433. mg_response_header_start(conn, conn->status_code);
  10434. send_no_cache_header(conn);
  10435. send_additional_header(conn);
  10436. mg_response_header_add(conn, "Content-Length", "0", -1);
  10437. /* Send all headers - there is no body */
  10438. mg_response_header_send(conn);
  10439. }
  10440. static void
  10441. delete_file(struct mg_connection *conn, const char *path)
  10442. {
  10443. struct de de;
  10444. memset(&de.file, 0, sizeof(de.file));
  10445. if (!mg_stat(conn, path, &de.file)) {
  10446. /* mg_stat returns 0 if the file does not exist */
  10447. mg_send_http_error(conn,
  10448. 404,
  10449. "Error: Cannot delete file\nFile %s not found",
  10450. path);
  10451. return;
  10452. }
  10453. DEBUG_TRACE("delete %s", path);
  10454. if (de.file.is_directory) {
  10455. if (remove_directory(conn, path)) {
  10456. /* Delete is successful: Return 204 without content. */
  10457. mg_send_http_error(conn, 204, "%s", "");
  10458. } else {
  10459. /* Delete is not successful: Return 500 (Server error). */
  10460. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10461. }
  10462. return;
  10463. }
  10464. /* This is an existing file (not a directory).
  10465. * Check if write permission is granted. */
  10466. if (access(path, W_OK) != 0) {
  10467. /* File is read only */
  10468. mg_send_http_error(
  10469. conn,
  10470. 403,
  10471. "Error: Delete not possible\nDeleting %s is not allowed",
  10472. path);
  10473. return;
  10474. }
  10475. /* Try to delete it. */
  10476. if (mg_remove(conn, path) == 0) {
  10477. /* Delete was successful: Return 204 without content. */
  10478. mg_response_header_start(conn, 204);
  10479. send_no_cache_header(conn);
  10480. send_additional_header(conn);
  10481. mg_response_header_add(conn, "Content-Length", "0", -1);
  10482. mg_response_header_send(conn);
  10483. } else {
  10484. /* Delete not successful (file locked). */
  10485. mg_send_http_error(conn,
  10486. 423,
  10487. "Error: Cannot delete file\nremove(%s): %s",
  10488. path,
  10489. strerror(ERRNO));
  10490. }
  10491. }
  10492. #endif /* !NO_FILES */
  10493. #if !defined(NO_FILESYSTEMS)
  10494. static void
  10495. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10496. static void
  10497. do_ssi_include(struct mg_connection *conn,
  10498. const char *ssi,
  10499. char *tag,
  10500. int include_level)
  10501. {
  10502. char file_name[MG_BUF_LEN], path[512], *p;
  10503. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10504. size_t len;
  10505. int truncated = 0;
  10506. if (conn == NULL) {
  10507. return;
  10508. }
  10509. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10510. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10511. * always < MG_BUF_LEN. */
  10512. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10513. /* File name is relative to the webserver root */
  10514. file_name[511] = 0;
  10515. (void)mg_snprintf(conn,
  10516. &truncated,
  10517. path,
  10518. sizeof(path),
  10519. "%s/%s",
  10520. conn->dom_ctx->config[DOCUMENT_ROOT],
  10521. file_name);
  10522. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10523. /* File name is relative to the webserver working directory
  10524. * or it is absolute system path */
  10525. file_name[511] = 0;
  10526. (void)
  10527. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10528. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10529. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10530. /* File name is relative to the currect document */
  10531. file_name[511] = 0;
  10532. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10533. if (!truncated) {
  10534. if ((p = strrchr(path, '/')) != NULL) {
  10535. p[1] = '\0';
  10536. }
  10537. len = strlen(path);
  10538. (void)mg_snprintf(conn,
  10539. &truncated,
  10540. path + len,
  10541. sizeof(path) - len,
  10542. "%s",
  10543. file_name);
  10544. }
  10545. } else {
  10546. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10547. return;
  10548. }
  10549. if (truncated) {
  10550. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10551. return;
  10552. }
  10553. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10554. mg_cry_internal(conn,
  10555. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10556. tag,
  10557. path,
  10558. strerror(ERRNO));
  10559. } else {
  10560. fclose_on_exec(&file.access, conn);
  10561. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10562. > 0) {
  10563. send_ssi_file(conn, path, &file, include_level + 1);
  10564. } else {
  10565. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10566. }
  10567. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10568. }
  10569. }
  10570. #if !defined(NO_POPEN)
  10571. static void
  10572. do_ssi_exec(struct mg_connection *conn, char *tag)
  10573. {
  10574. char cmd[1024] = "";
  10575. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10576. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10577. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10578. } else {
  10579. cmd[1023] = 0;
  10580. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10581. mg_cry_internal(conn,
  10582. "Cannot SSI #exec: [%s]: %s",
  10583. cmd,
  10584. strerror(ERRNO));
  10585. } else {
  10586. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10587. pclose(file.access.fp);
  10588. }
  10589. }
  10590. }
  10591. #endif /* !NO_POPEN */
  10592. static int
  10593. mg_fgetc(struct mg_file *filep)
  10594. {
  10595. if (filep == NULL) {
  10596. return EOF;
  10597. }
  10598. if (filep->access.fp != NULL) {
  10599. return fgetc(filep->access.fp);
  10600. } else {
  10601. return EOF;
  10602. }
  10603. }
  10604. static void
  10605. send_ssi_file(struct mg_connection *conn,
  10606. const char *path,
  10607. struct mg_file *filep,
  10608. int include_level)
  10609. {
  10610. char buf[MG_BUF_LEN];
  10611. int ch, len, in_tag, in_ssi_tag;
  10612. if (include_level > 10) {
  10613. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10614. return;
  10615. }
  10616. in_tag = in_ssi_tag = len = 0;
  10617. /* Read file, byte by byte, and look for SSI include tags */
  10618. while ((ch = mg_fgetc(filep)) != EOF) {
  10619. if (in_tag) {
  10620. /* We are in a tag, either SSI tag or html tag */
  10621. if (ch == '>') {
  10622. /* Tag is closing */
  10623. buf[len++] = '>';
  10624. if (in_ssi_tag) {
  10625. /* Handle SSI tag */
  10626. buf[len] = 0;
  10627. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10628. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10629. #if !defined(NO_POPEN)
  10630. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10631. do_ssi_exec(conn, buf + 9);
  10632. #endif /* !NO_POPEN */
  10633. } else {
  10634. mg_cry_internal(conn,
  10635. "%s: unknown SSI "
  10636. "command: \"%s\"",
  10637. path,
  10638. buf);
  10639. }
  10640. len = 0;
  10641. in_ssi_tag = in_tag = 0;
  10642. } else {
  10643. /* Not an SSI tag */
  10644. /* Flush buffer */
  10645. (void)mg_write(conn, buf, (size_t)len);
  10646. len = 0;
  10647. in_tag = 0;
  10648. }
  10649. } else {
  10650. /* Tag is still open */
  10651. buf[len++] = (char)(ch & 0xff);
  10652. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10653. /* All SSI tags start with <!--# */
  10654. in_ssi_tag = 1;
  10655. }
  10656. if ((len + 2) > (int)sizeof(buf)) {
  10657. /* Tag to long for buffer */
  10658. mg_cry_internal(conn, "%s: tag is too large", path);
  10659. return;
  10660. }
  10661. }
  10662. } else {
  10663. /* We are not in a tag yet. */
  10664. if (ch == '<') {
  10665. /* Tag is opening */
  10666. in_tag = 1;
  10667. if (len > 0) {
  10668. /* Flush current buffer.
  10669. * Buffer is filled with "len" bytes. */
  10670. (void)mg_write(conn, buf, (size_t)len);
  10671. }
  10672. /* Store the < */
  10673. len = 1;
  10674. buf[0] = '<';
  10675. } else {
  10676. /* No Tag */
  10677. /* Add data to buffer */
  10678. buf[len++] = (char)(ch & 0xff);
  10679. /* Flush if buffer is full */
  10680. if (len == (int)sizeof(buf)) {
  10681. mg_write(conn, buf, (size_t)len);
  10682. len = 0;
  10683. }
  10684. }
  10685. }
  10686. }
  10687. /* Send the rest of buffered data */
  10688. if (len > 0) {
  10689. mg_write(conn, buf, (size_t)len);
  10690. }
  10691. }
  10692. static void
  10693. handle_ssi_file_request(struct mg_connection *conn,
  10694. const char *path,
  10695. struct mg_file *filep)
  10696. {
  10697. char date[64];
  10698. time_t curtime = time(NULL);
  10699. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10700. return;
  10701. }
  10702. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10703. /* File exists (precondition for calling this function),
  10704. * but can not be opened by the server. */
  10705. mg_send_http_error(conn,
  10706. 500,
  10707. "Error: Cannot read file\nfopen(%s): %s",
  10708. path,
  10709. strerror(ERRNO));
  10710. } else {
  10711. /* Set "must_close" for HTTP/1.x, since we do not know the
  10712. * content length */
  10713. conn->must_close = 1;
  10714. gmt_time_string(date, sizeof(date), &curtime);
  10715. fclose_on_exec(&filep->access, conn);
  10716. /* 200 OK response */
  10717. mg_response_header_start(conn, 200);
  10718. send_no_cache_header(conn);
  10719. send_additional_header(conn);
  10720. send_cors_header(conn);
  10721. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10722. mg_response_header_send(conn);
  10723. /* Header sent, now send body */
  10724. send_ssi_file(conn, path, filep, 0);
  10725. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10726. }
  10727. }
  10728. #endif /* NO_FILESYSTEMS */
  10729. #if !defined(NO_FILES)
  10730. static void
  10731. send_options(struct mg_connection *conn)
  10732. {
  10733. if (!conn || !all_methods) {
  10734. return;
  10735. }
  10736. /* We do not set a "Cache-Control" header here, but leave the default.
  10737. * Since browsers do not send an OPTIONS request, we can not test the
  10738. * effect anyway. */
  10739. mg_response_header_start(conn, 200);
  10740. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10741. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10742. /* Use the same as before */
  10743. mg_response_header_add(conn, "Allow", all_methods, -1);
  10744. mg_response_header_add(conn, "DAV", "1", -1);
  10745. } else {
  10746. /* TODO: Check this later for HTTP/2 */
  10747. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10748. }
  10749. send_additional_header(conn);
  10750. mg_response_header_send(conn);
  10751. }
  10752. /* Writes PROPFIND properties for a collection element */
  10753. static int
  10754. print_props(struct mg_connection *conn,
  10755. const char *uri,
  10756. const char *name,
  10757. struct mg_file_stat *filep)
  10758. {
  10759. size_t i;
  10760. char mtime[64];
  10761. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10762. char *link_concat;
  10763. size_t link_concat_len;
  10764. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10765. return 0;
  10766. }
  10767. link_concat_len = strlen(uri) + strlen(name) + 1;
  10768. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10769. if (!link_concat) {
  10770. return 0;
  10771. }
  10772. strcpy(link_concat, uri);
  10773. strcat(link_concat, name);
  10774. /* Get full link used in request */
  10775. mg_construct_local_link(
  10776. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10777. /*
  10778. OutputDebugStringA("print_props:\n uri: ");
  10779. OutputDebugStringA(uri);
  10780. OutputDebugStringA("\n name: ");
  10781. OutputDebugStringA(name);
  10782. OutputDebugStringA("\n link: ");
  10783. OutputDebugStringA(link_buf);
  10784. OutputDebugStringA("\n");
  10785. */
  10786. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10787. mg_printf(conn,
  10788. "<d:response>"
  10789. "<d:href>%s</d:href>"
  10790. "<d:propstat>"
  10791. "<d:prop>"
  10792. "<d:resourcetype>%s</d:resourcetype>"
  10793. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10794. "<d:getlastmodified>%s</d:getlastmodified>"
  10795. "<d:lockdiscovery>",
  10796. link_buf,
  10797. filep->is_directory ? "<d:collection/>" : "",
  10798. filep->size,
  10799. mtime);
  10800. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10801. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10802. if (!strcmp(dav_lock[i].path, link_buf)) {
  10803. mg_printf(conn,
  10804. "<d:activelock>"
  10805. "<d:locktype><d:write/></d:locktype>"
  10806. "<d:lockscope><d:exclusive/></d:lockscope>"
  10807. "<d:depth>0</d:depth>"
  10808. "<d:owner>%s</d:owner>"
  10809. "<d:timeout>Second-%u</d:timeout>"
  10810. "<d:locktoken>"
  10811. "<d:href>%s</d:href>"
  10812. "</d:locktoken>"
  10813. "</d:activelock>\n",
  10814. dav_lock[i].user,
  10815. (unsigned)LOCK_DURATION_S,
  10816. dav_lock[i].token);
  10817. }
  10818. }
  10819. mg_printf(conn,
  10820. "</d:lockdiscovery>"
  10821. "</d:prop>"
  10822. "<d:status>HTTP/1.1 200 OK</d:status>"
  10823. "</d:propstat>"
  10824. "</d:response>\n");
  10825. mg_free(link_concat);
  10826. return 1;
  10827. }
  10828. static int
  10829. print_dav_dir_entry(struct de *de, void *data)
  10830. {
  10831. struct mg_connection *conn = (struct mg_connection *)data;
  10832. if (!de || !conn
  10833. || !print_props(
  10834. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10835. /* stop scan */
  10836. return 1;
  10837. }
  10838. return 0;
  10839. }
  10840. static void
  10841. handle_propfind(struct mg_connection *conn,
  10842. const char *path,
  10843. struct mg_file_stat *filep)
  10844. {
  10845. const char *depth = mg_get_header(conn, "Depth");
  10846. if (!conn || !path || !filep || !conn->dom_ctx) {
  10847. return;
  10848. }
  10849. /* return 207 "Multi-Status" */
  10850. conn->must_close = 1;
  10851. mg_response_header_start(conn, 207);
  10852. send_static_cache_header(conn);
  10853. send_additional_header(conn);
  10854. mg_response_header_add(conn,
  10855. "Content-Type",
  10856. "application/xml; charset=utf-8",
  10857. -1);
  10858. mg_response_header_send(conn);
  10859. /* Content */
  10860. mg_printf(conn,
  10861. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10862. "<d:multistatus xmlns:d='DAV:'>\n");
  10863. /* Print properties for the requested resource itself */
  10864. print_props(conn, conn->request_info.local_uri, "", filep);
  10865. /* If it is a directory, print directory entries too if Depth is not 0
  10866. */
  10867. if (filep->is_directory
  10868. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10869. "yes")
  10870. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10871. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10872. }
  10873. mg_printf(conn, "%s\n", "</d:multistatus>");
  10874. }
  10875. static void
  10876. dav_lock_file(struct mg_connection *conn, const char *path)
  10877. {
  10878. /* internal function - therefore conn is assumed to be valid */
  10879. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10880. uint64_t new_locktime;
  10881. int lock_index = -1;
  10882. int i;
  10883. uint64_t LOCK_DURATION_NS =
  10884. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10885. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10886. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10887. return;
  10888. }
  10889. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10890. /* const char *refresh = mg_get_header(conn, "If"); */
  10891. /* Link refresh should have an "If" header:
  10892. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10893. * But it seems Windows Explorer does not send them.
  10894. */
  10895. mg_lock_context(conn->phys_ctx);
  10896. new_locktime = mg_get_current_time_ns();
  10897. /* Find a slot for a lock */
  10898. while (lock_index < 0) {
  10899. /* find existing lock */
  10900. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10901. if (!strcmp(dav_lock[i].path, link_buf)) {
  10902. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10903. /* locked by the same user */
  10904. dav_lock[i].locktime = new_locktime;
  10905. lock_index = i;
  10906. break;
  10907. } else {
  10908. /* already locked by someone else */
  10909. if (new_locktime
  10910. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10911. /* Lock expired */
  10912. dav_lock[i].path[0] = 0;
  10913. } else {
  10914. /* Lock still valid */
  10915. mg_unlock_context(conn->phys_ctx);
  10916. mg_send_http_error(conn, 423, "%s", "Already locked");
  10917. return;
  10918. }
  10919. }
  10920. }
  10921. }
  10922. /* create new lock token */
  10923. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10924. if (dav_lock[i].path[0] == 0) {
  10925. char s[32];
  10926. dav_lock[i].locktime = mg_get_current_time_ns();
  10927. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10928. mg_md5(dav_lock[i].token,
  10929. link_buf,
  10930. "\x01",
  10931. s,
  10932. "\x01",
  10933. conn->request_info.remote_user,
  10934. NULL);
  10935. strncpy(dav_lock[i].path,
  10936. link_buf,
  10937. sizeof(dav_lock[i].path) - 1);
  10938. strncpy(dav_lock[i].user,
  10939. conn->request_info.remote_user,
  10940. sizeof(dav_lock[i].user) - 1);
  10941. lock_index = i;
  10942. break;
  10943. }
  10944. }
  10945. if (lock_index < 0) {
  10946. /* too many locks. Find oldest lock */
  10947. uint64_t oldest_locktime = dav_lock[0].locktime;
  10948. lock_index = 0;
  10949. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10950. if (dav_lock[i].locktime < oldest_locktime) {
  10951. oldest_locktime = dav_lock[i].locktime;
  10952. lock_index = i;
  10953. }
  10954. }
  10955. /* invalidate oldest lock */
  10956. dav_lock[lock_index].path[0] = 0;
  10957. }
  10958. }
  10959. mg_unlock_context(conn->phys_ctx);
  10960. /* return 200 "OK" */
  10961. conn->must_close = 1;
  10962. mg_response_header_start(conn, 200);
  10963. send_static_cache_header(conn);
  10964. send_additional_header(conn);
  10965. mg_response_header_add(conn,
  10966. "Content-Type",
  10967. "application/xml; charset=utf-8",
  10968. -1);
  10969. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10970. mg_response_header_send(conn);
  10971. /* Content */
  10972. mg_printf(conn,
  10973. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10974. "<d:prop xmlns:d=\"DAV:\">\n"
  10975. " <d:lockdiscovery>\n"
  10976. " <d:activelock>\n"
  10977. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  10978. " <d:locktype><d:write/></d:locktype>\n"
  10979. " <d:owner>\n"
  10980. " <d:href>%s</d:href>\n"
  10981. " </d:owner>\n"
  10982. " <d:timeout>Second-%u</d:timeout>\n"
  10983. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  10984. " <d:lockroot>\n"
  10985. " <d:href>%s</d:href>\n"
  10986. " </d:lockroot>\n"
  10987. " </d:activelock>\n"
  10988. " </d:lockdiscovery>\n"
  10989. " </d:prop>\n",
  10990. dav_lock[lock_index].user,
  10991. (LOCK_DURATION_S),
  10992. dav_lock[lock_index].token,
  10993. dav_lock[lock_index].path);
  10994. }
  10995. static void
  10996. dav_unlock_file(struct mg_connection *conn, const char *path)
  10997. {
  10998. /* internal function - therefore conn is assumed to be valid */
  10999. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11000. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11001. int lock_index;
  11002. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11003. return;
  11004. }
  11005. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11006. mg_lock_context(conn->phys_ctx);
  11007. /* find existing lock */
  11008. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11009. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11010. /* Success: return 204 "No Content" */
  11011. mg_unlock_context(conn->phys_ctx);
  11012. conn->must_close = 1;
  11013. mg_response_header_start(conn, 204);
  11014. mg_response_header_send(conn);
  11015. return;
  11016. }
  11017. }
  11018. mg_unlock_context(conn->phys_ctx);
  11019. /* Error: Cannot unlock a resource that is not locked */
  11020. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11021. }
  11022. static void
  11023. dav_proppatch(struct mg_connection *conn, const char *path)
  11024. {
  11025. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11026. if (!conn || !path || !conn->dom_ctx) {
  11027. return;
  11028. }
  11029. /* return 207 "Multi-Status" */
  11030. conn->must_close = 1;
  11031. mg_response_header_start(conn, 207);
  11032. send_static_cache_header(conn);
  11033. send_additional_header(conn);
  11034. mg_response_header_add(conn,
  11035. "Content-Type",
  11036. "application/xml; charset=utf-8",
  11037. -1);
  11038. mg_response_header_send(conn);
  11039. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11040. /* Content */
  11041. mg_printf(conn,
  11042. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11043. "<d:multistatus xmlns:d='DAV:'>\n"
  11044. "<d:response>\n<d:href>%s</d:href>\n",
  11045. link_buf);
  11046. mg_printf(conn,
  11047. "<d:propstat><d:status>HTTP/1.1 403 "
  11048. "Forbidden</d:status></d:propstat>\n");
  11049. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11050. }
  11051. #endif
  11052. void
  11053. mg_lock_connection(struct mg_connection *conn)
  11054. {
  11055. if (conn) {
  11056. (void)pthread_mutex_lock(&conn->mutex);
  11057. }
  11058. }
  11059. void
  11060. mg_unlock_connection(struct mg_connection *conn)
  11061. {
  11062. if (conn) {
  11063. (void)pthread_mutex_unlock(&conn->mutex);
  11064. }
  11065. }
  11066. void
  11067. mg_lock_context(struct mg_context *ctx)
  11068. {
  11069. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11070. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11071. }
  11072. }
  11073. void
  11074. mg_unlock_context(struct mg_context *ctx)
  11075. {
  11076. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11077. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11078. }
  11079. }
  11080. #if defined(USE_LUA)
  11081. #include "mod_lua.inl"
  11082. #endif /* USE_LUA */
  11083. #if defined(USE_DUKTAPE)
  11084. #include "mod_duktape.inl"
  11085. #endif /* USE_DUKTAPE */
  11086. #if defined(USE_WEBSOCKET)
  11087. #if !defined(NO_SSL_DL)
  11088. #define SHA_API static
  11089. #include "sha1.inl"
  11090. #endif
  11091. static int
  11092. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11093. {
  11094. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11095. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11096. size_t dst_len = sizeof(b64_sha);
  11097. SHA_CTX sha_ctx;
  11098. int truncated;
  11099. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11100. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11101. if (truncated) {
  11102. conn->must_close = 1;
  11103. return 0;
  11104. }
  11105. DEBUG_TRACE("%s", "Send websocket handshake");
  11106. SHA1_Init(&sha_ctx);
  11107. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11108. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11109. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11110. mg_printf(conn,
  11111. "HTTP/1.1 101 Switching Protocols\r\n"
  11112. "Upgrade: websocket\r\n"
  11113. "Connection: Upgrade\r\n"
  11114. "Sec-WebSocket-Accept: %s\r\n",
  11115. b64_sha);
  11116. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11117. // Send negotiated compression extension parameters
  11118. websocket_deflate_response(conn);
  11119. #endif
  11120. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11121. mg_printf(conn,
  11122. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11123. conn->request_info.acceptedWebSocketSubprotocol);
  11124. } else {
  11125. mg_printf(conn, "%s", "\r\n");
  11126. }
  11127. return 1;
  11128. }
  11129. #if !defined(MG_MAX_UNANSWERED_PING)
  11130. /* Configuration of the maximum number of websocket PINGs that might
  11131. * stay unanswered before the connection is considered broken.
  11132. * Note: The name of this define may still change (until it is
  11133. * defined as a compile parameter in a documentation).
  11134. */
  11135. #define MG_MAX_UNANSWERED_PING (5)
  11136. #endif
  11137. static void
  11138. read_websocket(struct mg_connection *conn,
  11139. mg_websocket_data_handler ws_data_handler,
  11140. void *callback_data)
  11141. {
  11142. /* Pointer to the beginning of the portion of the incoming websocket
  11143. * message queue.
  11144. * The original websocket upgrade request is never removed, so the queue
  11145. * begins after it. */
  11146. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11147. int n, error, exit_by_callback;
  11148. int ret;
  11149. /* body_len is the length of the entire queue in bytes
  11150. * len is the length of the current message
  11151. * data_len is the length of the current message's data payload
  11152. * header_len is the length of the current message's header */
  11153. size_t i, len, mask_len = 0, header_len, body_len;
  11154. uint64_t data_len = 0;
  11155. /* "The masking key is a 32-bit value chosen at random by the client."
  11156. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11157. */
  11158. unsigned char mask[4];
  11159. /* data points to the place where the message is stored when passed to
  11160. * the websocket_data callback. This is either mem on the stack, or a
  11161. * dynamically allocated buffer if it is too large. */
  11162. unsigned char mem[4096];
  11163. unsigned char mop; /* mask flag and opcode */
  11164. /* Variables used for connection monitoring */
  11165. double timeout = -1.0;
  11166. int enable_ping_pong = 0;
  11167. int ping_count = 0;
  11168. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11169. enable_ping_pong =
  11170. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11171. "yes");
  11172. }
  11173. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11174. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11175. }
  11176. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11177. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11178. }
  11179. if (timeout <= 0.0) {
  11180. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11181. }
  11182. /* Enter data processing loop */
  11183. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11184. conn->request_info.remote_addr,
  11185. conn->request_info.remote_port);
  11186. conn->in_websocket_handling = 1;
  11187. mg_set_thread_name("wsock");
  11188. /* Loop continuously, reading messages from the socket, invoking the
  11189. * callback, and waiting repeatedly until an error occurs. */
  11190. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11191. && (!conn->must_close)) {
  11192. header_len = 0;
  11193. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11194. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11195. len = buf[1] & 127;
  11196. mask_len = (buf[1] & 128) ? 4 : 0;
  11197. if ((len < 126) && (body_len >= mask_len)) {
  11198. /* inline 7-bit length field */
  11199. data_len = len;
  11200. header_len = 2 + mask_len;
  11201. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11202. /* 16-bit length field */
  11203. header_len = 4 + mask_len;
  11204. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11205. } else if (body_len >= (10 + mask_len)) {
  11206. /* 64-bit length field */
  11207. uint32_t l1, l2;
  11208. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11209. memcpy(&l2, &buf[6], 4);
  11210. header_len = 10 + mask_len;
  11211. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11212. if (data_len > (uint64_t)0x7FFF0000ul) {
  11213. /* no can do */
  11214. mg_cry_internal(
  11215. conn,
  11216. "%s",
  11217. "websocket out of memory; closing connection");
  11218. break;
  11219. }
  11220. }
  11221. }
  11222. if ((header_len > 0) && (body_len >= header_len)) {
  11223. /* Allocate space to hold websocket payload */
  11224. unsigned char *data = mem;
  11225. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11226. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11227. conn->phys_ctx);
  11228. if (data == NULL) {
  11229. /* Allocation failed, exit the loop and then close the
  11230. * connection */
  11231. mg_cry_internal(
  11232. conn,
  11233. "%s",
  11234. "websocket out of memory; closing connection");
  11235. break;
  11236. }
  11237. }
  11238. /* Copy the mask before we shift the queue and destroy it */
  11239. if (mask_len > 0) {
  11240. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11241. } else {
  11242. memset(mask, 0, sizeof(mask));
  11243. }
  11244. /* Read frame payload from the first message in the queue into
  11245. * data and advance the queue by moving the memory in place. */
  11246. DEBUG_ASSERT(body_len >= header_len);
  11247. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11248. mop = buf[0]; /* current mask and opcode */
  11249. /* Overflow case */
  11250. len = body_len - header_len;
  11251. memcpy(data, buf + header_len, len);
  11252. error = 0;
  11253. while ((uint64_t)len < data_len) {
  11254. n = pull_inner(NULL,
  11255. conn,
  11256. (char *)(data + len),
  11257. (int)(data_len - len),
  11258. timeout);
  11259. if (n <= -2) {
  11260. error = 1;
  11261. break;
  11262. } else if (n > 0) {
  11263. len += (size_t)n;
  11264. } else {
  11265. /* Timeout: should retry */
  11266. /* TODO: retry condition */
  11267. }
  11268. }
  11269. if (error) {
  11270. mg_cry_internal(
  11271. conn,
  11272. "%s",
  11273. "Websocket pull failed; closing connection");
  11274. if (data != mem) {
  11275. mg_free(data);
  11276. }
  11277. break;
  11278. }
  11279. conn->data_len = conn->request_len;
  11280. } else {
  11281. mop = buf[0]; /* current mask and opcode, overwritten by
  11282. * memmove() */
  11283. /* Length of the message being read at the front of the
  11284. * queue. Cast to 31 bit is OK, since we limited
  11285. * data_len before. */
  11286. len = (size_t)data_len + header_len;
  11287. /* Copy the data payload into the data pointer for the
  11288. * callback. Cast to 31 bit is OK, since we
  11289. * limited data_len */
  11290. memcpy(data, buf + header_len, (size_t)data_len);
  11291. /* Move the queue forward len bytes */
  11292. memmove(buf, buf + len, body_len - len);
  11293. /* Mark the queue as advanced */
  11294. conn->data_len -= (int)len;
  11295. }
  11296. /* Apply mask if necessary */
  11297. if (mask_len > 0) {
  11298. for (i = 0; i < (size_t)data_len; i++) {
  11299. data[i] ^= mask[i & 3];
  11300. }
  11301. }
  11302. exit_by_callback = 0;
  11303. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11304. /* filter PONG messages */
  11305. DEBUG_TRACE("PONG from %s:%u",
  11306. conn->request_info.remote_addr,
  11307. conn->request_info.remote_port);
  11308. /* No unanwered PINGs left */
  11309. ping_count = 0;
  11310. } else if (enable_ping_pong
  11311. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11312. /* reply PING messages */
  11313. DEBUG_TRACE("Reply PING from %s:%u",
  11314. conn->request_info.remote_addr,
  11315. conn->request_info.remote_port);
  11316. ret = mg_websocket_write(conn,
  11317. MG_WEBSOCKET_OPCODE_PONG,
  11318. (char *)data,
  11319. (size_t)data_len);
  11320. if (ret <= 0) {
  11321. /* Error: send failed */
  11322. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11323. break;
  11324. }
  11325. } else {
  11326. /* Exit the loop if callback signals to exit (server side),
  11327. * or "connection close" opcode received (client side). */
  11328. if (ws_data_handler != NULL) {
  11329. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11330. if (mop & 0x40) {
  11331. /* Inflate the data received if bit RSV1 is set. */
  11332. if (!conn->websocket_deflate_initialized) {
  11333. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11334. exit_by_callback = 1;
  11335. }
  11336. if (!exit_by_callback) {
  11337. size_t inflate_buf_size_old = 0;
  11338. size_t inflate_buf_size =
  11339. data_len
  11340. * 4; // Initial guess of the inflated message
  11341. // size. We double the memory when needed.
  11342. Bytef *inflated = NULL;
  11343. Bytef *new_mem = NULL;
  11344. conn->websocket_inflate_state.avail_in =
  11345. (uInt)(data_len + 4);
  11346. conn->websocket_inflate_state.next_in = data;
  11347. // Add trailing 0x00 0x00 0xff 0xff bytes
  11348. data[data_len] = '\x00';
  11349. data[data_len + 1] = '\x00';
  11350. data[data_len + 2] = '\xff';
  11351. data[data_len + 3] = '\xff';
  11352. do {
  11353. if (inflate_buf_size_old == 0) {
  11354. new_mem =
  11355. (Bytef *)mg_calloc(inflate_buf_size,
  11356. sizeof(Bytef));
  11357. } else {
  11358. inflate_buf_size *= 2;
  11359. new_mem =
  11360. (Bytef *)mg_realloc(inflated,
  11361. inflate_buf_size);
  11362. }
  11363. if (new_mem == NULL) {
  11364. mg_cry_internal(
  11365. conn,
  11366. "Out of memory: Cannot allocate "
  11367. "inflate buffer of %lu bytes",
  11368. (unsigned long)inflate_buf_size);
  11369. exit_by_callback = 1;
  11370. break;
  11371. }
  11372. inflated = new_mem;
  11373. conn->websocket_inflate_state.avail_out =
  11374. (uInt)(inflate_buf_size
  11375. - inflate_buf_size_old);
  11376. conn->websocket_inflate_state.next_out =
  11377. inflated + inflate_buf_size_old;
  11378. ret = inflate(&conn->websocket_inflate_state,
  11379. Z_SYNC_FLUSH);
  11380. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11381. || ret == Z_MEM_ERROR) {
  11382. mg_cry_internal(
  11383. conn,
  11384. "ZLIB inflate error: %i %s",
  11385. ret,
  11386. (conn->websocket_inflate_state.msg
  11387. ? conn->websocket_inflate_state.msg
  11388. : "<no error message>"));
  11389. exit_by_callback = 1;
  11390. break;
  11391. }
  11392. inflate_buf_size_old = inflate_buf_size;
  11393. } while (conn->websocket_inflate_state.avail_out
  11394. == 0);
  11395. inflate_buf_size -=
  11396. conn->websocket_inflate_state.avail_out;
  11397. if (!ws_data_handler(conn,
  11398. mop,
  11399. (char *)inflated,
  11400. inflate_buf_size,
  11401. callback_data)) {
  11402. exit_by_callback = 1;
  11403. }
  11404. mg_free(inflated);
  11405. }
  11406. } else
  11407. #endif
  11408. if (!ws_data_handler(conn,
  11409. mop,
  11410. (char *)data,
  11411. (size_t)data_len,
  11412. callback_data)) {
  11413. exit_by_callback = 1;
  11414. }
  11415. }
  11416. }
  11417. /* It a buffer has been allocated, free it again */
  11418. if (data != mem) {
  11419. mg_free(data);
  11420. }
  11421. if (exit_by_callback) {
  11422. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11423. conn->request_info.remote_addr,
  11424. conn->request_info.remote_port);
  11425. break;
  11426. }
  11427. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11428. /* Opcode == 8, connection close */
  11429. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11430. conn->request_info.remote_addr,
  11431. conn->request_info.remote_port);
  11432. break;
  11433. }
  11434. /* Not breaking the loop, process next websocket frame. */
  11435. } else {
  11436. /* Read from the socket into the next available location in the
  11437. * message queue. */
  11438. n = pull_inner(NULL,
  11439. conn,
  11440. conn->buf + conn->data_len,
  11441. conn->buf_size - conn->data_len,
  11442. timeout);
  11443. if (n <= -2) {
  11444. /* Error, no bytes read */
  11445. DEBUG_TRACE("PULL from %s:%u failed",
  11446. conn->request_info.remote_addr,
  11447. conn->request_info.remote_port);
  11448. break;
  11449. }
  11450. if (n > 0) {
  11451. conn->data_len += n;
  11452. /* Reset open PING count */
  11453. ping_count = 0;
  11454. } else {
  11455. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11456. && (!conn->must_close)) {
  11457. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11458. /* Stop sending PING */
  11459. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11460. "- closing connection",
  11461. ping_count,
  11462. conn->request_info.remote_addr,
  11463. conn->request_info.remote_port);
  11464. break;
  11465. }
  11466. if (enable_ping_pong) {
  11467. /* Send Websocket PING message */
  11468. DEBUG_TRACE("PING to %s:%u",
  11469. conn->request_info.remote_addr,
  11470. conn->request_info.remote_port);
  11471. ret = mg_websocket_write(conn,
  11472. MG_WEBSOCKET_OPCODE_PING,
  11473. NULL,
  11474. 0);
  11475. if (ret <= 0) {
  11476. /* Error: send failed */
  11477. DEBUG_TRACE("Send PING failed (%i)", ret);
  11478. break;
  11479. }
  11480. ping_count++;
  11481. }
  11482. }
  11483. /* Timeout: should retry */
  11484. /* TODO: get timeout def */
  11485. }
  11486. }
  11487. }
  11488. /* Leave data processing loop */
  11489. mg_set_thread_name("worker");
  11490. conn->in_websocket_handling = 0;
  11491. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11492. conn->request_info.remote_addr,
  11493. conn->request_info.remote_port);
  11494. }
  11495. static int
  11496. mg_websocket_write_exec(struct mg_connection *conn,
  11497. int opcode,
  11498. const char *data,
  11499. size_t dataLen,
  11500. uint32_t masking_key)
  11501. {
  11502. unsigned char header[14];
  11503. size_t headerLen;
  11504. int retval;
  11505. #if defined(GCC_DIAGNOSTIC)
  11506. /* Disable spurious conversion warning for GCC */
  11507. #pragma GCC diagnostic push
  11508. #pragma GCC diagnostic ignored "-Wconversion"
  11509. #endif
  11510. /* Note that POSIX/Winsock's send() is threadsafe
  11511. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11512. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11513. * push(), although that is only a problem if the packet is large or
  11514. * outgoing buffer is full). */
  11515. /* TODO: Check if this lock should be moved to user land.
  11516. * Currently the server sets this lock for websockets, but
  11517. * not for any other connection. It must be set for every
  11518. * conn read/written by more than one thread, no matter if
  11519. * it is a websocket or regular connection. */
  11520. (void)mg_lock_connection(conn);
  11521. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11522. size_t deflated_size = 0;
  11523. Bytef *deflated = 0;
  11524. // Deflate websocket messages over 100kb
  11525. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11526. if (use_deflate) {
  11527. if (!conn->websocket_deflate_initialized) {
  11528. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11529. return 0;
  11530. }
  11531. // Deflating the message
  11532. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11533. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11534. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11535. deflated_size = (Bytef *)compressBound((uLong)dataLen);
  11536. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11537. if (deflated == NULL) {
  11538. mg_cry_internal(
  11539. conn,
  11540. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11541. (unsigned long)deflated_size);
  11542. mg_unlock_connection(conn);
  11543. return -1;
  11544. }
  11545. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11546. conn->websocket_deflate_state.next_out = deflated;
  11547. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11548. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11549. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11550. } else
  11551. #endif
  11552. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11553. #if defined(GCC_DIAGNOSTIC)
  11554. #pragma GCC diagnostic pop
  11555. #endif
  11556. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11557. if (dataLen < 126) {
  11558. /* inline 7-bit length field */
  11559. header[1] = (unsigned char)dataLen;
  11560. headerLen = 2;
  11561. } else if (dataLen <= 0xFFFF) {
  11562. /* 16-bit length field */
  11563. uint16_t len = htons((uint16_t)dataLen);
  11564. header[1] = 126;
  11565. memcpy(header + 2, &len, 2);
  11566. headerLen = 4;
  11567. } else {
  11568. /* 64-bit length field */
  11569. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11570. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11571. header[1] = 127;
  11572. memcpy(header + 2, &len1, 4);
  11573. memcpy(header + 6, &len2, 4);
  11574. headerLen = 10;
  11575. }
  11576. if (masking_key) {
  11577. /* add mask */
  11578. header[1] |= 0x80;
  11579. memcpy(header + headerLen, &masking_key, 4);
  11580. headerLen += 4;
  11581. }
  11582. retval = mg_write(conn, header, headerLen);
  11583. if (retval != (int)headerLen) {
  11584. /* Did not send complete header */
  11585. retval = -1;
  11586. } else {
  11587. if (dataLen > 0) {
  11588. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11589. if (use_deflate) {
  11590. retval = mg_write(conn, deflated, dataLen);
  11591. mg_free(deflated);
  11592. } else
  11593. #endif
  11594. retval = mg_write(conn, data, dataLen);
  11595. }
  11596. /* if dataLen == 0, the header length (2) is returned */
  11597. }
  11598. /* TODO: Remove this unlock as well, when lock is removed. */
  11599. mg_unlock_connection(conn);
  11600. return retval;
  11601. }
  11602. int
  11603. mg_websocket_write(struct mg_connection *conn,
  11604. int opcode,
  11605. const char *data,
  11606. size_t dataLen)
  11607. {
  11608. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11609. }
  11610. static void
  11611. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11612. {
  11613. size_t i = 0;
  11614. i = 0;
  11615. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11616. /* Convert in 32 bit words, if data is 4 byte aligned */
  11617. while (i < (in_len - 3)) {
  11618. *(uint32_t *)(void *)(out + i) =
  11619. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11620. i += 4;
  11621. }
  11622. }
  11623. if (i != in_len) {
  11624. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11625. while (i < in_len) {
  11626. *(uint8_t *)(void *)(out + i) =
  11627. *(uint8_t *)(void *)(in + i)
  11628. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11629. i++;
  11630. }
  11631. }
  11632. }
  11633. int
  11634. mg_websocket_client_write(struct mg_connection *conn,
  11635. int opcode,
  11636. const char *data,
  11637. size_t dataLen)
  11638. {
  11639. int retval = -1;
  11640. char *masked_data =
  11641. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11642. uint32_t masking_key = 0;
  11643. if (masked_data == NULL) {
  11644. /* Return -1 in an error case */
  11645. mg_cry_internal(conn,
  11646. "%s",
  11647. "Cannot allocate buffer for masked websocket response: "
  11648. "Out of memory");
  11649. return -1;
  11650. }
  11651. do {
  11652. /* Get a masking key - but not 0 */
  11653. masking_key = (uint32_t)get_random();
  11654. } while (masking_key == 0);
  11655. mask_data(data, dataLen, masking_key, masked_data);
  11656. retval = mg_websocket_write_exec(
  11657. conn, opcode, masked_data, dataLen, masking_key);
  11658. mg_free(masked_data);
  11659. return retval;
  11660. }
  11661. static void
  11662. handle_websocket_request(struct mg_connection *conn,
  11663. const char *path,
  11664. int is_callback_resource,
  11665. struct mg_websocket_subprotocols *subprotocols,
  11666. mg_websocket_connect_handler ws_connect_handler,
  11667. mg_websocket_ready_handler ws_ready_handler,
  11668. mg_websocket_data_handler ws_data_handler,
  11669. mg_websocket_close_handler ws_close_handler,
  11670. void *cbData)
  11671. {
  11672. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11673. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11674. ptrdiff_t lua_websock = 0;
  11675. #if !defined(USE_LUA)
  11676. (void)path;
  11677. #endif
  11678. /* Step 1: Check websocket protocol version. */
  11679. /* Step 1.1: Check Sec-WebSocket-Key. */
  11680. if (!websock_key) {
  11681. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11682. * requires a Sec-WebSocket-Key header.
  11683. */
  11684. /* It could be the hixie draft version
  11685. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11686. */
  11687. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11688. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11689. char key3[8];
  11690. if ((key1 != NULL) && (key2 != NULL)) {
  11691. /* This version uses 8 byte body data in a GET request */
  11692. conn->content_len = 8;
  11693. if (8 == mg_read(conn, key3, 8)) {
  11694. /* This is the hixie version */
  11695. mg_send_http_error(conn,
  11696. 426,
  11697. "%s",
  11698. "Protocol upgrade to RFC 6455 required");
  11699. return;
  11700. }
  11701. }
  11702. /* This is an unknown version */
  11703. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11704. return;
  11705. }
  11706. /* Step 1.2: Check websocket protocol version. */
  11707. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11708. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11709. /* Reject wrong versions */
  11710. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11711. return;
  11712. }
  11713. /* Step 1.3: Could check for "Host", but we do not really nead this
  11714. * value for anything, so just ignore it. */
  11715. /* Step 2: If a callback is responsible, call it. */
  11716. if (is_callback_resource) {
  11717. /* Step 2.1 check and select subprotocol */
  11718. const char *protocols[64]; // max 64 headers
  11719. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11720. "Sec-WebSocket-Protocol",
  11721. protocols,
  11722. 64);
  11723. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11724. int headerNo, idx;
  11725. size_t len;
  11726. const char *sep, *curSubProtocol,
  11727. *acceptedWebSocketSubprotocol = NULL;
  11728. /* look for matching subprotocol */
  11729. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11730. /* There might be multiple headers ... */
  11731. const char *protocol = protocols[headerNo];
  11732. curSubProtocol = protocol;
  11733. /* ... and in every header there might be a , separated list */
  11734. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11735. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11736. curSubProtocol++;
  11737. sep = strchr(curSubProtocol, ',');
  11738. if (sep) {
  11739. len = (size_t)(sep - curSubProtocol);
  11740. } else {
  11741. len = strlen(curSubProtocol);
  11742. }
  11743. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11744. // COMPARE: curSubProtocol ==
  11745. // subprotocols->subprotocols[idx]
  11746. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11747. && (strncmp(curSubProtocol,
  11748. subprotocols->subprotocols[idx],
  11749. len)
  11750. == 0)) {
  11751. acceptedWebSocketSubprotocol =
  11752. subprotocols->subprotocols[idx];
  11753. break;
  11754. }
  11755. }
  11756. curSubProtocol += len;
  11757. }
  11758. }
  11759. conn->request_info.acceptedWebSocketSubprotocol =
  11760. acceptedWebSocketSubprotocol;
  11761. }
  11762. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11763. websocket_deflate_negotiate(conn);
  11764. #endif
  11765. if ((ws_connect_handler != NULL)
  11766. && (ws_connect_handler(conn, cbData) != 0)) {
  11767. /* C callback has returned non-zero, do not proceed with
  11768. * handshake.
  11769. */
  11770. /* Note that C callbacks are no longer called when Lua is
  11771. * responsible, so C can no longer filter callbacks for Lua. */
  11772. return;
  11773. }
  11774. }
  11775. #if defined(USE_LUA)
  11776. /* Step 3: No callback. Check if Lua is responsible. */
  11777. else {
  11778. /* Step 3.1: Check if Lua is responsible. */
  11779. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11780. lua_websock = match_prefix_strlen(
  11781. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11782. }
  11783. if (lua_websock) {
  11784. /* Step 3.2: Lua is responsible: call it. */
  11785. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11786. if (!conn->lua_websocket_state) {
  11787. /* Lua rejected the new client */
  11788. return;
  11789. }
  11790. }
  11791. }
  11792. #endif
  11793. /* Step 4: Check if there is a responsible websocket handler. */
  11794. if (!is_callback_resource && !lua_websock) {
  11795. /* There is no callback, and Lua is not responsible either. */
  11796. /* Reply with a 404 Not Found. We are still at a standard
  11797. * HTTP request here, before the websocket handshake, so
  11798. * we can still send standard HTTP error replies. */
  11799. mg_send_http_error(conn, 404, "%s", "Not found");
  11800. return;
  11801. }
  11802. /* Step 5: The websocket connection has been accepted */
  11803. if (!send_websocket_handshake(conn, websock_key)) {
  11804. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11805. return;
  11806. }
  11807. /* Step 6: Call the ready handler */
  11808. if (is_callback_resource) {
  11809. if (ws_ready_handler != NULL) {
  11810. ws_ready_handler(conn, cbData);
  11811. }
  11812. #if defined(USE_LUA)
  11813. } else if (lua_websock) {
  11814. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11815. /* the ready handler returned false */
  11816. return;
  11817. }
  11818. #endif
  11819. }
  11820. /* Step 7: Enter the read loop */
  11821. if (is_callback_resource) {
  11822. read_websocket(conn, ws_data_handler, cbData);
  11823. #if defined(USE_LUA)
  11824. } else if (lua_websock) {
  11825. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11826. #endif
  11827. }
  11828. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11829. /* Step 8: Close the deflate & inflate buffers */
  11830. if (conn->websocket_deflate_initialized) {
  11831. deflateEnd(&conn->websocket_deflate_state);
  11832. inflateEnd(&conn->websocket_inflate_state);
  11833. }
  11834. #endif
  11835. /* Step 9: Call the close handler */
  11836. if (ws_close_handler) {
  11837. ws_close_handler(conn, cbData);
  11838. }
  11839. }
  11840. #endif /* !USE_WEBSOCKET */
  11841. /* Is upgrade request:
  11842. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11843. * 1 = upgrade to websocket
  11844. * 2 = upgrade to HTTP/2
  11845. * -1 = upgrade to unknown protocol
  11846. */
  11847. static int
  11848. should_switch_to_protocol(const struct mg_connection *conn)
  11849. {
  11850. const char *upgrade, *connection;
  11851. /* A websocket protocoll has the following HTTP headers:
  11852. *
  11853. * Connection: Upgrade
  11854. * Upgrade: Websocket
  11855. */
  11856. connection = mg_get_header(conn, "Connection");
  11857. if (connection == NULL) {
  11858. return PROTOCOL_TYPE_HTTP1;
  11859. }
  11860. if (!mg_strcasestr(connection, "upgrade")) {
  11861. return PROTOCOL_TYPE_HTTP1;
  11862. }
  11863. upgrade = mg_get_header(conn, "Upgrade");
  11864. if (upgrade == NULL) {
  11865. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11866. return -1;
  11867. }
  11868. /* Upgrade to ... */
  11869. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11870. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11871. * "Sec-WebSocket-Version" are also required.
  11872. * Don't check them here, since even an unsupported websocket protocol
  11873. * request still IS a websocket request (in contrast to a standard HTTP
  11874. * request). It will fail later in handle_websocket_request.
  11875. */
  11876. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11877. }
  11878. if (0 != mg_strcasestr(upgrade, "h2")) {
  11879. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11880. }
  11881. /* Upgrade to another protocol */
  11882. return -1;
  11883. }
  11884. static int
  11885. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11886. {
  11887. int n;
  11888. unsigned int a, b, c, d, slash;
  11889. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11890. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11891. // integer value, but function will not report conversion
  11892. // errors; consider using 'strtol' instead
  11893. slash = 32;
  11894. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11895. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11896. // an integer value, but function will not report conversion
  11897. // errors; consider using 'strtol' instead
  11898. n = 0;
  11899. }
  11900. }
  11901. if ((n > 0) && ((size_t)n == vec->len)) {
  11902. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11903. /* IPv4 format */
  11904. if (sa->sa.sa_family == AF_INET) {
  11905. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11906. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11907. | ((uint32_t)c << 8) | (uint32_t)d;
  11908. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11909. return (ip & mask) == net;
  11910. }
  11911. return 0;
  11912. }
  11913. }
  11914. #if defined(USE_IPV6)
  11915. else {
  11916. char ad[50];
  11917. const char *p;
  11918. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11919. slash = 128;
  11920. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11921. n = 0;
  11922. }
  11923. }
  11924. if ((n <= 0) && no_strict) {
  11925. /* no square brackets? */
  11926. p = strchr(vec->ptr, '/');
  11927. if (p && (p < (vec->ptr + vec->len))) {
  11928. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11929. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11930. n += (int)(p - vec->ptr);
  11931. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11932. } else {
  11933. n = 0;
  11934. }
  11935. } else if (vec->len < sizeof(ad)) {
  11936. n = (int)vec->len;
  11937. slash = 128;
  11938. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11939. }
  11940. }
  11941. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11942. p = ad;
  11943. c = 0;
  11944. /* zone indexes are unsupported, at least two colons are needed */
  11945. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11946. if (*(p++) == ':') {
  11947. c++;
  11948. }
  11949. }
  11950. if ((*p == '\0') && (c >= 2)) {
  11951. struct sockaddr_in6 sin6;
  11952. unsigned int i;
  11953. /* for strict validation, an actual IPv6 argument is needed */
  11954. if (sa->sa.sa_family != AF_INET6) {
  11955. return 0;
  11956. }
  11957. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11958. /* IPv6 format */
  11959. for (i = 0; i < 16; i++) {
  11960. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11961. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11962. uint8_t mask = 0;
  11963. if (8 * i + 8 < slash) {
  11964. mask = 0xFFu;
  11965. } else if (8 * i < slash) {
  11966. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11967. }
  11968. if ((ip & mask) != net) {
  11969. return 0;
  11970. }
  11971. }
  11972. return 1;
  11973. }
  11974. }
  11975. }
  11976. }
  11977. #else
  11978. (void)no_strict;
  11979. #endif
  11980. /* malformed */
  11981. return -1;
  11982. }
  11983. static int
  11984. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11985. {
  11986. int throttle = 0;
  11987. struct vec vec, val;
  11988. char mult;
  11989. double v;
  11990. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11991. mult = ',';
  11992. if ((val.ptr == NULL)
  11993. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11994. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11995. // to an integer value, but function will not report
  11996. // conversion errors; consider using 'strtol' instead
  11997. || (v < 0)
  11998. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11999. && (mult != ','))) {
  12000. continue;
  12001. }
  12002. v *= (lowercase(&mult) == 'k')
  12003. ? 1024
  12004. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12005. if (vec.len == 1 && vec.ptr[0] == '*') {
  12006. throttle = (int)v;
  12007. } else {
  12008. int matched = parse_match_net(&vec, rsa, 0);
  12009. if (matched >= 0) {
  12010. /* a valid IP subnet */
  12011. if (matched) {
  12012. throttle = (int)v;
  12013. }
  12014. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12015. throttle = (int)v;
  12016. }
  12017. }
  12018. }
  12019. return throttle;
  12020. }
  12021. /* The mg_upload function is superseeded by mg_handle_form_request. */
  12022. #include "handle_form.inl"
  12023. static int
  12024. get_first_ssl_listener_index(const struct mg_context *ctx)
  12025. {
  12026. unsigned int i;
  12027. int idx = -1;
  12028. if (ctx) {
  12029. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12030. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12031. }
  12032. }
  12033. return idx;
  12034. }
  12035. /* Return host (without port) */
  12036. static void
  12037. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12038. {
  12039. const char *host_header =
  12040. get_header(ri->http_headers, ri->num_headers, "Host");
  12041. host->ptr = NULL;
  12042. host->len = 0;
  12043. if (host_header != NULL) {
  12044. const char *pos;
  12045. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12046. * is found. */
  12047. if (*host_header == '[') {
  12048. pos = strchr(host_header, ']');
  12049. if (!pos) {
  12050. /* Malformed hostname starts with '[', but no ']' found */
  12051. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12052. return;
  12053. }
  12054. /* terminate after ']' */
  12055. host->ptr = host_header;
  12056. host->len = (size_t)(pos + 1 - host_header);
  12057. } else {
  12058. /* Otherwise, a ':' separates hostname and port number */
  12059. pos = strchr(host_header, ':');
  12060. if (pos != NULL) {
  12061. host->len = (size_t)(pos - host_header);
  12062. } else {
  12063. host->len = strlen(host_header);
  12064. }
  12065. host->ptr = host_header;
  12066. }
  12067. }
  12068. }
  12069. static int
  12070. switch_domain_context(struct mg_connection *conn)
  12071. {
  12072. struct vec host;
  12073. get_host_from_request_info(&host, &conn->request_info);
  12074. if (host.ptr) {
  12075. if (conn->ssl) {
  12076. /* This is a HTTPS connection, maybe we have a hostname
  12077. * from SNI (set in ssl_servername_callback). */
  12078. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12079. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12080. /* We are not using the default domain */
  12081. if ((strlen(sslhost) != host.len)
  12082. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12083. /* Mismatch between SNI domain and HTTP domain */
  12084. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12085. sslhost,
  12086. (int)host.len,
  12087. host.ptr);
  12088. return 0;
  12089. }
  12090. }
  12091. } else {
  12092. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12093. while (dom) {
  12094. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12095. size_t domNameLen = strlen(domName);
  12096. if ((domNameLen == host.len)
  12097. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12098. /* Found matching domain */
  12099. DEBUG_TRACE("HTTP domain %s found",
  12100. dom->config[AUTHENTICATION_DOMAIN]);
  12101. /* TODO: Check if this is a HTTP or HTTPS domain */
  12102. conn->dom_ctx = dom;
  12103. break;
  12104. }
  12105. mg_lock_context(conn->phys_ctx);
  12106. dom = dom->next;
  12107. mg_unlock_context(conn->phys_ctx);
  12108. }
  12109. }
  12110. DEBUG_TRACE("HTTP%s Host: %.*s",
  12111. conn->ssl ? "S" : "",
  12112. (int)host.len,
  12113. host.ptr);
  12114. } else {
  12115. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12116. return 1;
  12117. }
  12118. return 1;
  12119. }
  12120. static void
  12121. redirect_to_https_port(struct mg_connection *conn, int port)
  12122. {
  12123. char target_url[MG_BUF_LEN];
  12124. int truncated = 0;
  12125. const char *expect_proto =
  12126. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12127. /* Use "308 Permanent Redirect" */
  12128. int redirect_code = 308;
  12129. /* In any case, close the current connection */
  12130. conn->must_close = 1;
  12131. /* Send host, port, uri and (if it exists) ?query_string */
  12132. if (mg_construct_local_link(
  12133. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12134. < 0) {
  12135. truncated = 1;
  12136. } else if (conn->request_info.query_string != NULL) {
  12137. size_t slen1 = strlen(target_url);
  12138. size_t slen2 = strlen(conn->request_info.query_string);
  12139. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12140. target_url[slen1] = '?';
  12141. memcpy(target_url + slen1 + 1,
  12142. conn->request_info.query_string,
  12143. slen2);
  12144. target_url[slen1 + slen2 + 1] = 0;
  12145. } else {
  12146. truncated = 1;
  12147. }
  12148. }
  12149. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12150. * is used as buffer size) */
  12151. if (truncated) {
  12152. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12153. return;
  12154. }
  12155. /* Use redirect helper function */
  12156. mg_send_http_redirect(conn, target_url, redirect_code);
  12157. }
  12158. static void
  12159. mg_set_handler_type(struct mg_context *phys_ctx,
  12160. struct mg_domain_context *dom_ctx,
  12161. const char *uri,
  12162. int handler_type,
  12163. int is_delete_request,
  12164. mg_request_handler handler,
  12165. struct mg_websocket_subprotocols *subprotocols,
  12166. mg_websocket_connect_handler connect_handler,
  12167. mg_websocket_ready_handler ready_handler,
  12168. mg_websocket_data_handler data_handler,
  12169. mg_websocket_close_handler close_handler,
  12170. mg_authorization_handler auth_handler,
  12171. void *cbdata)
  12172. {
  12173. struct mg_handler_info *tmp_rh, **lastref;
  12174. size_t urilen = strlen(uri);
  12175. if (handler_type == WEBSOCKET_HANDLER) {
  12176. DEBUG_ASSERT(handler == NULL);
  12177. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12178. || ready_handler != NULL || data_handler != NULL
  12179. || close_handler != NULL);
  12180. DEBUG_ASSERT(auth_handler == NULL);
  12181. if (handler != NULL) {
  12182. return;
  12183. }
  12184. if (!is_delete_request && (connect_handler == NULL)
  12185. && (ready_handler == NULL) && (data_handler == NULL)
  12186. && (close_handler == NULL)) {
  12187. return;
  12188. }
  12189. if (auth_handler != NULL) {
  12190. return;
  12191. }
  12192. } else if (handler_type == REQUEST_HANDLER) {
  12193. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12194. && data_handler == NULL && close_handler == NULL);
  12195. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12196. DEBUG_ASSERT(auth_handler == NULL);
  12197. if ((connect_handler != NULL) || (ready_handler != NULL)
  12198. || (data_handler != NULL) || (close_handler != NULL)) {
  12199. return;
  12200. }
  12201. if (!is_delete_request && (handler == NULL)) {
  12202. return;
  12203. }
  12204. if (auth_handler != NULL) {
  12205. return;
  12206. }
  12207. } else if (handler_type == AUTH_HANDLER) {
  12208. DEBUG_ASSERT(handler == NULL);
  12209. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12210. && data_handler == NULL && close_handler == NULL);
  12211. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12212. if (handler != NULL) {
  12213. return;
  12214. }
  12215. if ((connect_handler != NULL) || (ready_handler != NULL)
  12216. || (data_handler != NULL) || (close_handler != NULL)) {
  12217. return;
  12218. }
  12219. if (!is_delete_request && (auth_handler == NULL)) {
  12220. return;
  12221. }
  12222. } else {
  12223. /* Unknown handler type. */
  12224. return;
  12225. }
  12226. if (!phys_ctx || !dom_ctx) {
  12227. /* no context available */
  12228. return;
  12229. }
  12230. mg_lock_context(phys_ctx);
  12231. /* first try to find an existing handler */
  12232. do {
  12233. lastref = &(dom_ctx->handlers);
  12234. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12235. tmp_rh = tmp_rh->next) {
  12236. if (tmp_rh->handler_type == handler_type
  12237. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12238. if (!is_delete_request) {
  12239. /* update existing handler */
  12240. if (handler_type == REQUEST_HANDLER) {
  12241. /* Wait for end of use before updating */
  12242. if (tmp_rh->refcount) {
  12243. mg_unlock_context(phys_ctx);
  12244. mg_sleep(1);
  12245. mg_lock_context(phys_ctx);
  12246. /* tmp_rh might have been freed, search again. */
  12247. break;
  12248. }
  12249. /* Ok, the handler is no more use -> Update it */
  12250. tmp_rh->handler = handler;
  12251. } else if (handler_type == WEBSOCKET_HANDLER) {
  12252. tmp_rh->subprotocols = subprotocols;
  12253. tmp_rh->connect_handler = connect_handler;
  12254. tmp_rh->ready_handler = ready_handler;
  12255. tmp_rh->data_handler = data_handler;
  12256. tmp_rh->close_handler = close_handler;
  12257. } else { /* AUTH_HANDLER */
  12258. tmp_rh->auth_handler = auth_handler;
  12259. }
  12260. tmp_rh->cbdata = cbdata;
  12261. } else {
  12262. /* remove existing handler */
  12263. if (handler_type == REQUEST_HANDLER) {
  12264. /* Wait for end of use before removing */
  12265. if (tmp_rh->refcount) {
  12266. tmp_rh->removing = 1;
  12267. mg_unlock_context(phys_ctx);
  12268. mg_sleep(1);
  12269. mg_lock_context(phys_ctx);
  12270. /* tmp_rh might have been freed, search again. */
  12271. break;
  12272. }
  12273. /* Ok, the handler is no more used */
  12274. }
  12275. *lastref = tmp_rh->next;
  12276. mg_free(tmp_rh->uri);
  12277. mg_free(tmp_rh);
  12278. }
  12279. mg_unlock_context(phys_ctx);
  12280. return;
  12281. }
  12282. lastref = &(tmp_rh->next);
  12283. }
  12284. } while (tmp_rh != NULL);
  12285. if (is_delete_request) {
  12286. /* no handler to set, this was a remove request to a non-existing
  12287. * handler */
  12288. mg_unlock_context(phys_ctx);
  12289. return;
  12290. }
  12291. tmp_rh =
  12292. (struct mg_handler_info *)mg_calloc_ctx(1,
  12293. sizeof(struct mg_handler_info),
  12294. phys_ctx);
  12295. if (tmp_rh == NULL) {
  12296. mg_unlock_context(phys_ctx);
  12297. mg_cry_ctx_internal(phys_ctx,
  12298. "%s",
  12299. "Cannot create new request handler struct, OOM");
  12300. return;
  12301. }
  12302. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12303. if (!tmp_rh->uri) {
  12304. mg_unlock_context(phys_ctx);
  12305. mg_free(tmp_rh);
  12306. mg_cry_ctx_internal(phys_ctx,
  12307. "%s",
  12308. "Cannot create new request handler struct, OOM");
  12309. return;
  12310. }
  12311. tmp_rh->uri_len = urilen;
  12312. if (handler_type == REQUEST_HANDLER) {
  12313. tmp_rh->refcount = 0;
  12314. tmp_rh->removing = 0;
  12315. tmp_rh->handler = handler;
  12316. } else if (handler_type == WEBSOCKET_HANDLER) {
  12317. tmp_rh->subprotocols = subprotocols;
  12318. tmp_rh->connect_handler = connect_handler;
  12319. tmp_rh->ready_handler = ready_handler;
  12320. tmp_rh->data_handler = data_handler;
  12321. tmp_rh->close_handler = close_handler;
  12322. } else { /* AUTH_HANDLER */
  12323. tmp_rh->auth_handler = auth_handler;
  12324. }
  12325. tmp_rh->cbdata = cbdata;
  12326. tmp_rh->handler_type = handler_type;
  12327. tmp_rh->next = NULL;
  12328. *lastref = tmp_rh;
  12329. mg_unlock_context(phys_ctx);
  12330. }
  12331. void
  12332. mg_set_request_handler(struct mg_context *ctx,
  12333. const char *uri,
  12334. mg_request_handler handler,
  12335. void *cbdata)
  12336. {
  12337. mg_set_handler_type(ctx,
  12338. &(ctx->dd),
  12339. uri,
  12340. REQUEST_HANDLER,
  12341. handler == NULL,
  12342. handler,
  12343. NULL,
  12344. NULL,
  12345. NULL,
  12346. NULL,
  12347. NULL,
  12348. NULL,
  12349. cbdata);
  12350. }
  12351. void
  12352. mg_set_websocket_handler(struct mg_context *ctx,
  12353. const char *uri,
  12354. mg_websocket_connect_handler connect_handler,
  12355. mg_websocket_ready_handler ready_handler,
  12356. mg_websocket_data_handler data_handler,
  12357. mg_websocket_close_handler close_handler,
  12358. void *cbdata)
  12359. {
  12360. mg_set_websocket_handler_with_subprotocols(ctx,
  12361. uri,
  12362. NULL,
  12363. connect_handler,
  12364. ready_handler,
  12365. data_handler,
  12366. close_handler,
  12367. cbdata);
  12368. }
  12369. void
  12370. mg_set_websocket_handler_with_subprotocols(
  12371. struct mg_context *ctx,
  12372. const char *uri,
  12373. struct mg_websocket_subprotocols *subprotocols,
  12374. mg_websocket_connect_handler connect_handler,
  12375. mg_websocket_ready_handler ready_handler,
  12376. mg_websocket_data_handler data_handler,
  12377. mg_websocket_close_handler close_handler,
  12378. void *cbdata)
  12379. {
  12380. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12381. && (data_handler == NULL)
  12382. && (close_handler == NULL);
  12383. mg_set_handler_type(ctx,
  12384. &(ctx->dd),
  12385. uri,
  12386. WEBSOCKET_HANDLER,
  12387. is_delete_request,
  12388. NULL,
  12389. subprotocols,
  12390. connect_handler,
  12391. ready_handler,
  12392. data_handler,
  12393. close_handler,
  12394. NULL,
  12395. cbdata);
  12396. }
  12397. void
  12398. mg_set_auth_handler(struct mg_context *ctx,
  12399. const char *uri,
  12400. mg_authorization_handler handler,
  12401. void *cbdata)
  12402. {
  12403. mg_set_handler_type(ctx,
  12404. &(ctx->dd),
  12405. uri,
  12406. AUTH_HANDLER,
  12407. handler == NULL,
  12408. NULL,
  12409. NULL,
  12410. NULL,
  12411. NULL,
  12412. NULL,
  12413. NULL,
  12414. handler,
  12415. cbdata);
  12416. }
  12417. static int
  12418. get_request_handler(struct mg_connection *conn,
  12419. int handler_type,
  12420. mg_request_handler *handler,
  12421. struct mg_websocket_subprotocols **subprotocols,
  12422. mg_websocket_connect_handler *connect_handler,
  12423. mg_websocket_ready_handler *ready_handler,
  12424. mg_websocket_data_handler *data_handler,
  12425. mg_websocket_close_handler *close_handler,
  12426. mg_authorization_handler *auth_handler,
  12427. void **cbdata,
  12428. struct mg_handler_info **handler_info)
  12429. {
  12430. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12431. if (request_info) {
  12432. const char *uri = request_info->local_uri;
  12433. size_t urilen = strlen(uri);
  12434. struct mg_handler_info *tmp_rh;
  12435. int step, matched;
  12436. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12437. return 0;
  12438. }
  12439. mg_lock_context(conn->phys_ctx);
  12440. for (step = 0; step < 3; step++) {
  12441. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12442. tmp_rh = tmp_rh->next) {
  12443. if (tmp_rh->handler_type != handler_type) {
  12444. continue;
  12445. }
  12446. if (step == 0) {
  12447. /* first try for an exact match */
  12448. matched = (tmp_rh->uri_len == urilen)
  12449. && (strcmp(tmp_rh->uri, uri) == 0);
  12450. } else if (step == 1) {
  12451. /* next try for a partial match, we will accept
  12452. uri/something */
  12453. matched =
  12454. (tmp_rh->uri_len < urilen)
  12455. && (uri[tmp_rh->uri_len] == '/')
  12456. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12457. } else {
  12458. /* finally try for pattern match */
  12459. matched =
  12460. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12461. }
  12462. if (matched) {
  12463. if (handler_type == WEBSOCKET_HANDLER) {
  12464. *subprotocols = tmp_rh->subprotocols;
  12465. *connect_handler = tmp_rh->connect_handler;
  12466. *ready_handler = tmp_rh->ready_handler;
  12467. *data_handler = tmp_rh->data_handler;
  12468. *close_handler = tmp_rh->close_handler;
  12469. } else if (handler_type == REQUEST_HANDLER) {
  12470. if (tmp_rh->removing) {
  12471. /* Treat as none found */
  12472. step = 2;
  12473. break;
  12474. }
  12475. *handler = tmp_rh->handler;
  12476. /* Acquire handler and give it back */
  12477. tmp_rh->refcount++;
  12478. *handler_info = tmp_rh;
  12479. } else { /* AUTH_HANDLER */
  12480. *auth_handler = tmp_rh->auth_handler;
  12481. }
  12482. *cbdata = tmp_rh->cbdata;
  12483. mg_unlock_context(conn->phys_ctx);
  12484. return 1;
  12485. }
  12486. }
  12487. }
  12488. mg_unlock_context(conn->phys_ctx);
  12489. }
  12490. return 0; /* none found */
  12491. }
  12492. /* Check if the script file is in a path, allowed for script files.
  12493. * This can be used if uploading files is possible not only for the server
  12494. * admin, and the upload mechanism does not check the file extension.
  12495. */
  12496. static int
  12497. is_in_script_path(const struct mg_connection *conn, const char *path)
  12498. {
  12499. /* TODO (Feature): Add config value for allowed script path.
  12500. * Default: All allowed. */
  12501. (void)conn;
  12502. (void)path;
  12503. return 1;
  12504. }
  12505. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12506. static int
  12507. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12508. int bits,
  12509. char *data,
  12510. size_t len,
  12511. void *cbdata)
  12512. {
  12513. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12514. if (pcallbacks->websocket_data) {
  12515. return pcallbacks->websocket_data(conn, bits, data, len);
  12516. }
  12517. /* No handler set - assume "OK" */
  12518. return 1;
  12519. }
  12520. static void
  12521. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12522. void *cbdata)
  12523. {
  12524. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12525. if (pcallbacks->connection_close) {
  12526. pcallbacks->connection_close(conn);
  12527. }
  12528. }
  12529. #endif
  12530. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12531. */
  12532. static void
  12533. release_handler_ref(struct mg_connection *conn,
  12534. struct mg_handler_info *handler_info)
  12535. {
  12536. if (handler_info != NULL) {
  12537. /* Use context lock for ref counter */
  12538. mg_lock_context(conn->phys_ctx);
  12539. handler_info->refcount--;
  12540. mg_unlock_context(conn->phys_ctx);
  12541. }
  12542. }
  12543. /* This is the heart of the Civetweb's logic.
  12544. * This function is called when the request is read, parsed and validated,
  12545. * and Civetweb must decide what action to take: serve a file, or
  12546. * a directory, or call embedded function, etcetera. */
  12547. static void
  12548. handle_request(struct mg_connection *conn)
  12549. {
  12550. struct mg_request_info *ri = &conn->request_info;
  12551. char path[UTF8_PATH_MAX];
  12552. int uri_len, ssl_index;
  12553. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12554. is_put_or_delete_request = 0, is_callback_resource = 0,
  12555. is_template_text_file = 0, is_webdav_request = 0;
  12556. int i;
  12557. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12558. mg_request_handler callback_handler = NULL;
  12559. struct mg_handler_info *handler_info = NULL;
  12560. struct mg_websocket_subprotocols *subprotocols;
  12561. mg_websocket_connect_handler ws_connect_handler = NULL;
  12562. mg_websocket_ready_handler ws_ready_handler = NULL;
  12563. mg_websocket_data_handler ws_data_handler = NULL;
  12564. mg_websocket_close_handler ws_close_handler = NULL;
  12565. void *callback_data = NULL;
  12566. mg_authorization_handler auth_handler = NULL;
  12567. void *auth_callback_data = NULL;
  12568. int handler_type;
  12569. time_t curtime = time(NULL);
  12570. char date[64];
  12571. char *tmp;
  12572. path[0] = 0;
  12573. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12574. conn->request_state = 0;
  12575. /* 1. get the request url */
  12576. /* 1.1. split into url and query string */
  12577. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12578. != NULL) {
  12579. *((char *)conn->request_info.query_string++) = '\0';
  12580. }
  12581. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12582. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12583. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12584. if (ssl_index >= 0) {
  12585. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12586. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12587. redirect_to_https_port(conn, port);
  12588. } else {
  12589. /* A http to https forward port has been specified,
  12590. * but no https port to forward to. */
  12591. mg_send_http_error(conn,
  12592. 503,
  12593. "%s",
  12594. "Error: SSL forward not configured properly");
  12595. mg_cry_internal(conn,
  12596. "%s",
  12597. "Can not redirect to SSL, no SSL port available");
  12598. }
  12599. return;
  12600. }
  12601. uri_len = (int)strlen(ri->local_uri);
  12602. /* 1.3. decode url (if config says so) */
  12603. if (should_decode_url(conn)) {
  12604. url_decode_in_place((char *)ri->local_uri);
  12605. }
  12606. /* URL decode the query-string only if explicity set in the configuration */
  12607. if (conn->request_info.query_string) {
  12608. if (should_decode_query_string(conn)) {
  12609. url_decode_in_place((char *)conn->request_info.query_string);
  12610. }
  12611. }
  12612. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12613. * possible. The fact that we cleaned the URI is stored in that the
  12614. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12615. * ri->local_uri_raw still points to memory allocated in
  12616. * worker_thread_run(). ri->local_uri is private to the request so we
  12617. * don't have to use preallocated memory here. */
  12618. tmp = mg_strdup(ri->local_uri_raw);
  12619. if (!tmp) {
  12620. /* Out of memory. We cannot do anything reasonable here. */
  12621. return;
  12622. }
  12623. remove_dot_segments(tmp);
  12624. ri->local_uri = tmp;
  12625. /* step 1. completed, the url is known now */
  12626. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12627. /* 2. if this ip has limited speed, set it for this connection */
  12628. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12629. &conn->client.rsa,
  12630. ri->local_uri);
  12631. /* 3. call a "handle everything" callback, if registered */
  12632. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12633. /* Note that since V1.7 the "begin_request" function is called
  12634. * before an authorization check. If an authorization check is
  12635. * required, use a request_handler instead. */
  12636. i = conn->phys_ctx->callbacks.begin_request(conn);
  12637. if (i > 0) {
  12638. /* callback already processed the request. Store the
  12639. return value as a status code for the access log. */
  12640. conn->status_code = i;
  12641. if (!conn->must_close) {
  12642. discard_unread_request_data(conn);
  12643. }
  12644. DEBUG_TRACE("%s", "begin_request handled request");
  12645. return;
  12646. } else if (i == 0) {
  12647. /* civetweb should process the request */
  12648. } else {
  12649. /* unspecified - may change with the next version */
  12650. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12651. return;
  12652. }
  12653. }
  12654. /* request not yet handled by a handler or redirect, so the request
  12655. * is processed here */
  12656. /* 4. Check for CORS preflight requests and handle them (if configured).
  12657. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12658. */
  12659. if (!strcmp(ri->request_method, "OPTIONS")) {
  12660. /* Send a response to CORS preflights only if
  12661. * access_control_allow_methods is not NULL and not an empty string.
  12662. * In this case, scripts can still handle CORS. */
  12663. const char *cors_meth_cfg =
  12664. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12665. const char *cors_orig_cfg =
  12666. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12667. const char *cors_origin =
  12668. get_header(ri->http_headers, ri->num_headers, "Origin");
  12669. const char *cors_acrm = get_header(ri->http_headers,
  12670. ri->num_headers,
  12671. "Access-Control-Request-Method");
  12672. /* Todo: check if cors_origin is in cors_orig_cfg.
  12673. * Or, let the client check this. */
  12674. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12675. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12676. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12677. /* This is a valid CORS preflight, and the server is configured
  12678. * to handle it automatically. */
  12679. const char *cors_acrh =
  12680. get_header(ri->http_headers,
  12681. ri->num_headers,
  12682. "Access-Control-Request-Headers");
  12683. gmt_time_string(date, sizeof(date), &curtime);
  12684. mg_printf(conn,
  12685. "HTTP/1.1 200 OK\r\n"
  12686. "Date: %s\r\n"
  12687. "Access-Control-Allow-Origin: %s\r\n"
  12688. "Access-Control-Allow-Methods: %s\r\n"
  12689. "Content-Length: 0\r\n"
  12690. "Connection: %s\r\n",
  12691. date,
  12692. cors_orig_cfg,
  12693. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12694. suggest_connection_header(conn));
  12695. if (cors_acrh != NULL) {
  12696. /* CORS request is asking for additional headers */
  12697. const char *cors_hdr_cfg =
  12698. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12699. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12700. /* Allow only if access_control_allow_headers is
  12701. * not NULL and not an empty string. If this
  12702. * configuration is set to *, allow everything.
  12703. * Otherwise this configuration must be a list
  12704. * of allowed HTTP header names. */
  12705. mg_printf(conn,
  12706. "Access-Control-Allow-Headers: %s\r\n",
  12707. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12708. : cors_hdr_cfg));
  12709. }
  12710. }
  12711. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12712. mg_printf(conn, "\r\n");
  12713. DEBUG_TRACE("%s", "OPTIONS done");
  12714. return;
  12715. }
  12716. }
  12717. /* 5. interpret the url to find out how the request must be handled
  12718. */
  12719. /* 5.1. first test, if the request targets the regular http(s)://
  12720. * protocol namespace or the websocket ws(s):// protocol namespace.
  12721. */
  12722. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12723. #if defined(USE_WEBSOCKET)
  12724. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12725. #else
  12726. handler_type = REQUEST_HANDLER;
  12727. #endif /* defined(USE_WEBSOCKET) */
  12728. if (is_websocket_request) {
  12729. HTTP1_only;
  12730. }
  12731. /* 5.2. check if the request will be handled by a callback */
  12732. if (get_request_handler(conn,
  12733. handler_type,
  12734. &callback_handler,
  12735. &subprotocols,
  12736. &ws_connect_handler,
  12737. &ws_ready_handler,
  12738. &ws_data_handler,
  12739. &ws_close_handler,
  12740. NULL,
  12741. &callback_data,
  12742. &handler_info)) {
  12743. /* 5.2.1. A callback will handle this request. All requests
  12744. * handled by a callback have to be considered as requests
  12745. * to a script resource. */
  12746. is_callback_resource = 1;
  12747. is_script_resource = 1;
  12748. is_put_or_delete_request = is_put_or_delete_method(conn);
  12749. /* Never handle a C callback according to File WebDav rules,
  12750. * even if it is a webdav method */
  12751. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12752. } else {
  12753. no_callback_resource:
  12754. /* 5.2.2. No callback is responsible for this request. The URI
  12755. * addresses a file based resource (static content or Lua/cgi
  12756. * scripts in the file system). */
  12757. is_callback_resource = 0;
  12758. interpret_uri(conn,
  12759. path,
  12760. sizeof(path),
  12761. &file.stat,
  12762. &is_found,
  12763. &is_script_resource,
  12764. &is_websocket_request,
  12765. &is_put_or_delete_request,
  12766. &is_webdav_request,
  12767. &is_template_text_file);
  12768. }
  12769. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12770. if (is_webdav_request) {
  12771. /* TODO: Do we need a config option? */
  12772. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12773. if (webdav_enable[0] != 'y') {
  12774. mg_send_http_error(conn,
  12775. 405,
  12776. "%s method not allowed",
  12777. conn->request_info.request_method);
  12778. DEBUG_TRACE("%s", "webdav rejected");
  12779. return;
  12780. }
  12781. }
  12782. /* 6. authorization check */
  12783. /* 6.1. a custom authorization handler is installed */
  12784. if (get_request_handler(conn,
  12785. AUTH_HANDLER,
  12786. NULL,
  12787. NULL,
  12788. NULL,
  12789. NULL,
  12790. NULL,
  12791. NULL,
  12792. &auth_handler,
  12793. &auth_callback_data,
  12794. NULL)) {
  12795. if (!auth_handler(conn, auth_callback_data)) {
  12796. /* Callback handler will not be used anymore. Release it */
  12797. release_handler_ref(conn, handler_info);
  12798. DEBUG_TRACE("%s", "auth handler rejected request");
  12799. return;
  12800. }
  12801. } else if (is_put_or_delete_request && !is_script_resource
  12802. && !is_callback_resource) {
  12803. HTTP1_only;
  12804. /* 6.2. this request is a PUT/DELETE to a real file */
  12805. /* 6.2.1. thus, the server must have real files */
  12806. #if defined(NO_FILES)
  12807. if (1) {
  12808. #else
  12809. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12810. #endif
  12811. /* This code path will not be called for request handlers */
  12812. DEBUG_ASSERT(handler_info == NULL);
  12813. /* This server does not have any real files, thus the
  12814. * PUT/DELETE methods are not valid. */
  12815. mg_send_http_error(conn,
  12816. 405,
  12817. "%s method not allowed",
  12818. conn->request_info.request_method);
  12819. DEBUG_TRACE("%s", "all file based requests rejected");
  12820. return;
  12821. }
  12822. #if !defined(NO_FILES)
  12823. /* 6.2.2. Check if put authorization for static files is
  12824. * available.
  12825. */
  12826. if (!is_authorized_for_put(conn)) {
  12827. send_authorization_request(conn, NULL);
  12828. DEBUG_TRACE("%s", "file write needs authorization");
  12829. return;
  12830. }
  12831. #endif
  12832. } else {
  12833. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12834. * or it is a PUT or DELETE request to a resource that does not
  12835. * correspond to a file. Check authorization. */
  12836. if (!check_authorization(conn, path)) {
  12837. send_authorization_request(conn, NULL);
  12838. /* Callback handler will not be used anymore. Release it */
  12839. release_handler_ref(conn, handler_info);
  12840. DEBUG_TRACE("%s", "access authorization required");
  12841. return;
  12842. }
  12843. }
  12844. /* request is authorized or does not need authorization */
  12845. /* 7. check if there are request handlers for this uri */
  12846. if (is_callback_resource) {
  12847. HTTP1_only;
  12848. if (!is_websocket_request) {
  12849. i = callback_handler(conn, callback_data);
  12850. /* Callback handler will not be used anymore. Release it */
  12851. release_handler_ref(conn, handler_info);
  12852. if (i > 0) {
  12853. /* Do nothing, callback has served the request. Store
  12854. * then return value as status code for the log and discard
  12855. * all data from the client not used by the callback. */
  12856. conn->status_code = i;
  12857. if (!conn->must_close) {
  12858. discard_unread_request_data(conn);
  12859. }
  12860. } else {
  12861. /* The handler did NOT handle the request. */
  12862. /* Some proper reactions would be:
  12863. * a) close the connections without sending anything
  12864. * b) send a 404 not found
  12865. * c) try if there is a file matching the URI
  12866. * It would be possible to do a, b or c in the callback
  12867. * implementation, and return 1 - we cannot do anything
  12868. * here, that is not possible in the callback.
  12869. *
  12870. * TODO: What would be the best reaction here?
  12871. * (Note: The reaction may change, if there is a better
  12872. * idea.)
  12873. */
  12874. /* For the moment, use option c: We look for a proper file,
  12875. * but since a file request is not always a script resource,
  12876. * the authorization check might be different. */
  12877. callback_handler = NULL;
  12878. /* Here we are at a dead end:
  12879. * According to URI matching, a callback should be
  12880. * responsible for handling the request,
  12881. * we called it, but the callback declared itself
  12882. * not responsible.
  12883. * We use a goto here, to get out of this dead end,
  12884. * and continue with the default handling.
  12885. * A goto here is simpler and better to understand
  12886. * than some curious loop. */
  12887. goto no_callback_resource;
  12888. }
  12889. } else {
  12890. #if defined(USE_WEBSOCKET)
  12891. handle_websocket_request(conn,
  12892. path,
  12893. is_callback_resource,
  12894. subprotocols,
  12895. ws_connect_handler,
  12896. ws_ready_handler,
  12897. ws_data_handler,
  12898. ws_close_handler,
  12899. callback_data);
  12900. #endif
  12901. }
  12902. DEBUG_TRACE("%s", "websocket handling done");
  12903. return;
  12904. }
  12905. /* 8. handle websocket requests */
  12906. #if defined(USE_WEBSOCKET)
  12907. if (is_websocket_request) {
  12908. HTTP1_only;
  12909. if (is_script_resource) {
  12910. if (is_in_script_path(conn, path)) {
  12911. /* Websocket Lua script */
  12912. handle_websocket_request(conn,
  12913. path,
  12914. 0 /* Lua Script */,
  12915. NULL,
  12916. NULL,
  12917. NULL,
  12918. NULL,
  12919. NULL,
  12920. conn->phys_ctx->user_data);
  12921. } else {
  12922. /* Script was in an illegal path */
  12923. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12924. }
  12925. } else {
  12926. mg_send_http_error(conn, 404, "%s", "Not found");
  12927. }
  12928. DEBUG_TRACE("%s", "websocket script done");
  12929. return;
  12930. } else
  12931. #endif
  12932. #if defined(NO_FILES)
  12933. /* 9a. In case the server uses only callbacks, this uri is
  12934. * unknown.
  12935. * Then, all request handling ends here. */
  12936. mg_send_http_error(conn, 404, "%s", "Not Found");
  12937. #else
  12938. /* 9b. This request is either for a static file or resource handled
  12939. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12940. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12941. mg_send_http_error(conn, 404, "%s", "Not Found");
  12942. DEBUG_TRACE("%s", "no document root available");
  12943. return;
  12944. }
  12945. /* 10. Request is handled by a script */
  12946. if (is_script_resource) {
  12947. HTTP1_only;
  12948. handle_file_based_request(conn, path, &file);
  12949. DEBUG_TRACE("%s", "script handling done");
  12950. return;
  12951. }
  12952. /* Request was not handled by a callback or script. It will be
  12953. * handled by a server internal method. */
  12954. /* 11. Handle put/delete/mkcol requests */
  12955. if (is_put_or_delete_request) {
  12956. HTTP1_only;
  12957. /* 11.1. PUT method */
  12958. if (!strcmp(ri->request_method, "PUT")) {
  12959. put_file(conn, path);
  12960. DEBUG_TRACE("handling %s request to %s done",
  12961. ri->request_method,
  12962. path);
  12963. return;
  12964. }
  12965. /* 11.2. DELETE method */
  12966. if (!strcmp(ri->request_method, "DELETE")) {
  12967. delete_file(conn, path);
  12968. DEBUG_TRACE("handling %s request to %s done",
  12969. ri->request_method,
  12970. path);
  12971. return;
  12972. }
  12973. /* 11.3. MKCOL method */
  12974. if (!strcmp(ri->request_method, "MKCOL")) {
  12975. dav_mkcol(conn, path);
  12976. DEBUG_TRACE("handling %s request to %s done",
  12977. ri->request_method,
  12978. path);
  12979. return;
  12980. }
  12981. /* 11.4. MOVE method */
  12982. if (!strcmp(ri->request_method, "MOVE")) {
  12983. dav_move_file(conn, path, 0);
  12984. DEBUG_TRACE("handling %s request to %s done",
  12985. ri->request_method,
  12986. path);
  12987. return;
  12988. }
  12989. if (!strcmp(ri->request_method, "COPY")) {
  12990. dav_move_file(conn, path, 1);
  12991. DEBUG_TRACE("handling %s request to %s done",
  12992. ri->request_method,
  12993. path);
  12994. return;
  12995. }
  12996. /* 11.5. LOCK method */
  12997. if (!strcmp(ri->request_method, "LOCK")) {
  12998. dav_lock_file(conn, path);
  12999. DEBUG_TRACE("handling %s request to %s done",
  13000. ri->request_method,
  13001. path);
  13002. return;
  13003. }
  13004. /* 11.6. UNLOCK method */
  13005. if (!strcmp(ri->request_method, "UNLOCK")) {
  13006. dav_unlock_file(conn, path);
  13007. DEBUG_TRACE("handling %s request to %s done",
  13008. ri->request_method,
  13009. path);
  13010. return;
  13011. }
  13012. /* 11.7. PROPPATCH method */
  13013. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13014. dav_proppatch(conn, path);
  13015. DEBUG_TRACE("handling %s request to %s done",
  13016. ri->request_method,
  13017. path);
  13018. return;
  13019. }
  13020. /* 11.8. Other methods, e.g.: PATCH
  13021. * This method is not supported for static resources,
  13022. * only for scripts (Lua, CGI) and callbacks. */
  13023. mg_send_http_error(conn,
  13024. 405,
  13025. "%s method not allowed",
  13026. conn->request_info.request_method);
  13027. DEBUG_TRACE("method %s on %s is not supported",
  13028. ri->request_method,
  13029. path);
  13030. return;
  13031. }
  13032. /* 11. File does not exist, or it was configured that it should be
  13033. * hidden */
  13034. if (!is_found || (must_hide_file(conn, path))) {
  13035. mg_send_http_error(conn, 404, "%s", "Not found");
  13036. DEBUG_TRACE("handling %s request to %s: file not found",
  13037. ri->request_method,
  13038. path);
  13039. return;
  13040. }
  13041. /* 12. Directory uris should end with a slash */
  13042. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13043. && (ri->local_uri[uri_len - 1] != '/')) {
  13044. /* Path + server root */
  13045. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13046. if (ri->query_string) {
  13047. buflen += strlen(ri->query_string);
  13048. }
  13049. char *new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13050. if (!new_path) {
  13051. mg_send_http_error(conn, 500, "out or memory");
  13052. } else {
  13053. mg_get_request_link(conn, new_path, buflen - 1);
  13054. strcat(new_path, "/");
  13055. if (ri->query_string) {
  13056. /* Append ? and query string */
  13057. strcat(new_path, "?");
  13058. strcat(new_path, ri->query_string);
  13059. }
  13060. mg_send_http_redirect(conn, new_path, 301);
  13061. mg_free(new_path);
  13062. }
  13063. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13064. ri->request_method,
  13065. path);
  13066. return;
  13067. }
  13068. /* 13. Handle other methods than GET/HEAD */
  13069. /* 13.1. Handle PROPFIND */
  13070. if (!strcmp(ri->request_method, "PROPFIND")) {
  13071. handle_propfind(conn, path, &file.stat);
  13072. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13073. return;
  13074. }
  13075. /* 13.2. Handle OPTIONS for files */
  13076. if (!strcmp(ri->request_method, "OPTIONS")) {
  13077. /* This standard handler is only used for real files.
  13078. * Scripts should support the OPTIONS method themselves, to allow a
  13079. * maximum flexibility.
  13080. * Lua and CGI scripts may fully support CORS this way (including
  13081. * preflights). */
  13082. send_options(conn);
  13083. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13084. return;
  13085. }
  13086. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13087. if ((0 != strcmp(ri->request_method, "GET"))
  13088. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13089. mg_send_http_error(conn,
  13090. 405,
  13091. "%s method not allowed",
  13092. conn->request_info.request_method);
  13093. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13094. return;
  13095. }
  13096. /* 14. directories */
  13097. if (file.stat.is_directory) {
  13098. /* Substitute files have already been handled above. */
  13099. /* Here we can either generate and send a directory listing,
  13100. * or send an "access denied" error. */
  13101. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13102. "yes")) {
  13103. handle_directory_request(conn, path);
  13104. } else {
  13105. mg_send_http_error(conn,
  13106. 403,
  13107. "%s",
  13108. "Error: Directory listing denied");
  13109. }
  13110. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13111. return;
  13112. }
  13113. /* 15. Files with search/replace patterns: LSP and SSI */
  13114. if (is_template_text_file) {
  13115. HTTP1_only;
  13116. handle_file_based_request(conn, path, &file);
  13117. DEBUG_TRACE("handling %s request to %s done (template)",
  13118. ri->request_method,
  13119. path);
  13120. return;
  13121. }
  13122. /* 16. Static file - maybe cached */
  13123. #if !defined(NO_CACHING)
  13124. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13125. /* Send 304 "Not Modified" - this must not send any body data */
  13126. handle_not_modified_static_file_request(conn, &file);
  13127. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13128. ri->request_method,
  13129. path);
  13130. return;
  13131. }
  13132. #endif /* !NO_CACHING */
  13133. /* 17. Static file - not cached */
  13134. handle_static_file_request(conn, path, &file, NULL, NULL);
  13135. DEBUG_TRACE("handling %s request to %s done (static)",
  13136. ri->request_method,
  13137. path);
  13138. #endif /* !defined(NO_FILES) */
  13139. }
  13140. #if !defined(NO_FILESYSTEMS)
  13141. static void
  13142. handle_file_based_request(struct mg_connection *conn,
  13143. const char *path,
  13144. struct mg_file *file)
  13145. {
  13146. #if !defined(NO_CGI)
  13147. unsigned char cgi_config_idx, inc, max;
  13148. #endif
  13149. if (!conn || !conn->dom_ctx) {
  13150. return;
  13151. }
  13152. #if defined(USE_LUA)
  13153. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13154. path)
  13155. > 0) {
  13156. if (is_in_script_path(conn, path)) {
  13157. /* Lua server page: an SSI like page containing mostly plain
  13158. * html code plus some tags with server generated contents. */
  13159. handle_lsp_request(conn, path, file, NULL);
  13160. } else {
  13161. /* Script was in an illegal path */
  13162. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13163. }
  13164. return;
  13165. }
  13166. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13167. > 0) {
  13168. if (is_in_script_path(conn, path)) {
  13169. /* Lua in-server module script: a CGI like script used to
  13170. * generate the entire reply. */
  13171. mg_exec_lua_script(conn, path, NULL);
  13172. } else {
  13173. /* Script was in an illegal path */
  13174. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13175. }
  13176. return;
  13177. }
  13178. #endif
  13179. #if defined(USE_DUKTAPE)
  13180. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13181. path)
  13182. > 0) {
  13183. if (is_in_script_path(conn, path)) {
  13184. /* Call duktape to generate the page */
  13185. mg_exec_duktape_script(conn, path);
  13186. } else {
  13187. /* Script was in an illegal path */
  13188. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13189. }
  13190. return;
  13191. }
  13192. #endif
  13193. #if !defined(NO_CGI)
  13194. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13195. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13196. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13197. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13198. if (match_prefix_strlen(
  13199. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13200. path)
  13201. > 0) {
  13202. if (is_in_script_path(conn, path)) {
  13203. /* CGI scripts may support all HTTP methods */
  13204. handle_cgi_request(conn, path, cgi_config_idx);
  13205. } else {
  13206. /* Script was in an illegal path */
  13207. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13208. }
  13209. return;
  13210. }
  13211. }
  13212. }
  13213. #endif /* !NO_CGI */
  13214. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13215. if (is_in_script_path(conn, path)) {
  13216. handle_ssi_file_request(conn, path, file);
  13217. } else {
  13218. /* Script was in an illegal path */
  13219. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13220. }
  13221. return;
  13222. }
  13223. #if !defined(NO_CACHING)
  13224. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13225. /* Send 304 "Not Modified" - this must not send any body data */
  13226. handle_not_modified_static_file_request(conn, file);
  13227. return;
  13228. }
  13229. #endif /* !NO_CACHING */
  13230. handle_static_file_request(conn, path, file, NULL, NULL);
  13231. }
  13232. #endif /* NO_FILESYSTEMS */
  13233. static void
  13234. close_all_listening_sockets(struct mg_context *ctx)
  13235. {
  13236. unsigned int i;
  13237. if (!ctx) {
  13238. return;
  13239. }
  13240. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13241. closesocket(ctx->listening_sockets[i].sock);
  13242. #if defined(USE_X_DOM_SOCKET)
  13243. /* For unix domain sockets, the socket name represents a file that has
  13244. * to be deleted. */
  13245. /* See
  13246. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13247. */
  13248. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13249. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13250. IGNORE_UNUSED_RESULT(
  13251. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13252. }
  13253. #endif
  13254. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13255. }
  13256. mg_free(ctx->listening_sockets);
  13257. ctx->listening_sockets = NULL;
  13258. mg_free(ctx->listening_socket_fds);
  13259. ctx->listening_socket_fds = NULL;
  13260. }
  13261. /* Valid listening port specification is: [ip_address:]port[s]
  13262. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13263. * Examples for IPv6: [::]:80, [::1]:80,
  13264. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13265. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13266. * In order to bind to both, IPv4 and IPv6, you can either add
  13267. * both ports using 8080,[::]:8080, or the short form +8080.
  13268. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13269. * one only accepting IPv4 the other only IPv6. +8080 creates
  13270. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13271. * environment, they might work differently, or might not work
  13272. * at all - it must be tested what options work best in the
  13273. * relevant network environment.
  13274. */
  13275. static int
  13276. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13277. {
  13278. unsigned int a, b, c, d;
  13279. unsigned port;
  13280. unsigned long portUL;
  13281. int ch, len;
  13282. const char *cb;
  13283. char *endptr;
  13284. #if defined(USE_IPV6)
  13285. char buf[100] = {0};
  13286. #endif
  13287. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13288. * Also, all-zeroes in the socket address means binding to all addresses
  13289. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13290. memset(so, 0, sizeof(*so));
  13291. so->lsa.sin.sin_family = AF_INET;
  13292. *ip_version = 0;
  13293. /* Initialize len as invalid. */
  13294. port = 0;
  13295. len = 0;
  13296. /* Test for different ways to format this string */
  13297. if (sscanf(vec->ptr,
  13298. "%u.%u.%u.%u:%u%n",
  13299. &a,
  13300. &b,
  13301. &c,
  13302. &d,
  13303. &port,
  13304. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13305. // to an integer value, but function will not report
  13306. // conversion errors; consider using 'strtol' instead
  13307. == 5) {
  13308. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13309. so->lsa.sin.sin_addr.s_addr =
  13310. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13311. so->lsa.sin.sin_port = htons((uint16_t)port);
  13312. *ip_version = 4;
  13313. #if defined(USE_IPV6)
  13314. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13315. && ((size_t)len <= vec->len)
  13316. && mg_inet_pton(
  13317. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13318. /* IPv6 address, examples: see above */
  13319. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13320. */
  13321. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13322. *ip_version = 6;
  13323. #endif
  13324. } else if ((vec->ptr[0] == '+')
  13325. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13326. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13327. // string to an integer value, but function will not
  13328. // report conversion errors; consider using 'strtol'
  13329. // instead
  13330. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13331. /* Add 1 to len for the + character we skipped before */
  13332. len++;
  13333. #if defined(USE_IPV6)
  13334. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13335. so->lsa.sin6.sin6_family = AF_INET6;
  13336. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13337. *ip_version = 4 + 6;
  13338. #else
  13339. /* Bind to IPv4 only, since IPv6 is not built in. */
  13340. so->lsa.sin.sin_port = htons((uint16_t)port);
  13341. *ip_version = 4;
  13342. #endif
  13343. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13344. && (vec->ptr != endptr)) {
  13345. len = (int)(endptr - vec->ptr);
  13346. port = (uint16_t)portUL;
  13347. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13348. so->lsa.sin.sin_port = htons((uint16_t)port);
  13349. *ip_version = 4;
  13350. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13351. /* String could be a hostname. This check algotithm
  13352. * will only work for RFC 952 compliant hostnames,
  13353. * starting with a letter, containing only letters,
  13354. * digits and hyphen ('-'). Newer specs may allow
  13355. * more, but this is not guaranteed here, since it
  13356. * may interfere with rules for port option lists. */
  13357. /* According to RFC 1035, hostnames are restricted to 255 characters
  13358. * in total (63 between two dots). */
  13359. char hostname[256];
  13360. size_t hostnlen = (size_t)(cb - vec->ptr);
  13361. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13362. /* This would be invalid in any case */
  13363. *ip_version = 0;
  13364. return 0;
  13365. }
  13366. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13367. if (mg_inet_pton(
  13368. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13369. if (sscanf(cb + 1, "%u%n", &port, &len)
  13370. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13371. // string to an integer value, but function will not
  13372. // report conversion errors; consider using 'strtol'
  13373. // instead
  13374. *ip_version = 4;
  13375. so->lsa.sin.sin_port = htons((uint16_t)port);
  13376. len += (int)(hostnlen + 1);
  13377. } else {
  13378. len = 0;
  13379. }
  13380. #if defined(USE_IPV6)
  13381. } else if (mg_inet_pton(AF_INET6,
  13382. hostname,
  13383. &so->lsa.sin6,
  13384. sizeof(so->lsa.sin6),
  13385. 1)) {
  13386. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13387. *ip_version = 6;
  13388. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13389. len += (int)(hostnlen + 1);
  13390. } else {
  13391. len = 0;
  13392. }
  13393. #endif
  13394. } else {
  13395. len = 0;
  13396. }
  13397. #if defined(USE_X_DOM_SOCKET)
  13398. } else if (vec->ptr[0] == 'x') {
  13399. /* unix (linux) domain socket */
  13400. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13401. len = vec->len;
  13402. so->lsa.sun.sun_family = AF_UNIX;
  13403. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13404. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13405. port = 0;
  13406. *ip_version = 99;
  13407. } else {
  13408. /* String too long */
  13409. len = 0;
  13410. }
  13411. #endif
  13412. } else {
  13413. /* Parsing failure. */
  13414. len = 0;
  13415. }
  13416. /* sscanf and the option splitting code ensure the following condition
  13417. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13418. if ((len > 0) && is_valid_port(port)
  13419. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13420. /* Next character after the port number */
  13421. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13422. so->is_ssl = (ch == 's');
  13423. so->ssl_redir = (ch == 'r');
  13424. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13425. return 1;
  13426. }
  13427. }
  13428. /* Reset ip_version to 0 if there is an error */
  13429. *ip_version = 0;
  13430. return 0;
  13431. }
  13432. /* Is there any SSL port in use? */
  13433. static int
  13434. is_ssl_port_used(const char *ports)
  13435. {
  13436. if (ports) {
  13437. /* There are several different allowed syntax variants:
  13438. * - "80" for a single port using every network interface
  13439. * - "localhost:80" for a single port using only localhost
  13440. * - "80,localhost:8080" for two ports, one bound to localhost
  13441. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13442. * to IPv4 localhost, one to IPv6 localhost
  13443. * - "+80" use port 80 for IPv4 and IPv6
  13444. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13445. * for both: IPv4 and IPv4
  13446. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13447. * additionally port 8080 bound to localhost connections
  13448. *
  13449. * If we just look for 's' anywhere in the string, "localhost:80"
  13450. * will be detected as SSL (false positive).
  13451. * Looking for 's' after a digit may cause false positives in
  13452. * "my24service:8080".
  13453. * Looking from 's' backward if there are only ':' and numbers
  13454. * before will not work for "24service:8080" (non SSL, port 8080)
  13455. * or "24s" (SSL, port 24).
  13456. *
  13457. * Remark: Initially hostnames were not allowed to start with a
  13458. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13459. * Section 2.1).
  13460. *
  13461. * To get this correct, the entire string must be parsed as a whole,
  13462. * reading it as a list element for element and parsing with an
  13463. * algorithm equivalent to parse_port_string.
  13464. *
  13465. * In fact, we use local interface names here, not arbitrary
  13466. * hostnames, so in most cases the only name will be "localhost".
  13467. *
  13468. * So, for now, we use this simple algorithm, that may still return
  13469. * a false positive in bizarre cases.
  13470. */
  13471. int i;
  13472. int portslen = (int)strlen(ports);
  13473. char prevIsNumber = 0;
  13474. for (i = 0; i < portslen; i++) {
  13475. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13476. return 1;
  13477. }
  13478. if (ports[i] >= '0' && ports[i] <= '9') {
  13479. prevIsNumber = 1;
  13480. } else {
  13481. prevIsNumber = 0;
  13482. }
  13483. }
  13484. }
  13485. return 0;
  13486. }
  13487. static int
  13488. set_ports_option(struct mg_context *phys_ctx)
  13489. {
  13490. const char *list;
  13491. int on = 1;
  13492. #if defined(USE_IPV6)
  13493. int off = 0;
  13494. #endif
  13495. struct vec vec;
  13496. struct socket so, *ptr;
  13497. struct mg_pollfd *pfd;
  13498. union usa usa;
  13499. socklen_t len;
  13500. int ip_version;
  13501. int portsTotal = 0;
  13502. int portsOk = 0;
  13503. const char *opt_txt;
  13504. long opt_listen_backlog;
  13505. if (!phys_ctx) {
  13506. return 0;
  13507. }
  13508. memset(&so, 0, sizeof(so));
  13509. memset(&usa, 0, sizeof(usa));
  13510. len = sizeof(usa);
  13511. list = phys_ctx->dd.config[LISTENING_PORTS];
  13512. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13513. portsTotal++;
  13514. if (!parse_port_string(&vec, &so, &ip_version)) {
  13515. mg_cry_ctx_internal(
  13516. phys_ctx,
  13517. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13518. (int)vec.len,
  13519. vec.ptr,
  13520. portsTotal,
  13521. "[IP_ADDRESS:]PORT[s|r]");
  13522. continue;
  13523. }
  13524. #if !defined(NO_SSL)
  13525. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13526. mg_cry_ctx_internal(phys_ctx,
  13527. "Cannot add SSL socket (entry %i)",
  13528. portsTotal);
  13529. continue;
  13530. }
  13531. #endif
  13532. /* Create socket. */
  13533. /* For a list of protocol numbers (e.g., TCP==6) see:
  13534. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13535. */
  13536. if ((so.sock =
  13537. socket(so.lsa.sa.sa_family,
  13538. SOCK_STREAM,
  13539. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13540. == INVALID_SOCKET) {
  13541. mg_cry_ctx_internal(phys_ctx,
  13542. "cannot create socket (entry %i)",
  13543. portsTotal);
  13544. continue;
  13545. }
  13546. #if defined(_WIN32)
  13547. /* Windows SO_REUSEADDR lets many procs binds to a
  13548. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13549. * if someone already has the socket -- DTL */
  13550. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13551. * Windows might need a few seconds before
  13552. * the same port can be used again in the
  13553. * same process, so a short Sleep may be
  13554. * required between mg_stop and mg_start.
  13555. */
  13556. if (setsockopt(so.sock,
  13557. SOL_SOCKET,
  13558. SO_EXCLUSIVEADDRUSE,
  13559. (SOCK_OPT_TYPE)&on,
  13560. sizeof(on))
  13561. != 0) {
  13562. /* Set reuse option, but don't abort on errors. */
  13563. mg_cry_ctx_internal(
  13564. phys_ctx,
  13565. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13566. portsTotal);
  13567. }
  13568. #else
  13569. if (setsockopt(so.sock,
  13570. SOL_SOCKET,
  13571. SO_REUSEADDR,
  13572. (SOCK_OPT_TYPE)&on,
  13573. sizeof(on))
  13574. != 0) {
  13575. /* Set reuse option, but don't abort on errors. */
  13576. mg_cry_ctx_internal(
  13577. phys_ctx,
  13578. "cannot set socket option SO_REUSEADDR (entry %i)",
  13579. portsTotal);
  13580. }
  13581. #endif
  13582. #if defined(USE_X_DOM_SOCKET)
  13583. if (ip_version == 99) {
  13584. /* Unix domain socket */
  13585. } else
  13586. #endif
  13587. if (ip_version > 4) {
  13588. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13589. #if defined(USE_IPV6)
  13590. if (ip_version > 6) {
  13591. if (so.lsa.sa.sa_family == AF_INET6
  13592. && setsockopt(so.sock,
  13593. IPPROTO_IPV6,
  13594. IPV6_V6ONLY,
  13595. (void *)&off,
  13596. sizeof(off))
  13597. != 0) {
  13598. /* Set IPv6 only option, but don't abort on errors. */
  13599. mg_cry_ctx_internal(phys_ctx,
  13600. "cannot set socket option "
  13601. "IPV6_V6ONLY=off (entry %i)",
  13602. portsTotal);
  13603. }
  13604. } else {
  13605. if (so.lsa.sa.sa_family == AF_INET6
  13606. && setsockopt(so.sock,
  13607. IPPROTO_IPV6,
  13608. IPV6_V6ONLY,
  13609. (void *)&on,
  13610. sizeof(on))
  13611. != 0) {
  13612. /* Set IPv6 only option, but don't abort on errors. */
  13613. mg_cry_ctx_internal(phys_ctx,
  13614. "cannot set socket option "
  13615. "IPV6_V6ONLY=on (entry %i)",
  13616. portsTotal);
  13617. }
  13618. }
  13619. #else
  13620. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13621. closesocket(so.sock);
  13622. so.sock = INVALID_SOCKET;
  13623. continue;
  13624. #endif
  13625. }
  13626. if (so.lsa.sa.sa_family == AF_INET) {
  13627. len = sizeof(so.lsa.sin);
  13628. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13629. mg_cry_ctx_internal(phys_ctx,
  13630. "cannot bind to %.*s: %d (%s)",
  13631. (int)vec.len,
  13632. vec.ptr,
  13633. (int)ERRNO,
  13634. strerror(errno));
  13635. closesocket(so.sock);
  13636. so.sock = INVALID_SOCKET;
  13637. continue;
  13638. }
  13639. }
  13640. #if defined(USE_IPV6)
  13641. else if (so.lsa.sa.sa_family == AF_INET6) {
  13642. len = sizeof(so.lsa.sin6);
  13643. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13644. mg_cry_ctx_internal(phys_ctx,
  13645. "cannot bind to IPv6 %.*s: %d (%s)",
  13646. (int)vec.len,
  13647. vec.ptr,
  13648. (int)ERRNO,
  13649. strerror(errno));
  13650. closesocket(so.sock);
  13651. so.sock = INVALID_SOCKET;
  13652. continue;
  13653. }
  13654. }
  13655. #endif
  13656. #if defined(USE_X_DOM_SOCKET)
  13657. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13658. len = sizeof(so.lsa.sun);
  13659. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13660. mg_cry_ctx_internal(phys_ctx,
  13661. "cannot bind to unix socket %s: %d (%s)",
  13662. so.lsa.sun.sun_path,
  13663. (int)ERRNO,
  13664. strerror(errno));
  13665. closesocket(so.sock);
  13666. so.sock = INVALID_SOCKET;
  13667. continue;
  13668. }
  13669. }
  13670. #endif
  13671. else {
  13672. mg_cry_ctx_internal(
  13673. phys_ctx,
  13674. "cannot bind: address family not supported (entry %i)",
  13675. portsTotal);
  13676. closesocket(so.sock);
  13677. so.sock = INVALID_SOCKET;
  13678. continue;
  13679. }
  13680. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13681. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13682. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13683. mg_cry_ctx_internal(phys_ctx,
  13684. "%s value \"%s\" is invalid",
  13685. config_options[LISTEN_BACKLOG_SIZE].name,
  13686. opt_txt);
  13687. closesocket(so.sock);
  13688. so.sock = INVALID_SOCKET;
  13689. continue;
  13690. }
  13691. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13692. mg_cry_ctx_internal(phys_ctx,
  13693. "cannot listen to %.*s: %d (%s)",
  13694. (int)vec.len,
  13695. vec.ptr,
  13696. (int)ERRNO,
  13697. strerror(errno));
  13698. closesocket(so.sock);
  13699. so.sock = INVALID_SOCKET;
  13700. continue;
  13701. }
  13702. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13703. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13704. int err = (int)ERRNO;
  13705. mg_cry_ctx_internal(phys_ctx,
  13706. "call to getsockname failed %.*s: %d (%s)",
  13707. (int)vec.len,
  13708. vec.ptr,
  13709. err,
  13710. strerror(errno));
  13711. closesocket(so.sock);
  13712. so.sock = INVALID_SOCKET;
  13713. continue;
  13714. }
  13715. /* Update lsa port in case of random free ports */
  13716. #if defined(USE_IPV6)
  13717. if (so.lsa.sa.sa_family == AF_INET6) {
  13718. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13719. } else
  13720. #endif
  13721. {
  13722. so.lsa.sin.sin_port = usa.sin.sin_port;
  13723. }
  13724. if ((ptr = (struct socket *)
  13725. mg_realloc_ctx(phys_ctx->listening_sockets,
  13726. (phys_ctx->num_listening_sockets + 1)
  13727. * sizeof(phys_ctx->listening_sockets[0]),
  13728. phys_ctx))
  13729. == NULL) {
  13730. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13731. closesocket(so.sock);
  13732. so.sock = INVALID_SOCKET;
  13733. continue;
  13734. }
  13735. if ((pfd = (struct mg_pollfd *)
  13736. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13737. (phys_ctx->num_listening_sockets + 1)
  13738. * sizeof(phys_ctx->listening_socket_fds[0]),
  13739. phys_ctx))
  13740. == NULL) {
  13741. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13742. closesocket(so.sock);
  13743. so.sock = INVALID_SOCKET;
  13744. mg_free(ptr);
  13745. continue;
  13746. }
  13747. set_close_on_exec(so.sock, NULL, phys_ctx);
  13748. phys_ctx->listening_sockets = ptr;
  13749. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13750. phys_ctx->listening_socket_fds = pfd;
  13751. phys_ctx->num_listening_sockets++;
  13752. portsOk++;
  13753. }
  13754. if (portsOk != portsTotal) {
  13755. close_all_listening_sockets(phys_ctx);
  13756. portsOk = 0;
  13757. }
  13758. return portsOk;
  13759. }
  13760. static const char *
  13761. header_val(const struct mg_connection *conn, const char *header)
  13762. {
  13763. const char *header_value;
  13764. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13765. return "-";
  13766. } else {
  13767. return header_value;
  13768. }
  13769. }
  13770. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13771. #include "external_log_access.inl"
  13772. #elif !defined(NO_FILESYSTEMS)
  13773. static void
  13774. log_access(const struct mg_connection *conn)
  13775. {
  13776. const struct mg_request_info *ri;
  13777. struct mg_file fi;
  13778. char date[64], src_addr[IP_ADDR_STR_LEN];
  13779. struct tm *tm;
  13780. const char *referer;
  13781. const char *user_agent;
  13782. char log_buf[4096];
  13783. if (!conn || !conn->dom_ctx) {
  13784. return;
  13785. }
  13786. /* Set log message to "empty" */
  13787. log_buf[0] = 0;
  13788. #if defined(USE_LUA)
  13789. if (conn->phys_ctx->lua_bg_log_available) {
  13790. int ret;
  13791. struct mg_context *ctx = conn->phys_ctx;
  13792. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13793. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13794. /* call "log()" in Lua */
  13795. lua_getglobal(lstate, "log");
  13796. prepare_lua_request_info_inner(conn, lstate);
  13797. push_lua_response_log_data(conn, lstate);
  13798. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13799. if (ret == 0) {
  13800. int t = lua_type(lstate, -1);
  13801. if (t == LUA_TBOOLEAN) {
  13802. if (lua_toboolean(lstate, -1) == 0) {
  13803. /* log() returned false: do not log */
  13804. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13805. return;
  13806. }
  13807. /* log returned true: continue logging */
  13808. } else if (t == LUA_TSTRING) {
  13809. size_t len;
  13810. const char *txt = lua_tolstring(lstate, -1, &len);
  13811. if ((len == 0) || (*txt == 0)) {
  13812. /* log() returned empty string: do not log */
  13813. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13814. return;
  13815. }
  13816. /* Copy test from Lua into log_buf */
  13817. if (len >= sizeof(log_buf)) {
  13818. len = sizeof(log_buf) - 1;
  13819. }
  13820. memcpy(log_buf, txt, len);
  13821. log_buf[len] = 0;
  13822. }
  13823. } else {
  13824. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13825. }
  13826. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13827. }
  13828. #endif
  13829. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13830. if (mg_fopen(conn,
  13831. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13832. MG_FOPEN_MODE_APPEND,
  13833. &fi)
  13834. == 0) {
  13835. fi.access.fp = NULL;
  13836. }
  13837. } else {
  13838. fi.access.fp = NULL;
  13839. }
  13840. /* Log is written to a file and/or a callback. If both are not set,
  13841. * executing the rest of the function is pointless. */
  13842. if ((fi.access.fp == NULL)
  13843. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13844. return;
  13845. }
  13846. /* If we did not get a log message from Lua, create it here. */
  13847. if (!log_buf[0]) {
  13848. tm = localtime(&conn->conn_birth_time);
  13849. if (tm != NULL) {
  13850. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13851. } else {
  13852. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13853. date[sizeof(date) - 1] = '\0';
  13854. }
  13855. ri = &conn->request_info;
  13856. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13857. referer = header_val(conn, "Referer");
  13858. user_agent = header_val(conn, "User-Agent");
  13859. mg_snprintf(conn,
  13860. NULL, /* Ignore truncation in access log */
  13861. log_buf,
  13862. sizeof(log_buf),
  13863. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13864. " %s %s",
  13865. src_addr,
  13866. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13867. date,
  13868. ri->request_method ? ri->request_method : "-",
  13869. ri->request_uri ? ri->request_uri : "-",
  13870. ri->query_string ? "?" : "",
  13871. ri->query_string ? ri->query_string : "",
  13872. ri->http_version,
  13873. conn->status_code,
  13874. conn->num_bytes_sent,
  13875. referer,
  13876. user_agent);
  13877. }
  13878. /* Here we have a log message in log_buf. Call the callback */
  13879. if (conn->phys_ctx->callbacks.log_access) {
  13880. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13881. /* do not log if callack returns non-zero */
  13882. if (fi.access.fp) {
  13883. mg_fclose(&fi.access);
  13884. }
  13885. return;
  13886. }
  13887. }
  13888. /* Store in file */
  13889. if (fi.access.fp) {
  13890. int ok = 1;
  13891. flockfile(fi.access.fp);
  13892. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13893. ok = 0;
  13894. }
  13895. if (fflush(fi.access.fp) != 0) {
  13896. ok = 0;
  13897. }
  13898. funlockfile(fi.access.fp);
  13899. if (mg_fclose(&fi.access) != 0) {
  13900. ok = 0;
  13901. }
  13902. if (!ok) {
  13903. mg_cry_internal(conn,
  13904. "Error writing log file %s",
  13905. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13906. }
  13907. }
  13908. }
  13909. #else
  13910. #error "Either enable filesystems or provide a custom log_access implementation"
  13911. #endif /* Externally provided function */
  13912. /* Verify given socket address against the ACL.
  13913. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13914. */
  13915. static int
  13916. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13917. {
  13918. int allowed, flag, matched;
  13919. struct vec vec;
  13920. if (phys_ctx) {
  13921. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13922. /* If any ACL is set, deny by default */
  13923. allowed = (list == NULL) ? '+' : '-';
  13924. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13925. flag = vec.ptr[0];
  13926. matched = -1;
  13927. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13928. vec.ptr++;
  13929. vec.len--;
  13930. matched = parse_match_net(&vec, sa, 1);
  13931. }
  13932. if (matched < 0) {
  13933. mg_cry_ctx_internal(phys_ctx,
  13934. "%s: subnet must be [+|-]IP-addr[/x]",
  13935. __func__);
  13936. return -1;
  13937. }
  13938. if (matched) {
  13939. allowed = flag;
  13940. }
  13941. }
  13942. return allowed == '+';
  13943. }
  13944. return -1;
  13945. }
  13946. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13947. static int
  13948. set_uid_option(struct mg_context *phys_ctx)
  13949. {
  13950. int success = 0;
  13951. if (phys_ctx) {
  13952. /* We are currently running as curr_uid. */
  13953. const uid_t curr_uid = getuid();
  13954. /* If set, we want to run as run_as_user. */
  13955. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13956. const struct passwd *to_pw = NULL;
  13957. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13958. /* run_as_user does not exist on the system. We can't proceed
  13959. * further. */
  13960. mg_cry_ctx_internal(phys_ctx,
  13961. "%s: unknown user [%s]",
  13962. __func__,
  13963. run_as_user);
  13964. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13965. /* There was either no request to change user, or we're already
  13966. * running as run_as_user. Nothing else to do.
  13967. */
  13968. success = 1;
  13969. } else {
  13970. /* Valid change request. */
  13971. if (setgid(to_pw->pw_gid) == -1) {
  13972. mg_cry_ctx_internal(phys_ctx,
  13973. "%s: setgid(%s): %s",
  13974. __func__,
  13975. run_as_user,
  13976. strerror(errno));
  13977. } else if (setgroups(0, NULL) == -1) {
  13978. mg_cry_ctx_internal(phys_ctx,
  13979. "%s: setgroups(): %s",
  13980. __func__,
  13981. strerror(errno));
  13982. } else if (setuid(to_pw->pw_uid) == -1) {
  13983. mg_cry_ctx_internal(phys_ctx,
  13984. "%s: setuid(%s): %s",
  13985. __func__,
  13986. run_as_user,
  13987. strerror(errno));
  13988. } else {
  13989. success = 1;
  13990. }
  13991. }
  13992. }
  13993. return success;
  13994. }
  13995. #endif /* !_WIN32 */
  13996. static void
  13997. tls_dtor(void *key)
  13998. {
  13999. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14000. /* key == pthread_getspecific(sTlsKey); */
  14001. if (tls) {
  14002. if (tls->is_master == 2) {
  14003. tls->is_master = -3; /* Mark memory as dead */
  14004. mg_free(tls);
  14005. }
  14006. }
  14007. pthread_setspecific(sTlsKey, NULL);
  14008. }
  14009. #if defined(USE_MBEDTLS)
  14010. /* Check if SSL is required.
  14011. * If so, set up ctx->ssl_ctx pointer. */
  14012. static int
  14013. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14014. {
  14015. if (!phys_ctx) {
  14016. return 0;
  14017. }
  14018. if (!dom_ctx) {
  14019. dom_ctx = &(phys_ctx->dd);
  14020. }
  14021. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14022. /* No SSL port is set. No need to setup SSL. */
  14023. return 1;
  14024. }
  14025. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14026. if (dom_ctx->ssl_ctx == NULL) {
  14027. fprintf(stderr, "ssl_ctx malloc failed\n");
  14028. return 0;
  14029. }
  14030. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14031. == 0
  14032. ? 1
  14033. : 0;
  14034. }
  14035. #elif !defined(NO_SSL)
  14036. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14037. struct mg_domain_context *dom_ctx,
  14038. const char *pem,
  14039. const char *chain);
  14040. static const char *ssl_error(void);
  14041. static int
  14042. refresh_trust(struct mg_connection *conn)
  14043. {
  14044. struct stat cert_buf;
  14045. int64_t t = 0;
  14046. const char *pem;
  14047. const char *chain;
  14048. int should_verify_peer;
  14049. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14050. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14051. * refresh_trust still can not work. */
  14052. return 0;
  14053. }
  14054. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14055. if (chain == NULL) {
  14056. /* pem is not NULL here */
  14057. chain = pem;
  14058. }
  14059. if (*chain == 0) {
  14060. chain = NULL;
  14061. }
  14062. if (stat(pem, &cert_buf) != -1) {
  14063. t = (int64_t)cert_buf.st_mtime;
  14064. }
  14065. mg_lock_context(conn->phys_ctx);
  14066. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14067. conn->dom_ctx->ssl_cert_last_mtime = t;
  14068. should_verify_peer = 0;
  14069. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14070. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14071. == 0) {
  14072. should_verify_peer = 1;
  14073. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14074. "optional")
  14075. == 0) {
  14076. should_verify_peer = 1;
  14077. }
  14078. }
  14079. if (should_verify_peer) {
  14080. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14081. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14082. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14083. ca_file,
  14084. ca_path)
  14085. != 1) {
  14086. mg_unlock_context(conn->phys_ctx);
  14087. mg_cry_ctx_internal(
  14088. conn->phys_ctx,
  14089. "SSL_CTX_load_verify_locations error: %s "
  14090. "ssl_verify_peer requires setting "
  14091. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14092. "present in "
  14093. "the .conf file?",
  14094. ssl_error());
  14095. return 0;
  14096. }
  14097. }
  14098. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14099. mg_unlock_context(conn->phys_ctx);
  14100. return 0;
  14101. }
  14102. }
  14103. mg_unlock_context(conn->phys_ctx);
  14104. return 1;
  14105. }
  14106. #if defined(OPENSSL_API_1_1)
  14107. #else
  14108. static pthread_mutex_t *ssl_mutexes;
  14109. #endif /* OPENSSL_API_1_1 */
  14110. static int
  14111. sslize(struct mg_connection *conn,
  14112. int (*func)(SSL *),
  14113. const struct mg_client_options *client_options)
  14114. {
  14115. int ret, err;
  14116. int short_trust;
  14117. unsigned timeout = 1024;
  14118. unsigned i;
  14119. if (!conn) {
  14120. return 0;
  14121. }
  14122. short_trust =
  14123. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14124. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14125. if (short_trust) {
  14126. int trust_ret = refresh_trust(conn);
  14127. if (!trust_ret) {
  14128. return trust_ret;
  14129. }
  14130. }
  14131. mg_lock_context(conn->phys_ctx);
  14132. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14133. mg_unlock_context(conn->phys_ctx);
  14134. if (conn->ssl == NULL) {
  14135. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14136. OPENSSL_REMOVE_THREAD_STATE();
  14137. return 0;
  14138. }
  14139. SSL_set_app_data(conn->ssl, (char *)conn);
  14140. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14141. if (ret != 1) {
  14142. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14143. SSL_free(conn->ssl);
  14144. conn->ssl = NULL;
  14145. OPENSSL_REMOVE_THREAD_STATE();
  14146. return 0;
  14147. }
  14148. if (client_options) {
  14149. if (client_options->host_name) {
  14150. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14151. }
  14152. }
  14153. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14154. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14155. /* NOTE: The loop below acts as a back-off, so we can end
  14156. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14157. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14158. if (to >= 0) {
  14159. timeout = (unsigned)to;
  14160. }
  14161. }
  14162. /* SSL functions may fail and require to be called again:
  14163. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14164. * Here "func" could be SSL_connect or SSL_accept. */
  14165. for (i = 0; i <= timeout; i += 50) {
  14166. ERR_clear_error();
  14167. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14168. ret = func(conn->ssl);
  14169. if (ret != 1) {
  14170. err = SSL_get_error(conn->ssl, ret);
  14171. if ((err == SSL_ERROR_WANT_CONNECT)
  14172. || (err == SSL_ERROR_WANT_ACCEPT)
  14173. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14174. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14175. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14176. /* Don't wait if the server is going to be stopped. */
  14177. break;
  14178. }
  14179. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14180. /* Simply retry the function call. */
  14181. mg_sleep(50);
  14182. } else {
  14183. /* Need to retry the function call "later".
  14184. * See https://linux.die.net/man/3/ssl_get_error
  14185. * This is typical for non-blocking sockets. */
  14186. struct mg_pollfd pfd;
  14187. int pollres;
  14188. pfd.fd = conn->client.sock;
  14189. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14190. || (err == SSL_ERROR_WANT_WRITE))
  14191. ? POLLOUT
  14192. : POLLIN;
  14193. pollres =
  14194. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14195. if (pollres < 0) {
  14196. /* Break if error occured (-1)
  14197. * or server shutdown (-2) */
  14198. break;
  14199. }
  14200. }
  14201. } else if (err == SSL_ERROR_SYSCALL) {
  14202. /* This is an IO error. Look at errno. */
  14203. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14204. break;
  14205. } else {
  14206. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14207. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14208. break;
  14209. }
  14210. } else {
  14211. /* success */
  14212. break;
  14213. }
  14214. }
  14215. ERR_clear_error();
  14216. if (ret != 1) {
  14217. SSL_free(conn->ssl);
  14218. conn->ssl = NULL;
  14219. OPENSSL_REMOVE_THREAD_STATE();
  14220. return 0;
  14221. }
  14222. return 1;
  14223. }
  14224. /* Return OpenSSL error message (from CRYPTO lib) */
  14225. static const char *
  14226. ssl_error(void)
  14227. {
  14228. unsigned long err;
  14229. err = ERR_get_error();
  14230. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14231. }
  14232. static int
  14233. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14234. {
  14235. int i;
  14236. const char hexdigit[] = "0123456789abcdef";
  14237. if ((memlen <= 0) || (buflen <= 0)) {
  14238. return 0;
  14239. }
  14240. if (buflen < (3 * memlen)) {
  14241. return 0;
  14242. }
  14243. for (i = 0; i < memlen; i++) {
  14244. if (i > 0) {
  14245. buf[3 * i - 1] = ' ';
  14246. }
  14247. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14248. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14249. }
  14250. buf[3 * memlen - 1] = 0;
  14251. return 1;
  14252. }
  14253. static int
  14254. ssl_get_client_cert_info(const struct mg_connection *conn,
  14255. struct mg_client_cert *client_cert)
  14256. {
  14257. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14258. if (cert) {
  14259. char str_buf[1024];
  14260. unsigned char buf[256];
  14261. char *str_serial = NULL;
  14262. unsigned int ulen;
  14263. int ilen;
  14264. unsigned char *tmp_buf;
  14265. unsigned char *tmp_p;
  14266. /* Handle to algorithm used for fingerprint */
  14267. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14268. /* Get Subject and issuer */
  14269. X509_NAME *subj = X509_get_subject_name(cert);
  14270. X509_NAME *iss = X509_get_issuer_name(cert);
  14271. /* Get serial number */
  14272. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14273. /* Translate serial number to a hex string */
  14274. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14275. if (serial_bn) {
  14276. str_serial = BN_bn2hex(serial_bn);
  14277. BN_free(serial_bn);
  14278. }
  14279. client_cert->serial =
  14280. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14281. /* Translate subject and issuer to a string */
  14282. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14283. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14284. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14285. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14286. /* Calculate SHA1 fingerprint and store as a hex string */
  14287. ulen = 0;
  14288. /* ASN1_digest is deprecated. Do the calculation manually,
  14289. * using EVP_Digest. */
  14290. ilen = i2d_X509(cert, NULL);
  14291. tmp_buf = (ilen > 0)
  14292. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14293. conn->phys_ctx)
  14294. : NULL;
  14295. if (tmp_buf) {
  14296. tmp_p = tmp_buf;
  14297. (void)i2d_X509(cert, &tmp_p);
  14298. if (!EVP_Digest(
  14299. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14300. ulen = 0;
  14301. }
  14302. mg_free(tmp_buf);
  14303. }
  14304. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14305. *str_buf = 0;
  14306. }
  14307. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14308. client_cert->peer_cert = (void *)cert;
  14309. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14310. * see https://linux.die.net/man/3/bn_bn2hex */
  14311. OPENSSL_free(str_serial);
  14312. return 1;
  14313. }
  14314. return 0;
  14315. }
  14316. #if defined(OPENSSL_API_1_1)
  14317. #else
  14318. static void
  14319. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14320. {
  14321. (void)line;
  14322. (void)file;
  14323. if (mode & 1) {
  14324. /* 1 is CRYPTO_LOCK */
  14325. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14326. } else {
  14327. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14328. }
  14329. }
  14330. #endif /* OPENSSL_API_1_1 */
  14331. #if !defined(NO_SSL_DL)
  14332. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14333. static void *
  14334. load_tls_dll(char *ebuf,
  14335. size_t ebuf_len,
  14336. const char *dll_name,
  14337. struct ssl_func *sw,
  14338. int *feature_missing)
  14339. {
  14340. union {
  14341. void *p;
  14342. void (*fp)(void);
  14343. } u;
  14344. void *dll_handle;
  14345. struct ssl_func *fp;
  14346. int ok;
  14347. int truncated = 0;
  14348. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14349. mg_snprintf(NULL,
  14350. NULL, /* No truncation check for ebuf */
  14351. ebuf,
  14352. ebuf_len,
  14353. "%s: cannot load %s",
  14354. __func__,
  14355. dll_name);
  14356. return NULL;
  14357. }
  14358. ok = 1;
  14359. for (fp = sw; fp->name != NULL; fp++) {
  14360. #if defined(_WIN32)
  14361. /* GetProcAddress() returns pointer to function */
  14362. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14363. #else
  14364. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14365. * pointers to function pointers. We need to use a union to make a
  14366. * cast. */
  14367. u.p = dlsym(dll_handle, fp->name);
  14368. #endif /* _WIN32 */
  14369. /* Set pointer (might be NULL) */
  14370. fp->ptr = u.fp;
  14371. if (u.fp == NULL) {
  14372. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14373. if (feature_missing) {
  14374. feature_missing[fp->required]++;
  14375. }
  14376. if (fp->required == TLS_Mandatory) {
  14377. /* Mandatory function is missing */
  14378. if (ok) {
  14379. /* This is the first missing function.
  14380. * Create a new error message. */
  14381. mg_snprintf(NULL,
  14382. &truncated,
  14383. ebuf,
  14384. ebuf_len,
  14385. "%s: %s: cannot find %s",
  14386. __func__,
  14387. dll_name,
  14388. fp->name);
  14389. ok = 0;
  14390. } else {
  14391. /* This is yet anothermissing function.
  14392. * Append existing error message. */
  14393. size_t cur_len = strlen(ebuf);
  14394. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14395. mg_snprintf(NULL,
  14396. &truncated,
  14397. ebuf + cur_len,
  14398. ebuf_len - cur_len - 3,
  14399. ", %s",
  14400. fp->name);
  14401. if (truncated) {
  14402. /* If truncated, add "..." */
  14403. strcat(ebuf, "...");
  14404. }
  14405. }
  14406. }
  14407. }
  14408. }
  14409. }
  14410. if (!ok) {
  14411. (void)dlclose(dll_handle);
  14412. return NULL;
  14413. }
  14414. return dll_handle;
  14415. }
  14416. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14417. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14418. #endif /* NO_SSL_DL */
  14419. #if defined(SSL_ALREADY_INITIALIZED)
  14420. static volatile ptrdiff_t cryptolib_users =
  14421. 1; /* Reference counter for crypto library. */
  14422. #else
  14423. static volatile ptrdiff_t cryptolib_users =
  14424. 0; /* Reference counter for crypto library. */
  14425. #endif
  14426. static int
  14427. initialize_openssl(char *ebuf, size_t ebuf_len)
  14428. {
  14429. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14430. int i, num_locks;
  14431. size_t size;
  14432. #endif
  14433. if (ebuf_len > 0) {
  14434. ebuf[0] = 0;
  14435. }
  14436. #if !defined(NO_SSL_DL)
  14437. if (!cryptolib_dll_handle) {
  14438. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14439. cryptolib_dll_handle = load_tls_dll(
  14440. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14441. if (!cryptolib_dll_handle) {
  14442. mg_snprintf(NULL,
  14443. NULL, /* No truncation check for ebuf */
  14444. ebuf,
  14445. ebuf_len,
  14446. "%s: error loading library %s",
  14447. __func__,
  14448. CRYPTO_LIB);
  14449. DEBUG_TRACE("%s", ebuf);
  14450. return 0;
  14451. }
  14452. }
  14453. #endif /* NO_SSL_DL */
  14454. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14455. return 1;
  14456. }
  14457. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14458. /* Initialize locking callbacks, needed for thread safety.
  14459. * http://www.openssl.org/support/faq.html#PROG1
  14460. */
  14461. num_locks = CRYPTO_num_locks();
  14462. if (num_locks < 0) {
  14463. num_locks = 0;
  14464. }
  14465. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14466. /* allocate mutex array, if required */
  14467. if (num_locks == 0) {
  14468. /* No mutex array required */
  14469. ssl_mutexes = NULL;
  14470. } else {
  14471. /* Mutex array required - allocate it */
  14472. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14473. /* Check OOM */
  14474. if (ssl_mutexes == NULL) {
  14475. mg_snprintf(NULL,
  14476. NULL, /* No truncation check for ebuf */
  14477. ebuf,
  14478. ebuf_len,
  14479. "%s: cannot allocate mutexes: %s",
  14480. __func__,
  14481. ssl_error());
  14482. DEBUG_TRACE("%s", ebuf);
  14483. return 0;
  14484. }
  14485. /* initialize mutex array */
  14486. for (i = 0; i < num_locks; i++) {
  14487. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14488. mg_snprintf(NULL,
  14489. NULL, /* No truncation check for ebuf */
  14490. ebuf,
  14491. ebuf_len,
  14492. "%s: error initializing mutex %i of %i",
  14493. __func__,
  14494. i,
  14495. num_locks);
  14496. DEBUG_TRACE("%s", ebuf);
  14497. mg_free(ssl_mutexes);
  14498. return 0;
  14499. }
  14500. }
  14501. }
  14502. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14503. CRYPTO_set_id_callback(&mg_current_thread_id);
  14504. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14505. #if !defined(NO_SSL_DL)
  14506. if (!ssllib_dll_handle) {
  14507. ssllib_dll_handle =
  14508. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14509. if (!ssllib_dll_handle) {
  14510. #if !defined(OPENSSL_API_1_1)
  14511. mg_free(ssl_mutexes);
  14512. #endif
  14513. DEBUG_TRACE("%s", ebuf);
  14514. return 0;
  14515. }
  14516. }
  14517. #endif /* NO_SSL_DL */
  14518. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14519. && !defined(NO_SSL_DL)
  14520. /* Initialize SSL library */
  14521. OPENSSL_init_ssl(0, NULL);
  14522. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14523. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14524. NULL);
  14525. #else
  14526. /* Initialize SSL library */
  14527. SSL_library_init();
  14528. SSL_load_error_strings();
  14529. #endif
  14530. return 1;
  14531. }
  14532. static int
  14533. ssl_use_pem_file(struct mg_context *phys_ctx,
  14534. struct mg_domain_context *dom_ctx,
  14535. const char *pem,
  14536. const char *chain)
  14537. {
  14538. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14539. mg_cry_ctx_internal(phys_ctx,
  14540. "%s: cannot open certificate file %s: %s",
  14541. __func__,
  14542. pem,
  14543. ssl_error());
  14544. return 0;
  14545. }
  14546. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14547. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14548. mg_cry_ctx_internal(phys_ctx,
  14549. "%s: cannot open private key file %s: %s",
  14550. __func__,
  14551. pem,
  14552. ssl_error());
  14553. return 0;
  14554. }
  14555. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14556. mg_cry_ctx_internal(phys_ctx,
  14557. "%s: certificate and private key do not match: %s",
  14558. __func__,
  14559. pem);
  14560. return 0;
  14561. }
  14562. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14563. * chain files that contain private keys and certificates in
  14564. * SSL_CTX_use_certificate_chain_file.
  14565. * The CivetWeb-Server used pem-Files that contained both information.
  14566. * In order to make wolfSSL work, it is split in two files.
  14567. * One file that contains key and certificate used by the server and
  14568. * an optional chain file for the ssl stack.
  14569. */
  14570. if (chain) {
  14571. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14572. mg_cry_ctx_internal(phys_ctx,
  14573. "%s: cannot use certificate chain file %s: %s",
  14574. __func__,
  14575. chain,
  14576. ssl_error());
  14577. return 0;
  14578. }
  14579. }
  14580. return 1;
  14581. }
  14582. #if defined(OPENSSL_API_1_1)
  14583. static unsigned long
  14584. ssl_get_protocol(int version_id)
  14585. {
  14586. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14587. if (version_id > 0)
  14588. ret |= SSL_OP_NO_SSLv2;
  14589. if (version_id > 1)
  14590. ret |= SSL_OP_NO_SSLv3;
  14591. if (version_id > 2)
  14592. ret |= SSL_OP_NO_TLSv1;
  14593. if (version_id > 3)
  14594. ret |= SSL_OP_NO_TLSv1_1;
  14595. if (version_id > 4)
  14596. ret |= SSL_OP_NO_TLSv1_2;
  14597. #if defined(SSL_OP_NO_TLSv1_3)
  14598. if (version_id > 5)
  14599. ret |= SSL_OP_NO_TLSv1_3;
  14600. #endif
  14601. return ret;
  14602. }
  14603. #else
  14604. static long
  14605. ssl_get_protocol(int version_id)
  14606. {
  14607. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14608. if (version_id > 0)
  14609. ret |= SSL_OP_NO_SSLv2;
  14610. if (version_id > 1)
  14611. ret |= SSL_OP_NO_SSLv3;
  14612. if (version_id > 2)
  14613. ret |= SSL_OP_NO_TLSv1;
  14614. if (version_id > 3)
  14615. ret |= SSL_OP_NO_TLSv1_1;
  14616. if (version_id > 4)
  14617. ret |= SSL_OP_NO_TLSv1_2;
  14618. #if defined(SSL_OP_NO_TLSv1_3)
  14619. if (version_id > 5)
  14620. ret |= SSL_OP_NO_TLSv1_3;
  14621. #endif
  14622. return (long)ret;
  14623. }
  14624. #endif /* OPENSSL_API_1_1 */
  14625. /* SSL callback documentation:
  14626. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14627. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14628. * https://linux.die.net/man/3/ssl_set_info_callback */
  14629. /* Note: There is no "const" for the first argument in the documentation
  14630. * examples, however some (maybe most, but not all) headers of OpenSSL
  14631. * versions / OpenSSL compatibility layers have it. Having a different
  14632. * definition will cause a warning in C and an error in C++. Use "const SSL
  14633. * *", while automatical conversion from "SSL *" works for all compilers,
  14634. * but not other way around */
  14635. static void
  14636. ssl_info_callback(const SSL *ssl, int what, int ret)
  14637. {
  14638. (void)ret;
  14639. if (what & SSL_CB_HANDSHAKE_START) {
  14640. SSL_get_app_data(ssl);
  14641. }
  14642. if (what & SSL_CB_HANDSHAKE_DONE) {
  14643. /* TODO: check for openSSL 1.1 */
  14644. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14645. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14646. }
  14647. }
  14648. static int
  14649. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14650. {
  14651. #if defined(GCC_DIAGNOSTIC)
  14652. #pragma GCC diagnostic push
  14653. #pragma GCC diagnostic ignored "-Wcast-align"
  14654. #endif /* defined(GCC_DIAGNOSTIC) */
  14655. /* We used an aligned pointer in SSL_set_app_data */
  14656. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14657. #if defined(GCC_DIAGNOSTIC)
  14658. #pragma GCC diagnostic pop
  14659. #endif /* defined(GCC_DIAGNOSTIC) */
  14660. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14661. (void)ad;
  14662. (void)arg;
  14663. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14664. DEBUG_ASSERT(0);
  14665. return SSL_TLSEXT_ERR_NOACK;
  14666. }
  14667. conn->dom_ctx = &(conn->phys_ctx->dd);
  14668. /* Old clients (Win XP) will not support SNI. Then, there
  14669. * is no server name available in the request - we can
  14670. * only work with the default certificate.
  14671. * Multiple HTTPS hosts on one IP+port are only possible
  14672. * with a certificate containing all alternative names.
  14673. */
  14674. if ((servername == NULL) || (*servername == 0)) {
  14675. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14676. mg_lock_context(conn->phys_ctx);
  14677. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14678. mg_unlock_context(conn->phys_ctx);
  14679. return SSL_TLSEXT_ERR_NOACK;
  14680. }
  14681. DEBUG_TRACE("TLS connection to host %s", servername);
  14682. while (conn->dom_ctx) {
  14683. if (!mg_strcasecmp(servername,
  14684. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14685. /* Found matching domain */
  14686. DEBUG_TRACE("TLS domain %s found",
  14687. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14688. break;
  14689. }
  14690. mg_lock_context(conn->phys_ctx);
  14691. conn->dom_ctx = conn->dom_ctx->next;
  14692. mg_unlock_context(conn->phys_ctx);
  14693. }
  14694. if (conn->dom_ctx == NULL) {
  14695. /* Default domain */
  14696. DEBUG_TRACE("TLS default domain %s used",
  14697. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14698. conn->dom_ctx = &(conn->phys_ctx->dd);
  14699. }
  14700. mg_lock_context(conn->phys_ctx);
  14701. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14702. mg_unlock_context(conn->phys_ctx);
  14703. return SSL_TLSEXT_ERR_OK;
  14704. }
  14705. #if defined(USE_ALPN)
  14706. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14707. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14708. alpn_proto_list + 3 + 8,
  14709. NULL};
  14710. #if defined(USE_HTTP2)
  14711. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14712. alpn_proto_list + 3,
  14713. alpn_proto_list + 3 + 8,
  14714. NULL};
  14715. #endif
  14716. static int
  14717. alpn_select_cb(SSL *ssl,
  14718. const unsigned char **out,
  14719. unsigned char *outlen,
  14720. const unsigned char *in,
  14721. unsigned int inlen,
  14722. void *arg)
  14723. {
  14724. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14725. unsigned int i, j, enable_http2 = 0;
  14726. const char **alpn_proto_order = alpn_proto_order_http1;
  14727. struct mg_workerTLS *tls =
  14728. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14729. (void)ssl;
  14730. if (tls == NULL) {
  14731. /* Need to store protocol in Thread Local Storage */
  14732. /* If there is no Thread Local Storage, don't use ALPN */
  14733. return SSL_TLSEXT_ERR_NOACK;
  14734. }
  14735. #if defined(USE_HTTP2)
  14736. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14737. if (enable_http2) {
  14738. alpn_proto_order = alpn_proto_order_http2;
  14739. }
  14740. #endif
  14741. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14742. /* check all accepted protocols in this order */
  14743. const char *alpn_proto = alpn_proto_order[j];
  14744. /* search input for matching protocol */
  14745. for (i = 0; i < inlen; i++) {
  14746. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14747. *out = in + i + 1;
  14748. *outlen = in[i];
  14749. tls->alpn_proto = alpn_proto;
  14750. return SSL_TLSEXT_ERR_OK;
  14751. }
  14752. }
  14753. }
  14754. /* Nothing found */
  14755. return SSL_TLSEXT_ERR_NOACK;
  14756. }
  14757. static int
  14758. next_protos_advertised_cb(SSL *ssl,
  14759. const unsigned char **data,
  14760. unsigned int *len,
  14761. void *arg)
  14762. {
  14763. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14764. *data = (const unsigned char *)alpn_proto_list;
  14765. *len = (unsigned int)strlen((const char *)data);
  14766. (void)ssl;
  14767. (void)dom_ctx;
  14768. return SSL_TLSEXT_ERR_OK;
  14769. }
  14770. static int
  14771. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14772. {
  14773. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14774. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14775. (const unsigned char *)alpn_proto_list,
  14776. alpn_len);
  14777. if (ret != 0) {
  14778. mg_cry_ctx_internal(phys_ctx,
  14779. "SSL_CTX_set_alpn_protos error: %s",
  14780. ssl_error());
  14781. }
  14782. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14783. alpn_select_cb,
  14784. (void *)dom_ctx);
  14785. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14786. next_protos_advertised_cb,
  14787. (void *)dom_ctx);
  14788. return ret;
  14789. }
  14790. #endif
  14791. /* Setup SSL CTX as required by CivetWeb */
  14792. static int
  14793. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14794. struct mg_domain_context *dom_ctx,
  14795. const char *pem,
  14796. const char *chain)
  14797. {
  14798. int callback_ret;
  14799. int should_verify_peer;
  14800. int peer_certificate_optional;
  14801. const char *ca_path;
  14802. const char *ca_file;
  14803. int use_default_verify_paths;
  14804. int verify_depth;
  14805. struct timespec now_mt;
  14806. md5_byte_t ssl_context_id[16];
  14807. md5_state_t md5state;
  14808. int protocol_ver;
  14809. int ssl_cache_timeout;
  14810. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14811. && !defined(NO_SSL_DL)
  14812. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14813. mg_cry_ctx_internal(phys_ctx,
  14814. "SSL_CTX_new (server) error: %s",
  14815. ssl_error());
  14816. return 0;
  14817. }
  14818. #else
  14819. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14820. mg_cry_ctx_internal(phys_ctx,
  14821. "SSL_CTX_new (server) error: %s",
  14822. ssl_error());
  14823. return 0;
  14824. }
  14825. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14826. #if defined(SSL_OP_NO_TLSv1_3)
  14827. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14828. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14829. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14830. | SSL_OP_NO_TLSv1_3);
  14831. #else
  14832. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14833. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14834. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14835. #endif
  14836. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14837. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14838. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14839. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14840. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14841. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14842. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14843. #if defined(SSL_OP_NO_RENEGOTIATION)
  14844. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14845. #endif
  14846. #if !defined(NO_SSL_DL)
  14847. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14848. #endif /* NO_SSL_DL */
  14849. /* In SSL documentation examples callback defined without const
  14850. * specifier 'void (*)(SSL *, int, int)' See:
  14851. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14852. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14853. * But in the source code const SSL is used:
  14854. * 'void (*)(const SSL *, int, int)' See:
  14855. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14856. * Problem about wrong documentation described, but not resolved:
  14857. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14858. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14859. * But when compiled with modern C++ compiler, correct const should be
  14860. * provided
  14861. */
  14862. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14863. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14864. ssl_servername_callback);
  14865. /* If a callback has been specified, call it. */
  14866. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14867. ? 0
  14868. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14869. phys_ctx->user_data));
  14870. /* If callback returns 0, civetweb sets up the SSL certificate.
  14871. * If it returns 1, civetweb assumes the calback already did this.
  14872. * If it returns -1, initializing ssl fails. */
  14873. if (callback_ret < 0) {
  14874. mg_cry_ctx_internal(phys_ctx,
  14875. "SSL callback returned error: %i",
  14876. callback_ret);
  14877. return 0;
  14878. }
  14879. if (callback_ret > 0) {
  14880. /* Callback did everything. */
  14881. return 1;
  14882. }
  14883. /* If a domain callback has been specified, call it. */
  14884. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14885. ? 0
  14886. : (phys_ctx->callbacks.init_ssl_domain(
  14887. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14888. dom_ctx->ssl_ctx,
  14889. phys_ctx->user_data));
  14890. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14891. * If it returns 1, civetweb assumes the calback already did this.
  14892. * If it returns -1, initializing ssl fails. */
  14893. if (callback_ret < 0) {
  14894. mg_cry_ctx_internal(phys_ctx,
  14895. "Domain SSL callback returned error: %i",
  14896. callback_ret);
  14897. return 0;
  14898. }
  14899. if (callback_ret > 0) {
  14900. /* Domain callback did everything. */
  14901. return 1;
  14902. }
  14903. /* Use some combination of start time, domain and port as a SSL
  14904. * context ID. This should be unique on the current machine. */
  14905. md5_init(&md5state);
  14906. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14907. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14908. md5_append(&md5state,
  14909. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14910. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14911. md5_append(&md5state,
  14912. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14913. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14914. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14915. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14916. md5_finish(&md5state, ssl_context_id);
  14917. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14918. (unsigned char *)ssl_context_id,
  14919. sizeof(ssl_context_id));
  14920. if (pem != NULL) {
  14921. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14922. return 0;
  14923. }
  14924. }
  14925. /* Should we support client certificates? */
  14926. /* Default is "no". */
  14927. should_verify_peer = 0;
  14928. peer_certificate_optional = 0;
  14929. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14930. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14931. /* Yes, they are mandatory */
  14932. should_verify_peer = 1;
  14933. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14934. "optional")
  14935. == 0) {
  14936. /* Yes, they are optional */
  14937. should_verify_peer = 1;
  14938. peer_certificate_optional = 1;
  14939. }
  14940. }
  14941. use_default_verify_paths =
  14942. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14943. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14944. == 0);
  14945. if (should_verify_peer) {
  14946. ca_path = dom_ctx->config[SSL_CA_PATH];
  14947. ca_file = dom_ctx->config[SSL_CA_FILE];
  14948. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14949. != 1) {
  14950. mg_cry_ctx_internal(phys_ctx,
  14951. "SSL_CTX_load_verify_locations error: %s "
  14952. "ssl_verify_peer requires setting "
  14953. "either ssl_ca_path or ssl_ca_file. "
  14954. "Is any of them present in the "
  14955. ".conf file?",
  14956. ssl_error());
  14957. return 0;
  14958. }
  14959. if (peer_certificate_optional) {
  14960. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14961. } else {
  14962. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14963. SSL_VERIFY_PEER
  14964. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14965. NULL);
  14966. }
  14967. if (use_default_verify_paths
  14968. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14969. mg_cry_ctx_internal(phys_ctx,
  14970. "SSL_CTX_set_default_verify_paths error: %s",
  14971. ssl_error());
  14972. return 0;
  14973. }
  14974. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14975. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14976. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14977. }
  14978. }
  14979. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14980. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14981. dom_ctx->config[SSL_CIPHER_LIST])
  14982. != 1) {
  14983. mg_cry_ctx_internal(phys_ctx,
  14984. "SSL_CTX_set_cipher_list error: %s",
  14985. ssl_error());
  14986. }
  14987. }
  14988. /* SSL session caching */
  14989. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14990. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14991. : 0);
  14992. if (ssl_cache_timeout > 0) {
  14993. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14994. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14995. * default */
  14996. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14997. }
  14998. #if defined(USE_ALPN)
  14999. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15000. #if !defined(NO_SSL_DL)
  15001. if (!tls_feature_missing[TLS_ALPN])
  15002. #endif
  15003. {
  15004. init_alpn(phys_ctx, dom_ctx);
  15005. }
  15006. #endif
  15007. return 1;
  15008. }
  15009. /* Check if SSL is required.
  15010. * If so, dynamically load SSL library
  15011. * and set up ctx->ssl_ctx pointer. */
  15012. static int
  15013. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15014. {
  15015. void *ssl_ctx = 0;
  15016. int callback_ret;
  15017. const char *pem;
  15018. const char *chain;
  15019. char ebuf[128];
  15020. if (!phys_ctx) {
  15021. return 0;
  15022. }
  15023. if (!dom_ctx) {
  15024. dom_ctx = &(phys_ctx->dd);
  15025. }
  15026. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15027. /* No SSL port is set. No need to setup SSL. */
  15028. return 1;
  15029. }
  15030. /* Check for external SSL_CTX */
  15031. callback_ret =
  15032. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15033. ? 0
  15034. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15035. phys_ctx->user_data));
  15036. if (callback_ret < 0) {
  15037. /* Callback exists and returns <0: Initializing failed. */
  15038. mg_cry_ctx_internal(phys_ctx,
  15039. "external_ssl_ctx callback returned error: %i",
  15040. callback_ret);
  15041. return 0;
  15042. } else if (callback_ret > 0) {
  15043. /* Callback exists and returns >0: Initializing complete,
  15044. * civetweb should not modify the SSL context. */
  15045. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15046. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15047. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15048. return 0;
  15049. }
  15050. return 1;
  15051. }
  15052. /* If the callback does not exist or return 0, civetweb must initialize
  15053. * the SSL context. Handle "domain" callback next. */
  15054. /* Check for external domain SSL_CTX callback. */
  15055. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15056. ? 0
  15057. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15058. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15059. &ssl_ctx,
  15060. phys_ctx->user_data));
  15061. if (callback_ret < 0) {
  15062. /* Callback < 0: Error. Abort init. */
  15063. mg_cry_ctx_internal(
  15064. phys_ctx,
  15065. "external_ssl_ctx_domain callback returned error: %i",
  15066. callback_ret);
  15067. return 0;
  15068. } else if (callback_ret > 0) {
  15069. /* Callback > 0: Consider init done. */
  15070. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15071. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15072. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15073. return 0;
  15074. }
  15075. return 1;
  15076. }
  15077. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15078. * 0, CivetWeb should continue initializing SSL */
  15079. /* If PEM file is not specified and the init_ssl callbacks
  15080. * are not specified, setup will fail. */
  15081. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15082. && (phys_ctx->callbacks.init_ssl == NULL)
  15083. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15084. /* No certificate and no init_ssl callbacks:
  15085. * Essential data to set up TLS is missing.
  15086. */
  15087. mg_cry_ctx_internal(phys_ctx,
  15088. "Initializing SSL failed: -%s is not set",
  15089. config_options[SSL_CERTIFICATE].name);
  15090. return 0;
  15091. }
  15092. /* If a certificate chain is configured, use it. */
  15093. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15094. if (chain == NULL) {
  15095. /* Default: certificate chain in PEM file */
  15096. chain = pem;
  15097. }
  15098. if ((chain != NULL) && (*chain == 0)) {
  15099. /* If the chain is an empty string, don't use it. */
  15100. chain = NULL;
  15101. }
  15102. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15103. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15104. return 0;
  15105. }
  15106. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15107. }
  15108. static void
  15109. uninitialize_openssl(void)
  15110. {
  15111. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15112. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15113. /* Shutdown according to
  15114. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15115. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15116. */
  15117. CONF_modules_unload(1);
  15118. #else
  15119. int i;
  15120. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15121. /* Shutdown according to
  15122. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15123. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15124. */
  15125. CRYPTO_set_locking_callback(NULL);
  15126. CRYPTO_set_id_callback(NULL);
  15127. ENGINE_cleanup();
  15128. CONF_modules_unload(1);
  15129. ERR_free_strings();
  15130. EVP_cleanup();
  15131. CRYPTO_cleanup_all_ex_data();
  15132. OPENSSL_REMOVE_THREAD_STATE();
  15133. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15134. pthread_mutex_destroy(&ssl_mutexes[i]);
  15135. }
  15136. mg_free(ssl_mutexes);
  15137. ssl_mutexes = NULL;
  15138. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15139. }
  15140. }
  15141. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15142. #if !defined(NO_FILESYSTEMS)
  15143. static int
  15144. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15145. {
  15146. if (phys_ctx) {
  15147. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15148. const char *path;
  15149. struct mg_connection fc;
  15150. if (!dom_ctx) {
  15151. dom_ctx = &(phys_ctx->dd);
  15152. }
  15153. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15154. if ((path != NULL)
  15155. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15156. mg_cry_ctx_internal(phys_ctx,
  15157. "Cannot open %s: %s",
  15158. path,
  15159. strerror(ERRNO));
  15160. return 0;
  15161. }
  15162. return 1;
  15163. }
  15164. return 0;
  15165. }
  15166. #endif /* NO_FILESYSTEMS */
  15167. static int
  15168. set_acl_option(struct mg_context *phys_ctx)
  15169. {
  15170. union usa sa;
  15171. memset(&sa, 0, sizeof(sa));
  15172. #if defined(USE_IPV6)
  15173. sa.sin6.sin6_family = AF_INET6;
  15174. #else
  15175. sa.sin.sin_family = AF_INET;
  15176. #endif
  15177. return check_acl(phys_ctx, &sa) != -1;
  15178. }
  15179. static void
  15180. reset_per_request_attributes(struct mg_connection *conn)
  15181. {
  15182. if (!conn) {
  15183. return;
  15184. }
  15185. conn->num_bytes_sent = conn->consumed_content = 0;
  15186. conn->path_info = NULL;
  15187. conn->status_code = -1;
  15188. conn->content_len = -1;
  15189. conn->is_chunked = 0;
  15190. conn->must_close = 0;
  15191. conn->request_len = 0;
  15192. conn->request_state = 0;
  15193. conn->throttle = 0;
  15194. conn->accept_gzip = 0;
  15195. conn->response_info.content_length = conn->request_info.content_length = -1;
  15196. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15197. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15198. conn->response_info.status_text = NULL;
  15199. conn->response_info.status_code = 0;
  15200. conn->request_info.remote_user = NULL;
  15201. conn->request_info.request_method = NULL;
  15202. conn->request_info.request_uri = NULL;
  15203. /* Free cleaned local URI (if any) */
  15204. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15205. mg_free((void *)conn->request_info.local_uri);
  15206. conn->request_info.local_uri = NULL;
  15207. }
  15208. conn->request_info.local_uri = NULL;
  15209. #if defined(USE_SERVER_STATS)
  15210. conn->processing_time = 0;
  15211. #endif
  15212. }
  15213. static int
  15214. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15215. {
  15216. if ((so->lsa.sa.sa_family == AF_INET)
  15217. || (so->lsa.sa.sa_family == AF_INET6)) {
  15218. /* Only for TCP sockets */
  15219. if (setsockopt(so->sock,
  15220. IPPROTO_TCP,
  15221. TCP_NODELAY,
  15222. (SOCK_OPT_TYPE)&nodelay_on,
  15223. sizeof(nodelay_on))
  15224. != 0) {
  15225. /* Error */
  15226. return 1;
  15227. }
  15228. }
  15229. /* OK */
  15230. return 0;
  15231. }
  15232. #if !defined(__ZEPHYR__)
  15233. static void
  15234. close_socket_gracefully(struct mg_connection *conn)
  15235. {
  15236. #if defined(_WIN32)
  15237. char buf[MG_BUF_LEN];
  15238. int n;
  15239. #endif
  15240. struct linger linger;
  15241. int error_code = 0;
  15242. int linger_timeout = -2;
  15243. socklen_t opt_len = sizeof(error_code);
  15244. if (!conn) {
  15245. return;
  15246. }
  15247. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15248. * "Note that enabling a nonzero timeout on a nonblocking socket
  15249. * is not recommended.", so set it to blocking now */
  15250. set_blocking_mode(conn->client.sock);
  15251. /* Send FIN to the client */
  15252. shutdown(conn->client.sock, SHUTDOWN_WR);
  15253. #if defined(_WIN32)
  15254. /* Read and discard pending incoming data. If we do not do that and
  15255. * close
  15256. * the socket, the data in the send buffer may be discarded. This
  15257. * behaviour is seen on Windows, when client keeps sending data
  15258. * when server decides to close the connection; then when client
  15259. * does recv() it gets no data back. */
  15260. do {
  15261. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15262. } while (n > 0);
  15263. #endif
  15264. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15265. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15266. }
  15267. /* Set linger option according to configuration */
  15268. if (linger_timeout >= 0) {
  15269. /* Set linger option to avoid socket hanging out after close. This
  15270. * prevent ephemeral port exhaust problem under high QPS. */
  15271. linger.l_onoff = 1;
  15272. #if defined(_MSC_VER)
  15273. #pragma warning(push)
  15274. #pragma warning(disable : 4244)
  15275. #endif
  15276. #if defined(GCC_DIAGNOSTIC)
  15277. #pragma GCC diagnostic push
  15278. #pragma GCC diagnostic ignored "-Wconversion"
  15279. #endif
  15280. /* Data type of linger structure elements may differ,
  15281. * so we don't know what cast we need here.
  15282. * Disable type conversion warnings. */
  15283. linger.l_linger = (linger_timeout + 999) / 1000;
  15284. #if defined(GCC_DIAGNOSTIC)
  15285. #pragma GCC diagnostic pop
  15286. #endif
  15287. #if defined(_MSC_VER)
  15288. #pragma warning(pop)
  15289. #endif
  15290. } else {
  15291. linger.l_onoff = 0;
  15292. linger.l_linger = 0;
  15293. }
  15294. if (linger_timeout < -1) {
  15295. /* Default: don't configure any linger */
  15296. } else if (getsockopt(conn->client.sock,
  15297. SOL_SOCKET,
  15298. SO_ERROR,
  15299. #if defined(_WIN32) /* WinSock uses different data type here */
  15300. (char *)&error_code,
  15301. #else
  15302. &error_code,
  15303. #endif
  15304. &opt_len)
  15305. != 0) {
  15306. /* Cannot determine if socket is already closed. This should
  15307. * not occur and never did in a test. Log an error message
  15308. * and continue. */
  15309. mg_cry_internal(conn,
  15310. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15311. __func__,
  15312. strerror(ERRNO));
  15313. #if defined(_WIN32)
  15314. } else if (error_code == WSAECONNRESET) {
  15315. #else
  15316. } else if (error_code == ECONNRESET) {
  15317. #endif
  15318. /* Socket already closed by client/peer, close socket without linger
  15319. */
  15320. } else {
  15321. /* Set linger timeout */
  15322. if (setsockopt(conn->client.sock,
  15323. SOL_SOCKET,
  15324. SO_LINGER,
  15325. (char *)&linger,
  15326. sizeof(linger))
  15327. != 0) {
  15328. mg_cry_internal(
  15329. conn,
  15330. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15331. __func__,
  15332. linger.l_onoff,
  15333. linger.l_linger,
  15334. strerror(ERRNO));
  15335. }
  15336. }
  15337. /* Now we know that our FIN is ACK-ed, safe to close */
  15338. closesocket(conn->client.sock);
  15339. conn->client.sock = INVALID_SOCKET;
  15340. }
  15341. #endif
  15342. static void
  15343. close_connection(struct mg_connection *conn)
  15344. {
  15345. #if defined(USE_SERVER_STATS)
  15346. conn->conn_state = 6; /* to close */
  15347. #endif
  15348. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15349. if (conn->lua_websocket_state) {
  15350. lua_websocket_close(conn, conn->lua_websocket_state);
  15351. conn->lua_websocket_state = NULL;
  15352. }
  15353. #endif
  15354. mg_lock_connection(conn);
  15355. /* Set close flag, so keep-alive loops will stop */
  15356. conn->must_close = 1;
  15357. /* call the connection_close callback if assigned */
  15358. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15359. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15360. conn->phys_ctx->callbacks.connection_close(conn);
  15361. }
  15362. }
  15363. /* Reset user data, after close callback is called.
  15364. * Do not reuse it. If the user needs a destructor,
  15365. * it must be done in the connection_close callback. */
  15366. mg_set_user_connection_data(conn, NULL);
  15367. #if defined(USE_SERVER_STATS)
  15368. conn->conn_state = 7; /* closing */
  15369. #endif
  15370. #if defined(USE_MBEDTLS)
  15371. if (conn->ssl != NULL) {
  15372. mbed_ssl_close(conn->ssl);
  15373. conn->ssl = NULL;
  15374. }
  15375. #elif !defined(NO_SSL)
  15376. if (conn->ssl != NULL) {
  15377. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15378. */
  15379. SSL_shutdown(conn->ssl);
  15380. SSL_free(conn->ssl);
  15381. OPENSSL_REMOVE_THREAD_STATE();
  15382. conn->ssl = NULL;
  15383. }
  15384. #endif
  15385. if (conn->client.sock != INVALID_SOCKET) {
  15386. #if defined(__ZEPHYR__)
  15387. closesocket(conn->client.sock);
  15388. #else
  15389. close_socket_gracefully(conn);
  15390. #endif
  15391. conn->client.sock = INVALID_SOCKET;
  15392. }
  15393. /* call the connection_closed callback if assigned */
  15394. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15395. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15396. conn->phys_ctx->callbacks.connection_closed(conn);
  15397. }
  15398. }
  15399. mg_unlock_connection(conn);
  15400. #if defined(USE_SERVER_STATS)
  15401. conn->conn_state = 8; /* closed */
  15402. #endif
  15403. }
  15404. void
  15405. mg_close_connection(struct mg_connection *conn)
  15406. {
  15407. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15408. return;
  15409. }
  15410. #if defined(USE_WEBSOCKET)
  15411. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15412. if (conn->in_websocket_handling) {
  15413. /* Set close flag, so the server thread can exit. */
  15414. conn->must_close = 1;
  15415. return;
  15416. }
  15417. }
  15418. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15419. unsigned int i;
  15420. /* client context: loops must end */
  15421. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15422. conn->must_close = 1;
  15423. /* We need to get the client thread out of the select/recv call
  15424. * here. */
  15425. /* Since we use a sleep quantum of some seconds to check for recv
  15426. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15427. /* join worker thread */
  15428. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15429. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15430. }
  15431. }
  15432. #endif /* defined(USE_WEBSOCKET) */
  15433. close_connection(conn);
  15434. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15435. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15436. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15437. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15438. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15439. }
  15440. #endif
  15441. #if defined(USE_WEBSOCKET)
  15442. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15443. mg_free(conn->phys_ctx->worker_threadids);
  15444. (void)pthread_mutex_destroy(&conn->mutex);
  15445. mg_free(conn);
  15446. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15447. (void)pthread_mutex_destroy(&conn->mutex);
  15448. mg_free(conn);
  15449. }
  15450. #else
  15451. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15452. (void)pthread_mutex_destroy(&conn->mutex);
  15453. mg_free(conn);
  15454. }
  15455. #endif /* defined(USE_WEBSOCKET) */
  15456. }
  15457. static struct mg_connection *
  15458. mg_connect_client_impl(const struct mg_client_options *client_options,
  15459. int use_ssl,
  15460. char *ebuf,
  15461. size_t ebuf_len)
  15462. {
  15463. struct mg_connection *conn = NULL;
  15464. SOCKET sock;
  15465. union usa sa;
  15466. struct sockaddr *psa;
  15467. socklen_t len;
  15468. unsigned max_req_size =
  15469. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15470. /* Size of structures, aligned to 8 bytes */
  15471. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15472. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15473. conn =
  15474. (struct mg_connection *)mg_calloc(1,
  15475. conn_size + ctx_size + max_req_size);
  15476. if (conn == NULL) {
  15477. mg_snprintf(NULL,
  15478. NULL, /* No truncation check for ebuf */
  15479. ebuf,
  15480. ebuf_len,
  15481. "calloc(): %s",
  15482. strerror(ERRNO));
  15483. return NULL;
  15484. }
  15485. #if defined(GCC_DIAGNOSTIC)
  15486. #pragma GCC diagnostic push
  15487. #pragma GCC diagnostic ignored "-Wcast-align"
  15488. #endif /* defined(GCC_DIAGNOSTIC) */
  15489. /* conn_size is aligned to 8 bytes */
  15490. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15491. #if defined(GCC_DIAGNOSTIC)
  15492. #pragma GCC diagnostic pop
  15493. #endif /* defined(GCC_DIAGNOSTIC) */
  15494. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15495. conn->buf_size = (int)max_req_size;
  15496. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15497. conn->dom_ctx = &(conn->phys_ctx->dd);
  15498. if (!connect_socket(conn->phys_ctx,
  15499. client_options->host,
  15500. client_options->port,
  15501. use_ssl,
  15502. ebuf,
  15503. ebuf_len,
  15504. &sock,
  15505. &sa)) {
  15506. /* ebuf is set by connect_socket,
  15507. * free all memory and return NULL; */
  15508. mg_free(conn);
  15509. return NULL;
  15510. }
  15511. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15512. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15513. && !defined(NO_SSL_DL)
  15514. if (use_ssl
  15515. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15516. == NULL) {
  15517. mg_snprintf(NULL,
  15518. NULL, /* No truncation check for ebuf */
  15519. ebuf,
  15520. ebuf_len,
  15521. "SSL_CTX_new error: %s",
  15522. ssl_error());
  15523. closesocket(sock);
  15524. mg_free(conn);
  15525. return NULL;
  15526. }
  15527. #else
  15528. if (use_ssl
  15529. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15530. == NULL) {
  15531. mg_snprintf(NULL,
  15532. NULL, /* No truncation check for ebuf */
  15533. ebuf,
  15534. ebuf_len,
  15535. "SSL_CTX_new error: %s",
  15536. ssl_error());
  15537. closesocket(sock);
  15538. mg_free(conn);
  15539. return NULL;
  15540. }
  15541. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15542. #endif /* NO_SSL */
  15543. #if defined(USE_IPV6)
  15544. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15545. : sizeof(conn->client.rsa.sin6);
  15546. psa = (sa.sa.sa_family == AF_INET)
  15547. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15548. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15549. #else
  15550. len = sizeof(conn->client.rsa.sin);
  15551. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15552. #endif
  15553. conn->client.sock = sock;
  15554. conn->client.lsa = sa;
  15555. if (getsockname(sock, psa, &len) != 0) {
  15556. mg_cry_internal(conn,
  15557. "%s: getsockname() failed: %s",
  15558. __func__,
  15559. strerror(ERRNO));
  15560. }
  15561. conn->client.is_ssl = use_ssl ? 1 : 0;
  15562. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15563. mg_snprintf(NULL,
  15564. NULL, /* No truncation check for ebuf */
  15565. ebuf,
  15566. ebuf_len,
  15567. "Can not create mutex");
  15568. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15569. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15570. #endif
  15571. closesocket(sock);
  15572. mg_free(conn);
  15573. return NULL;
  15574. }
  15575. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15576. if (use_ssl) {
  15577. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15578. * SSL_CTX_set_verify call is needed to switch off server
  15579. * certificate checking, which is off by default in OpenSSL and
  15580. * on in yaSSL. */
  15581. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15582. * SSL_VERIFY_PEER, verify_ssl_server); */
  15583. if (client_options->client_cert) {
  15584. if (!ssl_use_pem_file(conn->phys_ctx,
  15585. conn->dom_ctx,
  15586. client_options->client_cert,
  15587. NULL)) {
  15588. mg_snprintf(NULL,
  15589. NULL, /* No truncation check for ebuf */
  15590. ebuf,
  15591. ebuf_len,
  15592. "Can not use SSL client certificate");
  15593. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15594. closesocket(sock);
  15595. mg_free(conn);
  15596. return NULL;
  15597. }
  15598. }
  15599. if (client_options->server_cert) {
  15600. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15601. client_options->server_cert,
  15602. NULL)
  15603. != 1) {
  15604. mg_cry_internal(conn,
  15605. "SSL_CTX_load_verify_locations error: %s ",
  15606. ssl_error());
  15607. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15608. closesocket(sock);
  15609. mg_free(conn);
  15610. return NULL;
  15611. }
  15612. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15613. } else {
  15614. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15615. }
  15616. if (!sslize(conn, SSL_connect, client_options)) {
  15617. mg_snprintf(NULL,
  15618. NULL, /* No truncation check for ebuf */
  15619. ebuf,
  15620. ebuf_len,
  15621. "SSL connection error");
  15622. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15623. closesocket(sock);
  15624. mg_free(conn);
  15625. return NULL;
  15626. }
  15627. }
  15628. #endif
  15629. return conn;
  15630. }
  15631. CIVETWEB_API struct mg_connection *
  15632. mg_connect_client_secure(const struct mg_client_options *client_options,
  15633. char *error_buffer,
  15634. size_t error_buffer_size)
  15635. {
  15636. return mg_connect_client_impl(client_options,
  15637. 1,
  15638. error_buffer,
  15639. error_buffer_size);
  15640. }
  15641. struct mg_connection *
  15642. mg_connect_client(const char *host,
  15643. int port,
  15644. int use_ssl,
  15645. char *error_buffer,
  15646. size_t error_buffer_size)
  15647. {
  15648. struct mg_client_options opts;
  15649. memset(&opts, 0, sizeof(opts));
  15650. opts.host = host;
  15651. opts.port = port;
  15652. if (use_ssl) {
  15653. opts.host_name = host;
  15654. }
  15655. return mg_connect_client_impl(&opts,
  15656. use_ssl,
  15657. error_buffer,
  15658. error_buffer_size);
  15659. }
  15660. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15661. struct mg_connection *
  15662. mg_connect_client2(const char *host,
  15663. const char *protocol,
  15664. int port,
  15665. const char *path,
  15666. struct mg_init_data *init,
  15667. struct mg_error_data *error)
  15668. {
  15669. (void)path;
  15670. (void)init;
  15671. int is_ssl, is_ws;
  15672. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15673. if (error != NULL) {
  15674. error->code = 0;
  15675. if (error->text_buffer_size > 0) {
  15676. *error->text = 0;
  15677. }
  15678. }
  15679. if ((host == NULL) || (protocol == NULL)) {
  15680. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15681. mg_snprintf(NULL,
  15682. NULL, /* No truncation check for error buffers */
  15683. error->text,
  15684. error->text_buffer_size,
  15685. "%s",
  15686. "Invalid parameters");
  15687. }
  15688. return NULL;
  15689. }
  15690. /* check all known protocolls */
  15691. if (!mg_strcasecmp(protocol, "http")) {
  15692. is_ssl = 0;
  15693. is_ws = 0;
  15694. } else if (!mg_strcasecmp(protocol, "https")) {
  15695. is_ssl = 1;
  15696. is_ws = 0;
  15697. #if defined(USE_WEBSOCKET)
  15698. } else if (!mg_strcasecmp(protocol, "ws")) {
  15699. is_ssl = 0;
  15700. is_ws = 1;
  15701. } else if (!mg_strcasecmp(protocol, "wss")) {
  15702. is_ssl = 1;
  15703. is_ws = 1;
  15704. #endif
  15705. } else {
  15706. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15707. mg_snprintf(NULL,
  15708. NULL, /* No truncation check for error buffers */
  15709. error->text,
  15710. error->text_buffer_size,
  15711. "Protocol %s not supported",
  15712. protocol);
  15713. }
  15714. return NULL;
  15715. }
  15716. /* TODO: The current implementation here just calls the old
  15717. * implementations, without using any new options. This is just a first
  15718. * step to test the new interfaces. */
  15719. #if defined(USE_WEBSOCKET)
  15720. if (is_ws) {
  15721. /* TODO: implement all options */
  15722. return mg_connect_websocket_client(
  15723. host,
  15724. port,
  15725. is_ssl,
  15726. ((error != NULL) ? error->text : NULL),
  15727. ((error != NULL) ? error->text_buffer_size : 0),
  15728. (path ? path : ""),
  15729. NULL /* TODO: origin */,
  15730. experimental_websocket_client_data_wrapper,
  15731. experimental_websocket_client_close_wrapper,
  15732. (void *)init->callbacks);
  15733. }
  15734. #else
  15735. (void)is_ws;
  15736. #endif
  15737. /* TODO: all additional options */
  15738. struct mg_client_options opts;
  15739. memset(&opts, 0, sizeof(opts));
  15740. opts.host = host;
  15741. opts.port = port;
  15742. return mg_connect_client_impl(&opts,
  15743. is_ssl,
  15744. ((error != NULL) ? error->text : NULL),
  15745. ((error != NULL) ? error->text_buffer_size
  15746. : 0));
  15747. }
  15748. #endif
  15749. static const struct {
  15750. const char *proto;
  15751. size_t proto_len;
  15752. unsigned default_port;
  15753. } abs_uri_protocols[] = {{"http://", 7, 80},
  15754. {"https://", 8, 443},
  15755. {"ws://", 5, 80},
  15756. {"wss://", 6, 443},
  15757. {NULL, 0, 0}};
  15758. /* Check if the uri is valid.
  15759. * return 0 for invalid uri,
  15760. * return 1 for *,
  15761. * return 2 for relative uri,
  15762. * return 3 for absolute uri without port,
  15763. * return 4 for absolute uri with port */
  15764. static int
  15765. get_uri_type(const char *uri)
  15766. {
  15767. int i;
  15768. const char *hostend, *portbegin;
  15769. char *portend;
  15770. unsigned long port;
  15771. /* According to the HTTP standard
  15772. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15773. * URI can be an asterisk (*) or should start with slash (relative uri),
  15774. * or it should start with the protocol (absolute uri). */
  15775. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15776. /* asterisk */
  15777. return 1;
  15778. }
  15779. /* Valid URIs according to RFC 3986
  15780. * (https://www.ietf.org/rfc/rfc3986.txt)
  15781. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15782. * and unreserved characters A-Z a-z 0-9 and -._~
  15783. * and % encoded symbols.
  15784. */
  15785. for (i = 0; uri[i] != 0; i++) {
  15786. if (uri[i] < 33) {
  15787. /* control characters and spaces are invalid */
  15788. return 0;
  15789. }
  15790. /* Allow everything else here (See #894) */
  15791. }
  15792. /* A relative uri starts with a / character */
  15793. if (uri[0] == '/') {
  15794. /* relative uri */
  15795. return 2;
  15796. }
  15797. /* It could be an absolute uri: */
  15798. /* This function only checks if the uri is valid, not if it is
  15799. * addressing the current server. So civetweb can also be used
  15800. * as a proxy server. */
  15801. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15802. if (mg_strncasecmp(uri,
  15803. abs_uri_protocols[i].proto,
  15804. abs_uri_protocols[i].proto_len)
  15805. == 0) {
  15806. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15807. if (!hostend) {
  15808. return 0;
  15809. }
  15810. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15811. if (!portbegin) {
  15812. return 3;
  15813. }
  15814. port = strtoul(portbegin + 1, &portend, 10);
  15815. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15816. return 0;
  15817. }
  15818. return 4;
  15819. }
  15820. }
  15821. return 0;
  15822. }
  15823. /* Return NULL or the relative uri at the current server */
  15824. static const char *
  15825. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15826. {
  15827. const char *server_domain;
  15828. size_t server_domain_len;
  15829. size_t request_domain_len = 0;
  15830. unsigned long port = 0;
  15831. int i, auth_domain_check_enabled;
  15832. const char *hostbegin = NULL;
  15833. const char *hostend = NULL;
  15834. const char *portbegin;
  15835. char *portend;
  15836. auth_domain_check_enabled =
  15837. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15838. /* DNS is case insensitive, so use case insensitive string compare here
  15839. */
  15840. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15841. if (mg_strncasecmp(uri,
  15842. abs_uri_protocols[i].proto,
  15843. abs_uri_protocols[i].proto_len)
  15844. == 0) {
  15845. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15846. hostend = strchr(hostbegin, '/');
  15847. if (!hostend) {
  15848. return 0;
  15849. }
  15850. portbegin = strchr(hostbegin, ':');
  15851. if ((!portbegin) || (portbegin > hostend)) {
  15852. port = abs_uri_protocols[i].default_port;
  15853. request_domain_len = (size_t)(hostend - hostbegin);
  15854. } else {
  15855. port = strtoul(portbegin + 1, &portend, 10);
  15856. if ((portend != hostend) || (port <= 0)
  15857. || !is_valid_port(port)) {
  15858. return 0;
  15859. }
  15860. request_domain_len = (size_t)(portbegin - hostbegin);
  15861. }
  15862. /* protocol found, port set */
  15863. break;
  15864. }
  15865. }
  15866. if (!port) {
  15867. /* port remains 0 if the protocol is not found */
  15868. return 0;
  15869. }
  15870. /* Check if the request is directed to a different server. */
  15871. /* First check if the port is the same. */
  15872. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15873. /* Request is directed to a different port */
  15874. return 0;
  15875. }
  15876. /* Finally check if the server corresponds to the authentication
  15877. * domain of the server (the server domain).
  15878. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15879. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15880. * but do not allow substrings (like
  15881. * http://notmydomain.com/path/file.ext
  15882. * or http://mydomain.com.fake/path/file.ext).
  15883. */
  15884. if (auth_domain_check_enabled) {
  15885. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15886. server_domain_len = strlen(server_domain);
  15887. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15888. return 0;
  15889. }
  15890. if ((request_domain_len == server_domain_len)
  15891. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15892. /* Request is directed to this server - full name match. */
  15893. } else {
  15894. if (request_domain_len < (server_domain_len + 2)) {
  15895. /* Request is directed to another server: The server name
  15896. * is longer than the request name.
  15897. * Drop this case here to avoid overflows in the
  15898. * following checks. */
  15899. return 0;
  15900. }
  15901. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15902. /* Request is directed to another server: It could be a
  15903. * substring
  15904. * like notmyserver.com */
  15905. return 0;
  15906. }
  15907. if (0
  15908. != memcmp(server_domain,
  15909. hostbegin + request_domain_len - server_domain_len,
  15910. server_domain_len)) {
  15911. /* Request is directed to another server:
  15912. * The server name is different. */
  15913. return 0;
  15914. }
  15915. }
  15916. }
  15917. return hostend;
  15918. }
  15919. static int
  15920. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15921. {
  15922. if (ebuf_len > 0) {
  15923. ebuf[0] = '\0';
  15924. }
  15925. *err = 0;
  15926. reset_per_request_attributes(conn);
  15927. if (!conn) {
  15928. mg_snprintf(conn,
  15929. NULL, /* No truncation check for ebuf */
  15930. ebuf,
  15931. ebuf_len,
  15932. "%s",
  15933. "Internal error");
  15934. *err = 500;
  15935. return 0;
  15936. }
  15937. /* Set the time the request was received. This value should be used for
  15938. * timeouts. */
  15939. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15940. conn->request_len =
  15941. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15942. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15943. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15944. mg_snprintf(conn,
  15945. NULL, /* No truncation check for ebuf */
  15946. ebuf,
  15947. ebuf_len,
  15948. "%s",
  15949. "Invalid message size");
  15950. *err = 500;
  15951. return 0;
  15952. }
  15953. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15954. mg_snprintf(conn,
  15955. NULL, /* No truncation check for ebuf */
  15956. ebuf,
  15957. ebuf_len,
  15958. "%s",
  15959. "Message too large");
  15960. *err = 413;
  15961. return 0;
  15962. }
  15963. if (conn->request_len <= 0) {
  15964. if (conn->data_len > 0) {
  15965. mg_snprintf(conn,
  15966. NULL, /* No truncation check for ebuf */
  15967. ebuf,
  15968. ebuf_len,
  15969. "%s",
  15970. "Malformed message");
  15971. *err = 400;
  15972. } else {
  15973. /* Server did not recv anything -> just close the connection */
  15974. conn->must_close = 1;
  15975. mg_snprintf(conn,
  15976. NULL, /* No truncation check for ebuf */
  15977. ebuf,
  15978. ebuf_len,
  15979. "%s",
  15980. "No data received");
  15981. *err = 0;
  15982. }
  15983. return 0;
  15984. }
  15985. return 1;
  15986. }
  15987. static int
  15988. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15989. {
  15990. const char *cl;
  15991. conn->connection_type =
  15992. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15993. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15994. return 0;
  15995. }
  15996. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15997. <= 0) {
  15998. mg_snprintf(conn,
  15999. NULL, /* No truncation check for ebuf */
  16000. ebuf,
  16001. ebuf_len,
  16002. "%s",
  16003. "Bad request");
  16004. *err = 400;
  16005. return 0;
  16006. }
  16007. /* Message is a valid request */
  16008. if (!switch_domain_context(conn)) {
  16009. mg_snprintf(conn,
  16010. NULL, /* No truncation check for ebuf */
  16011. ebuf,
  16012. ebuf_len,
  16013. "%s",
  16014. "Bad request: Host mismatch");
  16015. *err = 400;
  16016. return 0;
  16017. }
  16018. #if USE_ZLIB
  16019. if (((cl = get_header(conn->request_info.http_headers,
  16020. conn->request_info.num_headers,
  16021. "Accept-Encoding"))
  16022. != NULL)
  16023. && strstr(cl, "gzip")) {
  16024. conn->accept_gzip = 1;
  16025. }
  16026. #endif
  16027. if (((cl = get_header(conn->request_info.http_headers,
  16028. conn->request_info.num_headers,
  16029. "Transfer-Encoding"))
  16030. != NULL)
  16031. && mg_strcasecmp(cl, "identity")) {
  16032. if (mg_strcasecmp(cl, "chunked")) {
  16033. mg_snprintf(conn,
  16034. NULL, /* No truncation check for ebuf */
  16035. ebuf,
  16036. ebuf_len,
  16037. "%s",
  16038. "Bad request");
  16039. *err = 400;
  16040. return 0;
  16041. }
  16042. conn->is_chunked = 1;
  16043. conn->content_len = 0; /* not yet read */
  16044. } else if ((cl = get_header(conn->request_info.http_headers,
  16045. conn->request_info.num_headers,
  16046. "Content-Length"))
  16047. != NULL) {
  16048. /* Request has content length set */
  16049. char *endptr = NULL;
  16050. conn->content_len = strtoll(cl, &endptr, 10);
  16051. if ((endptr == cl) || (conn->content_len < 0)) {
  16052. mg_snprintf(conn,
  16053. NULL, /* No truncation check for ebuf */
  16054. ebuf,
  16055. ebuf_len,
  16056. "%s",
  16057. "Bad request");
  16058. *err = 411;
  16059. return 0;
  16060. }
  16061. /* Publish the content length back to the request info. */
  16062. conn->request_info.content_length = conn->content_len;
  16063. } else {
  16064. /* There is no exception, see RFC7230. */
  16065. conn->content_len = 0;
  16066. }
  16067. return 1;
  16068. }
  16069. /* conn is assumed to be valid in this internal function */
  16070. static int
  16071. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16072. {
  16073. const char *cl;
  16074. conn->connection_type =
  16075. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16076. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16077. return 0;
  16078. }
  16079. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16080. <= 0) {
  16081. mg_snprintf(conn,
  16082. NULL, /* No truncation check for ebuf */
  16083. ebuf,
  16084. ebuf_len,
  16085. "%s",
  16086. "Bad response");
  16087. *err = 400;
  16088. return 0;
  16089. }
  16090. /* Message is a valid response */
  16091. if (((cl = get_header(conn->response_info.http_headers,
  16092. conn->response_info.num_headers,
  16093. "Transfer-Encoding"))
  16094. != NULL)
  16095. && mg_strcasecmp(cl, "identity")) {
  16096. if (mg_strcasecmp(cl, "chunked")) {
  16097. mg_snprintf(conn,
  16098. NULL, /* No truncation check for ebuf */
  16099. ebuf,
  16100. ebuf_len,
  16101. "%s",
  16102. "Bad request");
  16103. *err = 400;
  16104. return 0;
  16105. }
  16106. conn->is_chunked = 1;
  16107. conn->content_len = 0; /* not yet read */
  16108. } else if ((cl = get_header(conn->response_info.http_headers,
  16109. conn->response_info.num_headers,
  16110. "Content-Length"))
  16111. != NULL) {
  16112. char *endptr = NULL;
  16113. conn->content_len = strtoll(cl, &endptr, 10);
  16114. if ((endptr == cl) || (conn->content_len < 0)) {
  16115. mg_snprintf(conn,
  16116. NULL, /* No truncation check for ebuf */
  16117. ebuf,
  16118. ebuf_len,
  16119. "%s",
  16120. "Bad request");
  16121. *err = 411;
  16122. return 0;
  16123. }
  16124. /* Publish the content length back to the response info. */
  16125. conn->response_info.content_length = conn->content_len;
  16126. /* TODO: check if it is still used in response_info */
  16127. conn->request_info.content_length = conn->content_len;
  16128. /* TODO: we should also consider HEAD method */
  16129. if (conn->response_info.status_code == 304) {
  16130. conn->content_len = 0;
  16131. }
  16132. } else {
  16133. /* TODO: we should also consider HEAD method */
  16134. if (((conn->response_info.status_code >= 100)
  16135. && (conn->response_info.status_code <= 199))
  16136. || (conn->response_info.status_code == 204)
  16137. || (conn->response_info.status_code == 304)) {
  16138. conn->content_len = 0;
  16139. } else {
  16140. conn->content_len = -1; /* unknown content length */
  16141. }
  16142. }
  16143. return 1;
  16144. }
  16145. int
  16146. mg_get_response(struct mg_connection *conn,
  16147. char *ebuf,
  16148. size_t ebuf_len,
  16149. int timeout)
  16150. {
  16151. int err, ret;
  16152. char txt[32]; /* will not overflow */
  16153. char *save_timeout;
  16154. char *new_timeout;
  16155. if (ebuf_len > 0) {
  16156. ebuf[0] = '\0';
  16157. }
  16158. if (!conn) {
  16159. mg_snprintf(conn,
  16160. NULL, /* No truncation check for ebuf */
  16161. ebuf,
  16162. ebuf_len,
  16163. "%s",
  16164. "Parameter error");
  16165. return -1;
  16166. }
  16167. /* Reset the previous responses */
  16168. conn->data_len = 0;
  16169. /* Implementation of API function for HTTP clients */
  16170. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16171. if (timeout >= 0) {
  16172. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16173. new_timeout = txt;
  16174. } else {
  16175. new_timeout = NULL;
  16176. }
  16177. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16178. ret = get_response(conn, ebuf, ebuf_len, &err);
  16179. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16180. /* TODO: here, the URI is the http response code */
  16181. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16182. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16183. /* TODO (mid): Define proper return values - maybe return length?
  16184. * For the first test use <0 for error and >0 for OK */
  16185. return (ret == 0) ? -1 : +1;
  16186. }
  16187. struct mg_connection *
  16188. mg_download(const char *host,
  16189. int port,
  16190. int use_ssl,
  16191. char *ebuf,
  16192. size_t ebuf_len,
  16193. const char *fmt,
  16194. ...)
  16195. {
  16196. struct mg_connection *conn;
  16197. va_list ap;
  16198. int i;
  16199. int reqerr;
  16200. if (ebuf_len > 0) {
  16201. ebuf[0] = '\0';
  16202. }
  16203. va_start(ap, fmt);
  16204. /* open a connection */
  16205. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16206. if (conn != NULL) {
  16207. i = mg_vprintf(conn, fmt, ap);
  16208. if (i <= 0) {
  16209. mg_snprintf(conn,
  16210. NULL, /* No truncation check for ebuf */
  16211. ebuf,
  16212. ebuf_len,
  16213. "%s",
  16214. "Error sending request");
  16215. } else {
  16216. /* make sure the buffer is clear */
  16217. conn->data_len = 0;
  16218. get_response(conn, ebuf, ebuf_len, &reqerr);
  16219. /* TODO: here, the URI is the http response code */
  16220. conn->request_info.local_uri = conn->request_info.request_uri;
  16221. }
  16222. }
  16223. /* if an error occurred, close the connection */
  16224. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16225. mg_close_connection(conn);
  16226. conn = NULL;
  16227. }
  16228. va_end(ap);
  16229. return conn;
  16230. }
  16231. struct websocket_client_thread_data {
  16232. struct mg_connection *conn;
  16233. mg_websocket_data_handler data_handler;
  16234. mg_websocket_close_handler close_handler;
  16235. void *callback_data;
  16236. };
  16237. #if defined(USE_WEBSOCKET)
  16238. #if defined(_WIN32)
  16239. static unsigned __stdcall websocket_client_thread(void *data)
  16240. #else
  16241. static void *
  16242. websocket_client_thread(void *data)
  16243. #endif
  16244. {
  16245. struct websocket_client_thread_data *cdata =
  16246. (struct websocket_client_thread_data *)data;
  16247. void *user_thread_ptr = NULL;
  16248. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16249. struct sigaction sa;
  16250. /* Ignore SIGPIPE */
  16251. memset(&sa, 0, sizeof(sa));
  16252. sa.sa_handler = SIG_IGN;
  16253. sigaction(SIGPIPE, &sa, NULL);
  16254. #endif
  16255. mg_set_thread_name("ws-clnt");
  16256. if (cdata->conn->phys_ctx) {
  16257. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16258. /* 3 indicates a websocket client thread */
  16259. /* TODO: check if conn->phys_ctx can be set */
  16260. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16261. cdata->conn->phys_ctx, 3);
  16262. }
  16263. }
  16264. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16265. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16266. if (cdata->close_handler != NULL) {
  16267. cdata->close_handler(cdata->conn, cdata->callback_data);
  16268. }
  16269. /* The websocket_client context has only this thread. If it runs out,
  16270. set the stop_flag to 2 (= "stopped"). */
  16271. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16272. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16273. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16274. 3,
  16275. user_thread_ptr);
  16276. }
  16277. mg_free((void *)cdata);
  16278. #if defined(_WIN32)
  16279. return 0;
  16280. #else
  16281. return NULL;
  16282. #endif
  16283. }
  16284. #endif
  16285. static struct mg_connection *
  16286. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16287. int use_ssl,
  16288. char *error_buffer,
  16289. size_t error_buffer_size,
  16290. const char *path,
  16291. const char *origin,
  16292. const char *extensions,
  16293. mg_websocket_data_handler data_func,
  16294. mg_websocket_close_handler close_func,
  16295. void *user_data)
  16296. {
  16297. struct mg_connection *conn = NULL;
  16298. #if defined(USE_WEBSOCKET)
  16299. struct websocket_client_thread_data *thread_data;
  16300. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16301. const char *host = client_options->host;
  16302. int i;
  16303. #if defined(__clang__)
  16304. #pragma clang diagnostic push
  16305. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16306. #endif
  16307. /* Establish the client connection and request upgrade */
  16308. conn = mg_connect_client_impl(client_options,
  16309. use_ssl,
  16310. error_buffer,
  16311. error_buffer_size);
  16312. /* Connection object will be null if something goes wrong */
  16313. if (conn == NULL) {
  16314. /* error_buffer should be already filled ... */
  16315. if (!error_buffer[0]) {
  16316. /* ... if not add an error message */
  16317. mg_snprintf(conn,
  16318. NULL, /* No truncation check for ebuf */
  16319. error_buffer,
  16320. error_buffer_size,
  16321. "Unexpected error");
  16322. }
  16323. return NULL;
  16324. }
  16325. if (origin != NULL) {
  16326. if (extensions != NULL) {
  16327. i = mg_printf(conn,
  16328. "GET %s HTTP/1.1\r\n"
  16329. "Host: %s\r\n"
  16330. "Upgrade: websocket\r\n"
  16331. "Connection: Upgrade\r\n"
  16332. "Sec-WebSocket-Key: %s\r\n"
  16333. "Sec-WebSocket-Version: 13\r\n"
  16334. "Sec-WebSocket-Extensions: %s\r\n"
  16335. "Origin: %s\r\n"
  16336. "\r\n",
  16337. path,
  16338. host,
  16339. magic,
  16340. extensions,
  16341. origin);
  16342. } else {
  16343. i = mg_printf(conn,
  16344. "GET %s HTTP/1.1\r\n"
  16345. "Host: %s\r\n"
  16346. "Upgrade: websocket\r\n"
  16347. "Connection: Upgrade\r\n"
  16348. "Sec-WebSocket-Key: %s\r\n"
  16349. "Sec-WebSocket-Version: 13\r\n"
  16350. "Origin: %s\r\n"
  16351. "\r\n",
  16352. path,
  16353. host,
  16354. magic,
  16355. origin);
  16356. }
  16357. } else {
  16358. if (extensions != NULL) {
  16359. i = mg_printf(conn,
  16360. "GET %s HTTP/1.1\r\n"
  16361. "Host: %s\r\n"
  16362. "Upgrade: websocket\r\n"
  16363. "Connection: Upgrade\r\n"
  16364. "Sec-WebSocket-Key: %s\r\n"
  16365. "Sec-WebSocket-Version: 13\r\n"
  16366. "Sec-WebSocket-Extensions: %s\r\n"
  16367. "\r\n",
  16368. path,
  16369. host,
  16370. magic,
  16371. extensions);
  16372. } else {
  16373. i = mg_printf(conn,
  16374. "GET %s HTTP/1.1\r\n"
  16375. "Host: %s\r\n"
  16376. "Upgrade: websocket\r\n"
  16377. "Connection: Upgrade\r\n"
  16378. "Sec-WebSocket-Key: %s\r\n"
  16379. "Sec-WebSocket-Version: 13\r\n"
  16380. "\r\n",
  16381. path,
  16382. host,
  16383. magic);
  16384. }
  16385. }
  16386. if (i <= 0) {
  16387. mg_snprintf(conn,
  16388. NULL, /* No truncation check for ebuf */
  16389. error_buffer,
  16390. error_buffer_size,
  16391. "%s",
  16392. "Error sending request");
  16393. mg_close_connection(conn);
  16394. return NULL;
  16395. }
  16396. conn->data_len = 0;
  16397. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16398. mg_close_connection(conn);
  16399. return NULL;
  16400. }
  16401. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16402. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16403. #if defined(__clang__)
  16404. #pragma clang diagnostic pop
  16405. #endif
  16406. if (conn->response_info.status_code != 101) {
  16407. /* We sent an "upgrade" request. For a correct websocket
  16408. * protocol handshake, we expect a "101 Continue" response.
  16409. * Otherwise it is a protocol violation. Maybe the HTTP
  16410. * Server does not know websockets. */
  16411. if (!*error_buffer) {
  16412. /* set an error, if not yet set */
  16413. mg_snprintf(conn,
  16414. NULL, /* No truncation check for ebuf */
  16415. error_buffer,
  16416. error_buffer_size,
  16417. "Unexpected server reply");
  16418. }
  16419. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16420. mg_close_connection(conn);
  16421. return NULL;
  16422. }
  16423. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16424. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16425. if (!thread_data) {
  16426. DEBUG_TRACE("%s\r\n", "Out of memory");
  16427. mg_close_connection(conn);
  16428. return NULL;
  16429. }
  16430. thread_data->conn = conn;
  16431. thread_data->data_handler = data_func;
  16432. thread_data->close_handler = close_func;
  16433. thread_data->callback_data = user_data;
  16434. conn->phys_ctx->worker_threadids =
  16435. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16436. if (!conn->phys_ctx->worker_threadids) {
  16437. DEBUG_TRACE("%s\r\n", "Out of memory");
  16438. mg_free(thread_data);
  16439. mg_close_connection(conn);
  16440. return NULL;
  16441. }
  16442. /* Now upgrade to ws/wss client context */
  16443. conn->phys_ctx->user_data = user_data;
  16444. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16445. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16446. /* Start a thread to read the websocket client connection
  16447. * This thread will automatically stop when mg_disconnect is
  16448. * called on the client connection */
  16449. if (mg_start_thread_with_id(websocket_client_thread,
  16450. thread_data,
  16451. conn->phys_ctx->worker_threadids)
  16452. != 0) {
  16453. conn->phys_ctx->cfg_worker_threads = 0;
  16454. mg_free(thread_data);
  16455. mg_close_connection(conn);
  16456. conn = NULL;
  16457. DEBUG_TRACE("%s",
  16458. "Websocket client connect thread could not be started\r\n");
  16459. }
  16460. #else
  16461. /* Appease "unused parameter" warnings */
  16462. (void)client_options;
  16463. (void)use_ssl;
  16464. (void)error_buffer;
  16465. (void)error_buffer_size;
  16466. (void)path;
  16467. (void)origin;
  16468. (void)extensions;
  16469. (void)user_data;
  16470. (void)data_func;
  16471. (void)close_func;
  16472. #endif
  16473. return conn;
  16474. }
  16475. struct mg_connection *
  16476. mg_connect_websocket_client(const char *host,
  16477. int port,
  16478. int use_ssl,
  16479. char *error_buffer,
  16480. size_t error_buffer_size,
  16481. const char *path,
  16482. const char *origin,
  16483. mg_websocket_data_handler data_func,
  16484. mg_websocket_close_handler close_func,
  16485. void *user_data)
  16486. {
  16487. struct mg_client_options client_options;
  16488. memset(&client_options, 0, sizeof(client_options));
  16489. client_options.host = host;
  16490. client_options.port = port;
  16491. return mg_connect_websocket_client_impl(&client_options,
  16492. use_ssl,
  16493. error_buffer,
  16494. error_buffer_size,
  16495. path,
  16496. origin,
  16497. NULL,
  16498. data_func,
  16499. close_func,
  16500. user_data);
  16501. }
  16502. struct mg_connection *
  16503. mg_connect_websocket_client_secure(
  16504. const struct mg_client_options *client_options,
  16505. char *error_buffer,
  16506. size_t error_buffer_size,
  16507. const char *path,
  16508. const char *origin,
  16509. mg_websocket_data_handler data_func,
  16510. mg_websocket_close_handler close_func,
  16511. void *user_data)
  16512. {
  16513. if (!client_options) {
  16514. return NULL;
  16515. }
  16516. return mg_connect_websocket_client_impl(client_options,
  16517. 1,
  16518. error_buffer,
  16519. error_buffer_size,
  16520. path,
  16521. origin,
  16522. NULL,
  16523. data_func,
  16524. close_func,
  16525. user_data);
  16526. }
  16527. struct mg_connection *
  16528. mg_connect_websocket_client_extensions(const char *host,
  16529. int port,
  16530. int use_ssl,
  16531. char *error_buffer,
  16532. size_t error_buffer_size,
  16533. const char *path,
  16534. const char *origin,
  16535. const char *extensions,
  16536. mg_websocket_data_handler data_func,
  16537. mg_websocket_close_handler close_func,
  16538. void *user_data)
  16539. {
  16540. struct mg_client_options client_options;
  16541. memset(&client_options, 0, sizeof(client_options));
  16542. client_options.host = host;
  16543. client_options.port = port;
  16544. return mg_connect_websocket_client_impl(&client_options,
  16545. use_ssl,
  16546. error_buffer,
  16547. error_buffer_size,
  16548. path,
  16549. origin,
  16550. extensions,
  16551. data_func,
  16552. close_func,
  16553. user_data);
  16554. }
  16555. struct mg_connection *
  16556. mg_connect_websocket_client_secure_extensions(
  16557. const struct mg_client_options *client_options,
  16558. char *error_buffer,
  16559. size_t error_buffer_size,
  16560. const char *path,
  16561. const char *origin,
  16562. const char *extensions,
  16563. mg_websocket_data_handler data_func,
  16564. mg_websocket_close_handler close_func,
  16565. void *user_data)
  16566. {
  16567. if (!client_options) {
  16568. return NULL;
  16569. }
  16570. return mg_connect_websocket_client_impl(client_options,
  16571. 1,
  16572. error_buffer,
  16573. error_buffer_size,
  16574. path,
  16575. origin,
  16576. extensions,
  16577. data_func,
  16578. close_func,
  16579. user_data);
  16580. }
  16581. /* Prepare connection data structure */
  16582. static void
  16583. init_connection(struct mg_connection *conn)
  16584. {
  16585. /* Is keep alive allowed by the server */
  16586. int keep_alive_enabled =
  16587. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16588. if (!keep_alive_enabled) {
  16589. conn->must_close = 1;
  16590. }
  16591. /* Important: on new connection, reset the receiving buffer. Credit
  16592. * goes to crule42. */
  16593. conn->data_len = 0;
  16594. conn->handled_requests = 0;
  16595. conn->connection_type = CONNECTION_TYPE_INVALID;
  16596. mg_set_user_connection_data(conn, NULL);
  16597. #if defined(USE_SERVER_STATS)
  16598. conn->conn_state = 2; /* init */
  16599. #endif
  16600. /* call the init_connection callback if assigned */
  16601. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16602. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16603. void *conn_data = NULL;
  16604. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16605. mg_set_user_connection_data(conn, conn_data);
  16606. }
  16607. }
  16608. }
  16609. /* Process a connection - may handle multiple requests
  16610. * using the same connection.
  16611. * Must be called with a valid connection (conn and
  16612. * conn->phys_ctx must be valid).
  16613. */
  16614. static void
  16615. process_new_connection(struct mg_connection *conn)
  16616. {
  16617. struct mg_request_info *ri = &conn->request_info;
  16618. int keep_alive, discard_len;
  16619. char ebuf[100];
  16620. const char *hostend;
  16621. int reqerr, uri_type;
  16622. #if defined(USE_SERVER_STATS)
  16623. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16624. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16625. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16626. #endif
  16627. DEBUG_TRACE("Start processing connection from %s",
  16628. conn->request_info.remote_addr);
  16629. /* Loop over multiple requests sent using the same connection
  16630. * (while "keep alive"). */
  16631. do {
  16632. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16633. conn->handled_requests + 1);
  16634. #if defined(USE_SERVER_STATS)
  16635. conn->conn_state = 3; /* ready */
  16636. #endif
  16637. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16638. /* The request sent by the client could not be understood by
  16639. * the server, or it was incomplete or a timeout. Send an
  16640. * error message and close the connection. */
  16641. if (reqerr > 0) {
  16642. DEBUG_ASSERT(ebuf[0] != '\0');
  16643. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16644. }
  16645. } else if (strcmp(ri->http_version, "1.0")
  16646. && strcmp(ri->http_version, "1.1")) {
  16647. /* HTTP/2 is not allowed here */
  16648. mg_snprintf(conn,
  16649. NULL, /* No truncation check for ebuf */
  16650. ebuf,
  16651. sizeof(ebuf),
  16652. "Bad HTTP version: [%s]",
  16653. ri->http_version);
  16654. mg_send_http_error(conn, 505, "%s", ebuf);
  16655. }
  16656. if (ebuf[0] == '\0') {
  16657. uri_type = get_uri_type(conn->request_info.request_uri);
  16658. switch (uri_type) {
  16659. case 1:
  16660. /* Asterisk */
  16661. conn->request_info.local_uri_raw = 0;
  16662. /* TODO: Deal with '*'. */
  16663. break;
  16664. case 2:
  16665. /* relative uri */
  16666. conn->request_info.local_uri_raw =
  16667. conn->request_info.request_uri;
  16668. break;
  16669. case 3:
  16670. case 4:
  16671. /* absolute uri (with/without port) */
  16672. hostend = get_rel_url_at_current_server(
  16673. conn->request_info.request_uri, conn);
  16674. if (hostend) {
  16675. conn->request_info.local_uri_raw = hostend;
  16676. } else {
  16677. conn->request_info.local_uri_raw = NULL;
  16678. }
  16679. break;
  16680. default:
  16681. mg_snprintf(conn,
  16682. NULL, /* No truncation check for ebuf */
  16683. ebuf,
  16684. sizeof(ebuf),
  16685. "Invalid URI");
  16686. mg_send_http_error(conn, 400, "%s", ebuf);
  16687. conn->request_info.local_uri_raw = NULL;
  16688. break;
  16689. }
  16690. conn->request_info.local_uri =
  16691. (char *)conn->request_info.local_uri_raw;
  16692. }
  16693. if (ebuf[0] != '\0') {
  16694. conn->protocol_type = -1;
  16695. } else {
  16696. /* HTTP/1 allows protocol upgrade */
  16697. conn->protocol_type = should_switch_to_protocol(conn);
  16698. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16699. /* This will occur, if a HTTP/1.1 request should be upgraded
  16700. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16701. * Since most (all?) major browsers only support HTTP/2 using
  16702. * ALPN, this is hard to test and very low priority.
  16703. * Deactivate it (at least for now).
  16704. */
  16705. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16706. }
  16707. }
  16708. DEBUG_TRACE("http: %s, error: %s",
  16709. (ri->http_version ? ri->http_version : "none"),
  16710. (ebuf[0] ? ebuf : "none"));
  16711. if (ebuf[0] == '\0') {
  16712. if (conn->request_info.local_uri) {
  16713. /* handle request to local server */
  16714. handle_request_stat_log(conn);
  16715. } else {
  16716. /* TODO: handle non-local request (PROXY) */
  16717. conn->must_close = 1;
  16718. }
  16719. } else {
  16720. conn->must_close = 1;
  16721. }
  16722. /* Response complete. Free header buffer */
  16723. free_buffered_response_header_list(conn);
  16724. if (ri->remote_user != NULL) {
  16725. mg_free((void *)ri->remote_user);
  16726. /* Important! When having connections with and without auth
  16727. * would cause double free and then crash */
  16728. ri->remote_user = NULL;
  16729. }
  16730. /* NOTE(lsm): order is important here. should_keep_alive() call
  16731. * is using parsed request, which will be invalid after
  16732. * memmove's below.
  16733. * Therefore, memorize should_keep_alive() result now for later
  16734. * use in loop exit condition. */
  16735. /* Enable it only if this request is completely discardable. */
  16736. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16737. && should_keep_alive(conn) && (conn->content_len >= 0)
  16738. && (conn->request_len > 0)
  16739. && ((conn->is_chunked == 4)
  16740. || (!conn->is_chunked
  16741. && ((conn->consumed_content == conn->content_len)
  16742. || ((conn->request_len + conn->content_len)
  16743. <= conn->data_len))))
  16744. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16745. if (keep_alive) {
  16746. /* Discard all buffered data for this request */
  16747. discard_len =
  16748. ((conn->request_len + conn->content_len) < conn->data_len)
  16749. ? (int)(conn->request_len + conn->content_len)
  16750. : conn->data_len;
  16751. conn->data_len -= discard_len;
  16752. if (conn->data_len > 0) {
  16753. DEBUG_TRACE("discard_len = %d", discard_len);
  16754. memmove(conn->buf,
  16755. conn->buf + discard_len,
  16756. (size_t)conn->data_len);
  16757. }
  16758. }
  16759. DEBUG_ASSERT(conn->data_len >= 0);
  16760. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16761. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16762. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16763. (long int)conn->data_len,
  16764. (long int)conn->buf_size);
  16765. break;
  16766. }
  16767. conn->handled_requests++;
  16768. } while (keep_alive);
  16769. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16770. conn->request_info.remote_addr,
  16771. difftime(time(NULL), conn->conn_birth_time));
  16772. close_connection(conn);
  16773. #if defined(USE_SERVER_STATS)
  16774. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16775. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16776. #endif
  16777. }
  16778. #if defined(ALTERNATIVE_QUEUE)
  16779. static void
  16780. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16781. {
  16782. unsigned int i;
  16783. while (!ctx->stop_flag) {
  16784. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16785. /* find a free worker slot and signal it */
  16786. if (ctx->client_socks[i].in_use == 2) {
  16787. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16788. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16789. ctx->client_socks[i] = *sp;
  16790. ctx->client_socks[i].in_use = 1;
  16791. /* socket has been moved to the consumer */
  16792. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16793. (void)event_signal(ctx->client_wait_events[i]);
  16794. return;
  16795. }
  16796. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16797. }
  16798. }
  16799. /* queue is full */
  16800. mg_sleep(1);
  16801. }
  16802. /* must consume */
  16803. set_blocking_mode(sp->sock);
  16804. closesocket(sp->sock);
  16805. }
  16806. static int
  16807. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16808. {
  16809. DEBUG_TRACE("%s", "going idle");
  16810. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16811. ctx->client_socks[thread_index].in_use = 2;
  16812. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16813. event_wait(ctx->client_wait_events[thread_index]);
  16814. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16815. *sp = ctx->client_socks[thread_index];
  16816. if (ctx->stop_flag) {
  16817. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16818. if (sp->in_use == 1) {
  16819. /* must consume */
  16820. set_blocking_mode(sp->sock);
  16821. closesocket(sp->sock);
  16822. }
  16823. return 0;
  16824. }
  16825. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16826. if (sp->in_use == 1) {
  16827. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16828. return 1;
  16829. }
  16830. /* must not reach here */
  16831. DEBUG_ASSERT(0);
  16832. return 0;
  16833. }
  16834. #else /* ALTERNATIVE_QUEUE */
  16835. /* Worker threads take accepted socket from the queue */
  16836. static int
  16837. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16838. {
  16839. (void)thread_index;
  16840. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16841. DEBUG_TRACE("%s", "going idle");
  16842. /* If the queue is empty, wait. We're idle at this point. */
  16843. while ((ctx->sq_head == ctx->sq_tail)
  16844. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16845. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16846. }
  16847. /* If we're stopping, sq_head may be equal to sq_tail. */
  16848. if (ctx->sq_head > ctx->sq_tail) {
  16849. /* Copy socket from the queue and increment tail */
  16850. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16851. ctx->sq_tail++;
  16852. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16853. /* Wrap pointers if needed */
  16854. while (ctx->sq_tail > ctx->sq_size) {
  16855. ctx->sq_tail -= ctx->sq_size;
  16856. ctx->sq_head -= ctx->sq_size;
  16857. }
  16858. }
  16859. (void)pthread_cond_signal(&ctx->sq_empty);
  16860. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16861. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16862. }
  16863. /* Master thread adds accepted socket to a queue */
  16864. static void
  16865. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16866. {
  16867. int queue_filled;
  16868. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16869. queue_filled = ctx->sq_head - ctx->sq_tail;
  16870. /* If the queue is full, wait */
  16871. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16872. && (queue_filled >= ctx->sq_size)) {
  16873. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16874. #if defined(USE_SERVER_STATS)
  16875. if (queue_filled > ctx->sq_max_fill) {
  16876. ctx->sq_max_fill = queue_filled;
  16877. }
  16878. #endif
  16879. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16880. ctx->sq_blocked = 0; /* Not blocked now */
  16881. queue_filled = ctx->sq_head - ctx->sq_tail;
  16882. }
  16883. if (queue_filled < ctx->sq_size) {
  16884. /* Copy socket to the queue and increment head */
  16885. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16886. ctx->sq_head++;
  16887. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16888. }
  16889. queue_filled = ctx->sq_head - ctx->sq_tail;
  16890. #if defined(USE_SERVER_STATS)
  16891. if (queue_filled > ctx->sq_max_fill) {
  16892. ctx->sq_max_fill = queue_filled;
  16893. }
  16894. #endif
  16895. (void)pthread_cond_signal(&ctx->sq_full);
  16896. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16897. }
  16898. #endif /* ALTERNATIVE_QUEUE */
  16899. static void
  16900. worker_thread_run(struct mg_connection *conn)
  16901. {
  16902. struct mg_context *ctx = conn->phys_ctx;
  16903. int thread_index;
  16904. struct mg_workerTLS tls;
  16905. mg_set_thread_name("worker");
  16906. tls.is_master = 0;
  16907. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16908. #if defined(_WIN32)
  16909. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16910. #endif
  16911. /* Initialize thread local storage before calling any callback */
  16912. pthread_setspecific(sTlsKey, &tls);
  16913. /* Check if there is a user callback */
  16914. if (ctx->callbacks.init_thread) {
  16915. /* call init_thread for a worker thread (type 1), and store the
  16916. * return value */
  16917. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16918. } else {
  16919. /* No callback: set user pointer to NULL */
  16920. tls.user_ptr = NULL;
  16921. }
  16922. /* Connection structure has been pre-allocated */
  16923. thread_index = (int)(conn - ctx->worker_connections);
  16924. if ((thread_index < 0)
  16925. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16926. mg_cry_ctx_internal(ctx,
  16927. "Internal error: Invalid worker index %i",
  16928. thread_index);
  16929. return;
  16930. }
  16931. /* Request buffers are not pre-allocated. They are private to the
  16932. * request and do not contain any state information that might be
  16933. * of interest to anyone observing a server status. */
  16934. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16935. if (conn->buf == NULL) {
  16936. mg_cry_ctx_internal(
  16937. ctx,
  16938. "Out of memory: Cannot allocate buffer for worker %i",
  16939. thread_index);
  16940. return;
  16941. }
  16942. conn->buf_size = (int)ctx->max_request_size;
  16943. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16944. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16945. conn->request_info.user_data = ctx->user_data;
  16946. /* Allocate a mutex for this connection to allow communication both
  16947. * within the request handler and from elsewhere in the application
  16948. */
  16949. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16950. mg_free(conn->buf);
  16951. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16952. return;
  16953. }
  16954. #if defined(USE_SERVER_STATS)
  16955. conn->conn_state = 1; /* not consumed */
  16956. #endif
  16957. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16958. * signal sq_empty condvar to wake up the master waiting in
  16959. * produce_socket() */
  16960. while (consume_socket(ctx, &conn->client, thread_index)) {
  16961. /* New connections must start with new protocol negotiation */
  16962. tls.alpn_proto = NULL;
  16963. #if defined(USE_SERVER_STATS)
  16964. conn->conn_close_time = 0;
  16965. #endif
  16966. conn->conn_birth_time = time(NULL);
  16967. /* Fill in IP, port info early so even if SSL setup below fails,
  16968. * error handler would have the corresponding info.
  16969. * Thanks to Johannes Winkelmann for the patch.
  16970. */
  16971. conn->request_info.remote_port =
  16972. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16973. conn->request_info.server_port =
  16974. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16975. sockaddr_to_string(conn->request_info.remote_addr,
  16976. sizeof(conn->request_info.remote_addr),
  16977. &conn->client.rsa);
  16978. DEBUG_TRACE("Incomming %sconnection from %s",
  16979. (conn->client.is_ssl ? "SSL " : ""),
  16980. conn->request_info.remote_addr);
  16981. conn->request_info.is_ssl = conn->client.is_ssl;
  16982. if (conn->client.is_ssl) {
  16983. #if defined(USE_MBEDTLS)
  16984. /* HTTPS connection */
  16985. if (mbed_ssl_accept(&(conn->ssl),
  16986. conn->dom_ctx->ssl_ctx,
  16987. (int *)&(conn->client.sock),
  16988. conn->phys_ctx)
  16989. == 0) {
  16990. /* conn->dom_ctx is set in get_request */
  16991. /* process HTTPS connection */
  16992. init_connection(conn);
  16993. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16994. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16995. process_new_connection(conn);
  16996. } else {
  16997. /* make sure the connection is cleaned up on SSL failure */
  16998. close_connection(conn);
  16999. }
  17000. #elif !defined(NO_SSL)
  17001. /* HTTPS connection */
  17002. if (sslize(conn, SSL_accept, NULL)) {
  17003. /* conn->dom_ctx is set in get_request */
  17004. /* Get SSL client certificate information (if set) */
  17005. struct mg_client_cert client_cert;
  17006. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17007. conn->request_info.client_cert = &client_cert;
  17008. }
  17009. /* process HTTPS connection */
  17010. #if defined(USE_HTTP2)
  17011. if ((tls.alpn_proto != NULL)
  17012. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17013. /* process HTTPS/2 connection */
  17014. init_connection(conn);
  17015. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17016. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17017. conn->content_len =
  17018. -1; /* content length is not predefined */
  17019. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17020. process_new_http2_connection(conn);
  17021. } else
  17022. #endif
  17023. {
  17024. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17025. init_connection(conn);
  17026. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17027. /* Start with HTTP, WS will be an "upgrade" request later */
  17028. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17029. process_new_connection(conn);
  17030. }
  17031. /* Free client certificate info */
  17032. if (conn->request_info.client_cert) {
  17033. mg_free((void *)(conn->request_info.client_cert->subject));
  17034. mg_free((void *)(conn->request_info.client_cert->issuer));
  17035. mg_free((void *)(conn->request_info.client_cert->serial));
  17036. mg_free((void *)(conn->request_info.client_cert->finger));
  17037. /* Free certificate memory */
  17038. X509_free(
  17039. (X509 *)conn->request_info.client_cert->peer_cert);
  17040. conn->request_info.client_cert->peer_cert = 0;
  17041. conn->request_info.client_cert->subject = 0;
  17042. conn->request_info.client_cert->issuer = 0;
  17043. conn->request_info.client_cert->serial = 0;
  17044. conn->request_info.client_cert->finger = 0;
  17045. conn->request_info.client_cert = 0;
  17046. }
  17047. } else {
  17048. /* make sure the connection is cleaned up on SSL failure */
  17049. close_connection(conn);
  17050. }
  17051. #endif
  17052. } else {
  17053. /* process HTTP connection */
  17054. init_connection(conn);
  17055. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17056. /* Start with HTTP, WS will be an "upgrade" request later */
  17057. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17058. process_new_connection(conn);
  17059. }
  17060. DEBUG_TRACE("%s", "Connection closed");
  17061. #if defined(USE_SERVER_STATS)
  17062. conn->conn_close_time = time(NULL);
  17063. #endif
  17064. }
  17065. /* Call exit thread user callback */
  17066. if (ctx->callbacks.exit_thread) {
  17067. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17068. }
  17069. /* delete thread local storage objects */
  17070. pthread_setspecific(sTlsKey, NULL);
  17071. #if defined(_WIN32)
  17072. CloseHandle(tls.pthread_cond_helper_mutex);
  17073. #endif
  17074. pthread_mutex_destroy(&conn->mutex);
  17075. /* Free the request buffer. */
  17076. conn->buf_size = 0;
  17077. mg_free(conn->buf);
  17078. conn->buf = NULL;
  17079. /* Free cleaned URI (if any) */
  17080. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17081. mg_free((void *)conn->request_info.local_uri);
  17082. conn->request_info.local_uri = NULL;
  17083. }
  17084. #if defined(USE_SERVER_STATS)
  17085. conn->conn_state = 9; /* done */
  17086. #endif
  17087. DEBUG_TRACE("%s", "exiting");
  17088. }
  17089. /* Threads have different return types on Windows and Unix. */
  17090. #if defined(_WIN32)
  17091. static unsigned __stdcall worker_thread(void *thread_func_param)
  17092. {
  17093. worker_thread_run((struct mg_connection *)thread_func_param);
  17094. return 0;
  17095. }
  17096. #else
  17097. static void *
  17098. worker_thread(void *thread_func_param)
  17099. {
  17100. #if !defined(__ZEPHYR__)
  17101. struct sigaction sa;
  17102. /* Ignore SIGPIPE */
  17103. memset(&sa, 0, sizeof(sa));
  17104. sa.sa_handler = SIG_IGN;
  17105. sigaction(SIGPIPE, &sa, NULL);
  17106. #endif
  17107. worker_thread_run((struct mg_connection *)thread_func_param);
  17108. return NULL;
  17109. }
  17110. #endif /* _WIN32 */
  17111. /* This is an internal function, thus all arguments are expected to be
  17112. * valid - a NULL check is not required. */
  17113. static void
  17114. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17115. {
  17116. struct socket so;
  17117. char src_addr[IP_ADDR_STR_LEN];
  17118. socklen_t len = sizeof(so.rsa);
  17119. #if !defined(__ZEPHYR__)
  17120. int on = 1;
  17121. #endif
  17122. memset(&so, 0, sizeof(so));
  17123. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17124. == INVALID_SOCKET) {
  17125. } else if (check_acl(ctx, &so.rsa) != 1) {
  17126. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17127. mg_cry_ctx_internal(ctx,
  17128. "%s: %s is not allowed to connect",
  17129. __func__,
  17130. src_addr);
  17131. closesocket(so.sock);
  17132. } else {
  17133. /* Put so socket structure into the queue */
  17134. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17135. set_close_on_exec(so.sock, NULL, ctx);
  17136. so.is_ssl = listener->is_ssl;
  17137. so.ssl_redir = listener->ssl_redir;
  17138. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17139. mg_cry_ctx_internal(ctx,
  17140. "%s: getsockname() failed: %s",
  17141. __func__,
  17142. strerror(ERRNO));
  17143. }
  17144. #if !defined(__ZEPHYR__)
  17145. if ((so.lsa.sa.sa_family == AF_INET)
  17146. || (so.lsa.sa.sa_family == AF_INET6)) {
  17147. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17148. * This is needed because if HTTP-level keep-alive
  17149. * is enabled, and client resets the connection, server won't get
  17150. * TCP FIN or RST and will keep the connection open forever. With
  17151. * TCP keep-alive, next keep-alive handshake will figure out that
  17152. * the client is down and will close the server end.
  17153. * Thanks to Igor Klopov who suggested the patch. */
  17154. if (setsockopt(so.sock,
  17155. SOL_SOCKET,
  17156. SO_KEEPALIVE,
  17157. (SOCK_OPT_TYPE)&on,
  17158. sizeof(on))
  17159. != 0) {
  17160. mg_cry_ctx_internal(
  17161. ctx,
  17162. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17163. __func__,
  17164. strerror(ERRNO));
  17165. }
  17166. }
  17167. #endif
  17168. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17169. * to effectively fill up the underlying IP packet payload and
  17170. * reduce the overhead of sending lots of small buffers. However
  17171. * this hurts the server's throughput (ie. operations per second)
  17172. * when HTTP 1.1 persistent connections are used and the responses
  17173. * are relatively small (eg. less than 1400 bytes).
  17174. */
  17175. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17176. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17177. if (set_tcp_nodelay(&so, 1) != 0) {
  17178. mg_cry_ctx_internal(
  17179. ctx,
  17180. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17181. __func__,
  17182. strerror(ERRNO));
  17183. }
  17184. }
  17185. /* The "non blocking" property should already be
  17186. * inherited from the parent socket. Set it for
  17187. * non-compliant socket implementations. */
  17188. set_non_blocking_mode(so.sock);
  17189. so.in_use = 0;
  17190. produce_socket(ctx, &so);
  17191. }
  17192. }
  17193. static void
  17194. master_thread_run(struct mg_context *ctx)
  17195. {
  17196. struct mg_workerTLS tls;
  17197. struct mg_pollfd *pfd;
  17198. unsigned int i;
  17199. unsigned int workerthreadcount;
  17200. if (!ctx) {
  17201. return;
  17202. }
  17203. mg_set_thread_name("master");
  17204. /* Increase priority of the master thread */
  17205. #if defined(_WIN32)
  17206. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17207. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17208. int min_prio = sched_get_priority_min(SCHED_RR);
  17209. int max_prio = sched_get_priority_max(SCHED_RR);
  17210. if ((min_prio >= 0) && (max_prio >= 0)
  17211. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17212. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17213. struct sched_param sched_param = {0};
  17214. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17215. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17216. }
  17217. #endif
  17218. /* Initialize thread local storage */
  17219. #if defined(_WIN32)
  17220. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17221. #endif
  17222. tls.is_master = 1;
  17223. pthread_setspecific(sTlsKey, &tls);
  17224. if (ctx->callbacks.init_thread) {
  17225. /* Callback for the master thread (type 0) */
  17226. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17227. } else {
  17228. tls.user_ptr = NULL;
  17229. }
  17230. /* Lua background script "start" event */
  17231. #if defined(USE_LUA)
  17232. if (ctx->lua_background_state) {
  17233. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17234. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17235. /* call "start()" in Lua */
  17236. lua_getglobal(lstate, "start");
  17237. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17238. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17239. if (ret != 0) {
  17240. struct mg_connection fc;
  17241. lua_cry(fake_connection(&fc, ctx),
  17242. ret,
  17243. lstate,
  17244. "lua_background_script",
  17245. "start");
  17246. }
  17247. } else {
  17248. lua_pop(lstate, 1);
  17249. }
  17250. /* determine if there is a "log()" function in Lua background script */
  17251. lua_getglobal(lstate, "log");
  17252. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17253. ctx->lua_bg_log_available = 1;
  17254. }
  17255. lua_pop(lstate, 1);
  17256. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17257. }
  17258. #endif
  17259. /* Server starts *now* */
  17260. ctx->start_time = time(NULL);
  17261. /* Server accept loop */
  17262. pfd = ctx->listening_socket_fds;
  17263. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17264. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17265. pfd[i].fd = ctx->listening_sockets[i].sock;
  17266. pfd[i].events = POLLIN;
  17267. }
  17268. if (mg_poll(pfd,
  17269. ctx->num_listening_sockets,
  17270. SOCKET_TIMEOUT_QUANTUM,
  17271. &(ctx->stop_flag))
  17272. > 0) {
  17273. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17274. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17275. * successful poll, and POLLIN is defined as
  17276. * (POLLRDNORM | POLLRDBAND)
  17277. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17278. * pfd[i].revents == POLLIN. */
  17279. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17280. && (pfd[i].revents & POLLIN)) {
  17281. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17282. }
  17283. }
  17284. }
  17285. }
  17286. /* Here stop_flag is 1 - Initiate shutdown. */
  17287. DEBUG_TRACE("%s", "stopping workers");
  17288. /* Stop signal received: somebody called mg_stop. Quit. */
  17289. close_all_listening_sockets(ctx);
  17290. /* Wakeup workers that are waiting for connections to handle. */
  17291. #if defined(ALTERNATIVE_QUEUE)
  17292. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17293. event_signal(ctx->client_wait_events[i]);
  17294. }
  17295. #else
  17296. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17297. pthread_cond_broadcast(&ctx->sq_full);
  17298. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17299. #endif
  17300. /* Join all worker threads to avoid leaking threads. */
  17301. workerthreadcount = ctx->cfg_worker_threads;
  17302. for (i = 0; i < workerthreadcount; i++) {
  17303. if (ctx->worker_threadids[i] != 0) {
  17304. mg_join_thread(ctx->worker_threadids[i]);
  17305. }
  17306. }
  17307. #if defined(USE_LUA)
  17308. /* Free Lua state of lua background task */
  17309. if (ctx->lua_background_state) {
  17310. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17311. ctx->lua_bg_log_available = 0;
  17312. /* call "stop()" in Lua */
  17313. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17314. lua_getglobal(lstate, "stop");
  17315. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17316. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17317. if (ret != 0) {
  17318. struct mg_connection fc;
  17319. lua_cry(fake_connection(&fc, ctx),
  17320. ret,
  17321. lstate,
  17322. "lua_background_script",
  17323. "stop");
  17324. }
  17325. }
  17326. lua_close(lstate);
  17327. ctx->lua_background_state = 0;
  17328. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17329. }
  17330. #endif
  17331. DEBUG_TRACE("%s", "exiting");
  17332. /* call exit thread callback */
  17333. if (ctx->callbacks.exit_thread) {
  17334. /* Callback for the master thread (type 0) */
  17335. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17336. }
  17337. #if defined(_WIN32)
  17338. CloseHandle(tls.pthread_cond_helper_mutex);
  17339. #endif
  17340. pthread_setspecific(sTlsKey, NULL);
  17341. /* Signal mg_stop() that we're done.
  17342. * WARNING: This must be the very last thing this
  17343. * thread does, as ctx becomes invalid after this line. */
  17344. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17345. }
  17346. /* Threads have different return types on Windows and Unix. */
  17347. #if defined(_WIN32)
  17348. static unsigned __stdcall master_thread(void *thread_func_param)
  17349. {
  17350. master_thread_run((struct mg_context *)thread_func_param);
  17351. return 0;
  17352. }
  17353. #else
  17354. static void *
  17355. master_thread(void *thread_func_param)
  17356. {
  17357. #if !defined(__ZEPHYR__)
  17358. struct sigaction sa;
  17359. /* Ignore SIGPIPE */
  17360. memset(&sa, 0, sizeof(sa));
  17361. sa.sa_handler = SIG_IGN;
  17362. sigaction(SIGPIPE, &sa, NULL);
  17363. #endif
  17364. master_thread_run((struct mg_context *)thread_func_param);
  17365. return NULL;
  17366. }
  17367. #endif /* _WIN32 */
  17368. static void
  17369. free_context(struct mg_context *ctx)
  17370. {
  17371. int i;
  17372. struct mg_handler_info *tmp_rh;
  17373. if (ctx == NULL) {
  17374. return;
  17375. }
  17376. /* Call user callback */
  17377. if (ctx->callbacks.exit_context) {
  17378. ctx->callbacks.exit_context(ctx);
  17379. }
  17380. /* All threads exited, no sync is needed. Destroy thread mutex and
  17381. * condvars
  17382. */
  17383. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17384. #if defined(ALTERNATIVE_QUEUE)
  17385. mg_free(ctx->client_socks);
  17386. if (ctx->client_wait_events != NULL) {
  17387. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17388. event_destroy(ctx->client_wait_events[i]);
  17389. }
  17390. mg_free(ctx->client_wait_events);
  17391. }
  17392. #else
  17393. (void)pthread_cond_destroy(&ctx->sq_empty);
  17394. (void)pthread_cond_destroy(&ctx->sq_full);
  17395. mg_free(ctx->squeue);
  17396. #endif
  17397. /* Destroy other context global data structures mutex */
  17398. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17399. #if defined(USE_LUA)
  17400. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17401. #endif
  17402. /* Deallocate config parameters */
  17403. for (i = 0; i < NUM_OPTIONS; i++) {
  17404. if (ctx->dd.config[i] != NULL) {
  17405. #if defined(_MSC_VER)
  17406. #pragma warning(suppress : 6001)
  17407. #endif
  17408. mg_free(ctx->dd.config[i]);
  17409. }
  17410. }
  17411. /* Deallocate request handlers */
  17412. while (ctx->dd.handlers) {
  17413. tmp_rh = ctx->dd.handlers;
  17414. ctx->dd.handlers = tmp_rh->next;
  17415. mg_free(tmp_rh->uri);
  17416. mg_free(tmp_rh);
  17417. }
  17418. #if defined(USE_MBEDTLS)
  17419. if (ctx->dd.ssl_ctx != NULL) {
  17420. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17421. mg_free(ctx->dd.ssl_ctx);
  17422. ctx->dd.ssl_ctx = NULL;
  17423. }
  17424. #elif !defined(NO_SSL)
  17425. /* Deallocate SSL context */
  17426. if (ctx->dd.ssl_ctx != NULL) {
  17427. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17428. int callback_ret =
  17429. (ctx->callbacks.external_ssl_ctx == NULL)
  17430. ? 0
  17431. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17432. if (callback_ret == 0) {
  17433. SSL_CTX_free(ctx->dd.ssl_ctx);
  17434. }
  17435. /* else: ignore error and ommit SSL_CTX_free in case
  17436. * callback_ret is 1 */
  17437. }
  17438. #endif /* !NO_SSL */
  17439. /* Deallocate worker thread ID array */
  17440. mg_free(ctx->worker_threadids);
  17441. /* Deallocate worker thread ID array */
  17442. mg_free(ctx->worker_connections);
  17443. /* deallocate system name string */
  17444. mg_free(ctx->systemName);
  17445. /* Deallocate context itself */
  17446. mg_free(ctx);
  17447. }
  17448. void
  17449. mg_stop(struct mg_context *ctx)
  17450. {
  17451. pthread_t mt;
  17452. if (!ctx) {
  17453. return;
  17454. }
  17455. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17456. * two threads is not allowed. */
  17457. mt = ctx->masterthreadid;
  17458. if (mt == 0) {
  17459. return;
  17460. }
  17461. ctx->masterthreadid = 0;
  17462. /* Set stop flag, so all threads know they have to exit. */
  17463. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17464. /* Join timer thread */
  17465. #if defined(USE_TIMERS)
  17466. timers_exit(ctx);
  17467. #endif
  17468. /* Wait until everything has stopped. */
  17469. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17470. (void)mg_sleep(10);
  17471. }
  17472. /* Wait to stop master thread */
  17473. mg_join_thread(mt);
  17474. /* Close remaining Lua states */
  17475. #if defined(USE_LUA)
  17476. lua_ctx_exit(ctx);
  17477. #endif
  17478. /* Free memory */
  17479. free_context(ctx);
  17480. }
  17481. static void
  17482. get_system_name(char **sysName)
  17483. {
  17484. #if defined(_WIN32)
  17485. char name[128];
  17486. DWORD dwVersion = 0;
  17487. DWORD dwMajorVersion = 0;
  17488. DWORD dwMinorVersion = 0;
  17489. DWORD dwBuild = 0;
  17490. BOOL wowRet, isWoW = FALSE;
  17491. #if defined(_MSC_VER)
  17492. #pragma warning(push)
  17493. /* GetVersion was declared deprecated */
  17494. #pragma warning(disable : 4996)
  17495. #endif
  17496. dwVersion = GetVersion();
  17497. #if defined(_MSC_VER)
  17498. #pragma warning(pop)
  17499. #endif
  17500. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17501. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17502. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17503. (void)dwBuild;
  17504. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17505. sprintf(name,
  17506. "Windows %u.%u%s",
  17507. (unsigned)dwMajorVersion,
  17508. (unsigned)dwMinorVersion,
  17509. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17510. *sysName = mg_strdup(name);
  17511. #elif defined(__ZEPHYR__)
  17512. *sysName = mg_strdup("Zephyr OS");
  17513. #else
  17514. struct utsname name;
  17515. memset(&name, 0, sizeof(name));
  17516. uname(&name);
  17517. *sysName = mg_strdup(name.sysname);
  17518. #endif
  17519. }
  17520. static void
  17521. legacy_init(const char **options)
  17522. {
  17523. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17524. if (options) {
  17525. const char **run_options = options;
  17526. const char *optname = config_options[LISTENING_PORTS].name;
  17527. /* Try to find the "listening_ports" option */
  17528. while (*run_options) {
  17529. if (!strcmp(*run_options, optname)) {
  17530. ports_option = run_options[1];
  17531. }
  17532. run_options += 2;
  17533. }
  17534. }
  17535. if (is_ssl_port_used(ports_option)) {
  17536. /* Initialize with SSL support */
  17537. mg_init_library(MG_FEATURES_TLS);
  17538. } else {
  17539. /* Initialize without SSL support */
  17540. mg_init_library(MG_FEATURES_DEFAULT);
  17541. }
  17542. }
  17543. struct mg_context *
  17544. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17545. {
  17546. struct mg_context *ctx;
  17547. const char *name, *value, *default_value;
  17548. int idx, ok, workerthreadcount;
  17549. unsigned int i;
  17550. int itmp;
  17551. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17552. const char **options =
  17553. ((init != NULL) ? (init->configuration_options) : (NULL));
  17554. struct mg_workerTLS tls;
  17555. if (error != NULL) {
  17556. error->code = 0;
  17557. if (error->text_buffer_size > 0) {
  17558. *error->text = 0;
  17559. }
  17560. }
  17561. if (mg_init_library_called == 0) {
  17562. /* Legacy INIT, if mg_start is called without mg_init_library.
  17563. * Note: This will cause a memory leak when unloading the library.
  17564. */
  17565. legacy_init(options);
  17566. }
  17567. if (mg_init_library_called == 0) {
  17568. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17569. mg_snprintf(NULL,
  17570. NULL, /* No truncation check for error buffers */
  17571. error->text,
  17572. error->text_buffer_size,
  17573. "%s",
  17574. "Library uninitialized");
  17575. }
  17576. return NULL;
  17577. }
  17578. /* Allocate context and initialize reasonable general case defaults. */
  17579. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17580. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17581. mg_snprintf(NULL,
  17582. NULL, /* No truncation check for error buffers */
  17583. error->text,
  17584. error->text_buffer_size,
  17585. "%s",
  17586. "Out of memory");
  17587. }
  17588. return NULL;
  17589. }
  17590. /* Random number generator will initialize at the first call */
  17591. ctx->dd.auth_nonce_mask =
  17592. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17593. /* Save started thread index to reuse in other external API calls
  17594. * For the sake of thread synchronization all non-civetweb threads
  17595. * can be considered as single external thread */
  17596. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17597. tls.is_master = -1; /* Thread calling mg_start */
  17598. tls.thread_idx = ctx->starter_thread_idx;
  17599. #if defined(_WIN32)
  17600. tls.pthread_cond_helper_mutex = NULL;
  17601. #endif
  17602. pthread_setspecific(sTlsKey, &tls);
  17603. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17604. #if !defined(ALTERNATIVE_QUEUE)
  17605. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17606. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17607. ctx->sq_blocked = 0;
  17608. #endif
  17609. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17610. #if defined(USE_LUA)
  17611. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17612. #endif
  17613. if (!ok) {
  17614. const char *err_msg =
  17615. "Cannot initialize thread synchronization objects";
  17616. /* Fatal error - abort start. However, this situation should never
  17617. * occur in practice. */
  17618. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17619. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17620. mg_snprintf(NULL,
  17621. NULL, /* No truncation check for error buffers */
  17622. error->text,
  17623. error->text_buffer_size,
  17624. "%s",
  17625. err_msg);
  17626. }
  17627. mg_free(ctx);
  17628. pthread_setspecific(sTlsKey, NULL);
  17629. return NULL;
  17630. }
  17631. if ((init != NULL) && (init->callbacks != NULL)) {
  17632. /* Set all callbacks except exit_context. */
  17633. ctx->callbacks = *init->callbacks;
  17634. exit_callback = init->callbacks->exit_context;
  17635. /* The exit callback is activated once the context is successfully
  17636. * created. It should not be called, if an incomplete context object
  17637. * is deleted during a failed initialization. */
  17638. ctx->callbacks.exit_context = 0;
  17639. }
  17640. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17641. ctx->dd.handlers = NULL;
  17642. ctx->dd.next = NULL;
  17643. #if defined(USE_LUA)
  17644. lua_ctx_init(ctx);
  17645. #endif
  17646. /* Store options */
  17647. while (options && (name = *options++) != NULL) {
  17648. if ((idx = get_option_index(name)) == -1) {
  17649. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17650. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17651. mg_snprintf(NULL,
  17652. NULL, /* No truncation check for error buffers */
  17653. error->text,
  17654. error->text_buffer_size,
  17655. "Invalid configuration option: %s",
  17656. name);
  17657. }
  17658. free_context(ctx);
  17659. pthread_setspecific(sTlsKey, NULL);
  17660. return NULL;
  17661. } else if ((value = *options++) == NULL) {
  17662. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17663. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17664. mg_snprintf(NULL,
  17665. NULL, /* No truncation check for error buffers */
  17666. error->text,
  17667. error->text_buffer_size,
  17668. "Invalid configuration option value: %s",
  17669. name);
  17670. }
  17671. free_context(ctx);
  17672. pthread_setspecific(sTlsKey, NULL);
  17673. return NULL;
  17674. }
  17675. if (ctx->dd.config[idx] != NULL) {
  17676. /* A duplicate configuration option is not an error - the last
  17677. * option value will be used. */
  17678. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17679. mg_free(ctx->dd.config[idx]);
  17680. }
  17681. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17682. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17683. }
  17684. /* Set default value if needed */
  17685. for (i = 0; config_options[i].name != NULL; i++) {
  17686. default_value = config_options[i].default_value;
  17687. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17688. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17689. }
  17690. }
  17691. /* Request size option */
  17692. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17693. if (itmp < 1024) {
  17694. mg_cry_ctx_internal(ctx,
  17695. "%s too small",
  17696. config_options[MAX_REQUEST_SIZE].name);
  17697. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17698. mg_snprintf(NULL,
  17699. NULL, /* No truncation check for error buffers */
  17700. error->text,
  17701. error->text_buffer_size,
  17702. "Invalid configuration option value: %s",
  17703. config_options[MAX_REQUEST_SIZE].name);
  17704. }
  17705. free_context(ctx);
  17706. pthread_setspecific(sTlsKey, NULL);
  17707. return NULL;
  17708. }
  17709. ctx->max_request_size = (unsigned)itmp;
  17710. /* Queue length */
  17711. #if !defined(ALTERNATIVE_QUEUE)
  17712. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17713. if (itmp < 1) {
  17714. mg_cry_ctx_internal(ctx,
  17715. "%s too small",
  17716. config_options[CONNECTION_QUEUE_SIZE].name);
  17717. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17718. mg_snprintf(NULL,
  17719. NULL, /* No truncation check for error buffers */
  17720. error->text,
  17721. error->text_buffer_size,
  17722. "Invalid configuration option value: %s",
  17723. config_options[CONNECTION_QUEUE_SIZE].name);
  17724. }
  17725. free_context(ctx);
  17726. pthread_setspecific(sTlsKey, NULL);
  17727. return NULL;
  17728. }
  17729. ctx->squeue =
  17730. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17731. if (ctx->squeue == NULL) {
  17732. mg_cry_ctx_internal(ctx,
  17733. "Out of memory: Cannot allocate %s",
  17734. config_options[CONNECTION_QUEUE_SIZE].name);
  17735. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17736. mg_snprintf(NULL,
  17737. NULL, /* No truncation check for error buffers */
  17738. error->text,
  17739. error->text_buffer_size,
  17740. "Out of memory: Cannot allocate %s",
  17741. config_options[CONNECTION_QUEUE_SIZE].name);
  17742. }
  17743. free_context(ctx);
  17744. pthread_setspecific(sTlsKey, NULL);
  17745. return NULL;
  17746. }
  17747. ctx->sq_size = itmp;
  17748. #endif
  17749. /* Worker thread count option */
  17750. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17751. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17752. if (workerthreadcount <= 0) {
  17753. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17754. } else {
  17755. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17756. }
  17757. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17758. mg_snprintf(NULL,
  17759. NULL, /* No truncation check for error buffers */
  17760. error->text,
  17761. error->text_buffer_size,
  17762. "Invalid configuration option value: %s",
  17763. config_options[NUM_THREADS].name);
  17764. }
  17765. free_context(ctx);
  17766. pthread_setspecific(sTlsKey, NULL);
  17767. return NULL;
  17768. }
  17769. /* Document root */
  17770. #if defined(NO_FILES)
  17771. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17772. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17773. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17774. mg_snprintf(NULL,
  17775. NULL, /* No truncation check for error buffers */
  17776. error->text,
  17777. error->text_buffer_size,
  17778. "Invalid configuration option value: %s",
  17779. config_options[DOCUMENT_ROOT].name);
  17780. }
  17781. free_context(ctx);
  17782. pthread_setspecific(sTlsKey, NULL);
  17783. return NULL;
  17784. }
  17785. #endif
  17786. get_system_name(&ctx->systemName);
  17787. #if defined(USE_LUA)
  17788. /* If a Lua background script has been configured, start it. */
  17789. ctx->lua_bg_log_available = 0;
  17790. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17791. char ebuf[256];
  17792. struct vec opt_vec;
  17793. struct vec eq_vec;
  17794. const char *sparams;
  17795. memset(ebuf, 0, sizeof(ebuf));
  17796. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17797. /* Create a Lua state, load all standard libraries and the mg table */
  17798. lua_State *state = mg_lua_context_script_prepare(
  17799. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17800. if (!state) {
  17801. mg_cry_ctx_internal(ctx,
  17802. "lua_background_script load error: %s",
  17803. ebuf);
  17804. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17805. mg_snprintf(NULL,
  17806. NULL, /* No truncation check for error buffers */
  17807. error->text,
  17808. error->text_buffer_size,
  17809. "Error in script %s: %s",
  17810. config_options[LUA_BACKGROUND_SCRIPT].name,
  17811. ebuf);
  17812. }
  17813. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17814. free_context(ctx);
  17815. pthread_setspecific(sTlsKey, NULL);
  17816. return NULL;
  17817. }
  17818. /* Add a table with parameters into mg.params */
  17819. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17820. if (sparams && sparams[0]) {
  17821. lua_getglobal(state, "mg");
  17822. lua_pushstring(state, "params");
  17823. lua_newtable(state);
  17824. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17825. != NULL) {
  17826. reg_llstring(
  17827. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17828. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17829. break;
  17830. }
  17831. lua_rawset(state, -3);
  17832. lua_pop(state, 1);
  17833. }
  17834. /* Call script */
  17835. state = mg_lua_context_script_run(state,
  17836. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17837. ctx,
  17838. ebuf,
  17839. sizeof(ebuf));
  17840. if (!state) {
  17841. mg_cry_ctx_internal(ctx,
  17842. "lua_background_script start error: %s",
  17843. ebuf);
  17844. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17845. mg_snprintf(NULL,
  17846. NULL, /* No truncation check for error buffers */
  17847. error->text,
  17848. error->text_buffer_size,
  17849. "Error in script %s: %s",
  17850. config_options[DOCUMENT_ROOT].name,
  17851. ebuf);
  17852. }
  17853. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17854. free_context(ctx);
  17855. pthread_setspecific(sTlsKey, NULL);
  17856. return NULL;
  17857. }
  17858. /* state remains valid */
  17859. ctx->lua_background_state = (void *)state;
  17860. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17861. } else {
  17862. ctx->lua_background_state = 0;
  17863. }
  17864. #endif
  17865. /* Step by step initialization of ctx - depending on build options */
  17866. #if !defined(NO_FILESYSTEMS)
  17867. if (!set_gpass_option(ctx, NULL)) {
  17868. const char *err_msg = "Invalid global password file";
  17869. /* Fatal error - abort start. */
  17870. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17871. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17872. mg_snprintf(NULL,
  17873. NULL, /* No truncation check for error buffers */
  17874. error->text,
  17875. error->text_buffer_size,
  17876. "%s",
  17877. err_msg);
  17878. }
  17879. free_context(ctx);
  17880. pthread_setspecific(sTlsKey, NULL);
  17881. return NULL;
  17882. }
  17883. #endif
  17884. #if defined(USE_MBEDTLS)
  17885. if (!mg_sslctx_init(ctx, NULL)) {
  17886. const char *err_msg = "Error initializing SSL context";
  17887. /* Fatal error - abort start. */
  17888. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17889. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17890. mg_snprintf(NULL,
  17891. NULL, /* No truncation check for error buffers */
  17892. error->text,
  17893. error->text_buffer_size,
  17894. "%s",
  17895. err_msg);
  17896. }
  17897. free_context(ctx);
  17898. pthread_setspecific(sTlsKey, NULL);
  17899. return NULL;
  17900. }
  17901. #elif !defined(NO_SSL)
  17902. if (!init_ssl_ctx(ctx, NULL)) {
  17903. const char *err_msg = "Error initializing SSL context";
  17904. /* Fatal error - abort start. */
  17905. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17906. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17907. mg_snprintf(NULL,
  17908. NULL, /* No truncation check for error buffers */
  17909. error->text,
  17910. error->text_buffer_size,
  17911. "%s",
  17912. err_msg);
  17913. }
  17914. free_context(ctx);
  17915. pthread_setspecific(sTlsKey, NULL);
  17916. return NULL;
  17917. }
  17918. #endif
  17919. if (!set_ports_option(ctx)) {
  17920. const char *err_msg = "Failed to setup server ports";
  17921. /* Fatal error - abort start. */
  17922. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17923. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17924. mg_snprintf(NULL,
  17925. NULL, /* No truncation check for error buffers */
  17926. error->text,
  17927. error->text_buffer_size,
  17928. "%s",
  17929. err_msg);
  17930. }
  17931. free_context(ctx);
  17932. pthread_setspecific(sTlsKey, NULL);
  17933. return NULL;
  17934. }
  17935. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17936. if (!set_uid_option(ctx)) {
  17937. const char *err_msg = "Failed to run as configured user";
  17938. /* Fatal error - abort start. */
  17939. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17940. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17941. mg_snprintf(NULL,
  17942. NULL, /* No truncation check for error buffers */
  17943. error->text,
  17944. error->text_buffer_size,
  17945. "%s",
  17946. err_msg);
  17947. }
  17948. free_context(ctx);
  17949. pthread_setspecific(sTlsKey, NULL);
  17950. return NULL;
  17951. }
  17952. #endif
  17953. if (!set_acl_option(ctx)) {
  17954. const char *err_msg = "Failed to setup access control list";
  17955. /* Fatal error - abort start. */
  17956. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17957. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17958. mg_snprintf(NULL,
  17959. NULL, /* No truncation check for error buffers */
  17960. error->text,
  17961. error->text_buffer_size,
  17962. "%s",
  17963. err_msg);
  17964. }
  17965. free_context(ctx);
  17966. pthread_setspecific(sTlsKey, NULL);
  17967. return NULL;
  17968. }
  17969. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17970. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17971. sizeof(pthread_t),
  17972. ctx);
  17973. if (ctx->worker_threadids == NULL) {
  17974. const char *err_msg = "Not enough memory for worker thread ID array";
  17975. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17976. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17977. mg_snprintf(NULL,
  17978. NULL, /* No truncation check for error buffers */
  17979. error->text,
  17980. error->text_buffer_size,
  17981. "%s",
  17982. err_msg);
  17983. }
  17984. free_context(ctx);
  17985. pthread_setspecific(sTlsKey, NULL);
  17986. return NULL;
  17987. }
  17988. ctx->worker_connections =
  17989. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17990. sizeof(struct mg_connection),
  17991. ctx);
  17992. if (ctx->worker_connections == NULL) {
  17993. const char *err_msg =
  17994. "Not enough memory for worker thread connection array";
  17995. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17996. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17997. mg_snprintf(NULL,
  17998. NULL, /* No truncation check for error buffers */
  17999. error->text,
  18000. error->text_buffer_size,
  18001. "%s",
  18002. err_msg);
  18003. }
  18004. free_context(ctx);
  18005. pthread_setspecific(sTlsKey, NULL);
  18006. return NULL;
  18007. }
  18008. #if defined(ALTERNATIVE_QUEUE)
  18009. ctx->client_wait_events =
  18010. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18011. sizeof(ctx->client_wait_events[0]),
  18012. ctx);
  18013. if (ctx->client_wait_events == NULL) {
  18014. const char *err_msg = "Not enough memory for worker event array";
  18015. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18016. mg_free(ctx->worker_threadids);
  18017. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18018. mg_snprintf(NULL,
  18019. NULL, /* No truncation check for error buffers */
  18020. error->text,
  18021. error->text_buffer_size,
  18022. "%s",
  18023. err_msg);
  18024. }
  18025. free_context(ctx);
  18026. pthread_setspecific(sTlsKey, NULL);
  18027. return NULL;
  18028. }
  18029. ctx->client_socks =
  18030. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18031. sizeof(ctx->client_socks[0]),
  18032. ctx);
  18033. if (ctx->client_socks == NULL) {
  18034. const char *err_msg = "Not enough memory for worker socket array";
  18035. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18036. mg_free(ctx->client_wait_events);
  18037. mg_free(ctx->worker_threadids);
  18038. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18039. mg_snprintf(NULL,
  18040. NULL, /* No truncation check for error buffers */
  18041. error->text,
  18042. error->text_buffer_size,
  18043. "%s",
  18044. err_msg);
  18045. }
  18046. free_context(ctx);
  18047. pthread_setspecific(sTlsKey, NULL);
  18048. return NULL;
  18049. }
  18050. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18051. ctx->client_wait_events[i] = event_create();
  18052. if (ctx->client_wait_events[i] == 0) {
  18053. const char *err_msg = "Error creating worker event %i";
  18054. mg_cry_ctx_internal(ctx, err_msg, i);
  18055. while (i > 0) {
  18056. i--;
  18057. event_destroy(ctx->client_wait_events[i]);
  18058. }
  18059. mg_free(ctx->client_socks);
  18060. mg_free(ctx->client_wait_events);
  18061. mg_free(ctx->worker_threadids);
  18062. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18063. mg_snprintf(NULL,
  18064. NULL, /* No truncation check for error buffers */
  18065. error->text,
  18066. error->text_buffer_size,
  18067. err_msg,
  18068. i);
  18069. }
  18070. free_context(ctx);
  18071. pthread_setspecific(sTlsKey, NULL);
  18072. return NULL;
  18073. }
  18074. }
  18075. #endif
  18076. #if defined(USE_TIMERS)
  18077. if (timers_init(ctx) != 0) {
  18078. const char *err_msg = "Error creating timers";
  18079. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18080. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18081. mg_snprintf(NULL,
  18082. NULL, /* No truncation check for error buffers */
  18083. error->text,
  18084. error->text_buffer_size,
  18085. "%s",
  18086. err_msg);
  18087. }
  18088. free_context(ctx);
  18089. pthread_setspecific(sTlsKey, NULL);
  18090. return NULL;
  18091. }
  18092. #endif
  18093. /* Context has been created - init user libraries */
  18094. if (ctx->callbacks.init_context) {
  18095. ctx->callbacks.init_context(ctx);
  18096. }
  18097. /* From now, the context is successfully created.
  18098. * When it is destroyed, the exit callback should be called. */
  18099. ctx->callbacks.exit_context = exit_callback;
  18100. ctx->context_type = CONTEXT_SERVER; /* server context */
  18101. /* Start worker threads */
  18102. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18103. /* worker_thread sets up the other fields */
  18104. ctx->worker_connections[i].phys_ctx = ctx;
  18105. if (mg_start_thread_with_id(worker_thread,
  18106. &ctx->worker_connections[i],
  18107. &ctx->worker_threadids[i])
  18108. != 0) {
  18109. long error_no = (long)ERRNO;
  18110. /* thread was not created */
  18111. if (i > 0) {
  18112. /* If the second, third, ... thread cannot be created, set a
  18113. * warning, but keep running. */
  18114. mg_cry_ctx_internal(ctx,
  18115. "Cannot start worker thread %i: error %ld",
  18116. i + 1,
  18117. error_no);
  18118. /* If the server initialization should stop here, all
  18119. * threads that have already been created must be stopped
  18120. * first, before any free_context(ctx) call.
  18121. */
  18122. } else {
  18123. /* If the first worker thread cannot be created, stop
  18124. * initialization and free the entire server context. */
  18125. mg_cry_ctx_internal(ctx,
  18126. "Cannot create threads: error %ld",
  18127. error_no);
  18128. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18129. mg_snprintf(
  18130. NULL,
  18131. NULL, /* No truncation check for error buffers */
  18132. error->text,
  18133. error->text_buffer_size,
  18134. "Cannot create first worker thread: error %ld",
  18135. error_no);
  18136. }
  18137. free_context(ctx);
  18138. pthread_setspecific(sTlsKey, NULL);
  18139. return NULL;
  18140. }
  18141. break;
  18142. }
  18143. }
  18144. /* Start master (listening) thread */
  18145. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18146. pthread_setspecific(sTlsKey, NULL);
  18147. return ctx;
  18148. }
  18149. struct mg_context *
  18150. mg_start(const struct mg_callbacks *callbacks,
  18151. void *user_data,
  18152. const char **options)
  18153. {
  18154. struct mg_init_data init = {0};
  18155. init.callbacks = callbacks;
  18156. init.user_data = user_data;
  18157. init.configuration_options = options;
  18158. return mg_start2(&init, NULL);
  18159. }
  18160. /* Add an additional domain to an already running web server. */
  18161. int
  18162. mg_start_domain2(struct mg_context *ctx,
  18163. const char **options,
  18164. struct mg_error_data *error)
  18165. {
  18166. const char *name;
  18167. const char *value;
  18168. const char *default_value;
  18169. struct mg_domain_context *new_dom;
  18170. struct mg_domain_context *dom;
  18171. int idx, i;
  18172. if (error != NULL) {
  18173. error->code = 0;
  18174. if (error->text_buffer_size > 0) {
  18175. *error->text = 0;
  18176. }
  18177. }
  18178. if ((ctx == NULL) || (options == NULL)) {
  18179. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18180. mg_snprintf(NULL,
  18181. NULL, /* No truncation check for error buffers */
  18182. error->text,
  18183. error->text_buffer_size,
  18184. "%s",
  18185. "Invalid parameters");
  18186. }
  18187. return -1;
  18188. }
  18189. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18190. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18191. mg_snprintf(NULL,
  18192. NULL, /* No truncation check for error buffers */
  18193. error->text,
  18194. error->text_buffer_size,
  18195. "%s",
  18196. "Server already stopped");
  18197. }
  18198. return -1;
  18199. }
  18200. new_dom = (struct mg_domain_context *)
  18201. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18202. if (!new_dom) {
  18203. /* Out of memory */
  18204. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18205. mg_snprintf(NULL,
  18206. NULL, /* No truncation check for error buffers */
  18207. error->text,
  18208. error->text_buffer_size,
  18209. "%s",
  18210. "Out or memory");
  18211. }
  18212. return -6;
  18213. }
  18214. /* Store options - TODO: unite duplicate code */
  18215. while (options && (name = *options++) != NULL) {
  18216. if ((idx = get_option_index(name)) == -1) {
  18217. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18218. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18219. mg_snprintf(NULL,
  18220. NULL, /* No truncation check for error buffers */
  18221. error->text,
  18222. error->text_buffer_size,
  18223. "Invalid option: %s",
  18224. name);
  18225. }
  18226. mg_free(new_dom);
  18227. return -2;
  18228. } else if ((value = *options++) == NULL) {
  18229. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18230. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18231. mg_snprintf(NULL,
  18232. NULL, /* No truncation check for error buffers */
  18233. error->text,
  18234. error->text_buffer_size,
  18235. "Invalid option value: %s",
  18236. name);
  18237. }
  18238. mg_free(new_dom);
  18239. return -2;
  18240. }
  18241. if (new_dom->config[idx] != NULL) {
  18242. /* Duplicate option: Later values overwrite earlier ones. */
  18243. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18244. mg_free(new_dom->config[idx]);
  18245. }
  18246. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18247. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18248. }
  18249. /* Authentication domain is mandatory */
  18250. /* TODO: Maybe use a new option hostname? */
  18251. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18252. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18253. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18254. mg_snprintf(NULL,
  18255. NULL, /* No truncation check for error buffers */
  18256. error->text,
  18257. error->text_buffer_size,
  18258. "Mandatory option %s missing",
  18259. config_options[AUTHENTICATION_DOMAIN].name);
  18260. }
  18261. mg_free(new_dom);
  18262. return -4;
  18263. }
  18264. /* Set default value if needed. Take the config value from
  18265. * ctx as a default value. */
  18266. for (i = 0; config_options[i].name != NULL; i++) {
  18267. default_value = ctx->dd.config[i];
  18268. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18269. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18270. }
  18271. }
  18272. new_dom->handlers = NULL;
  18273. new_dom->next = NULL;
  18274. new_dom->nonce_count = 0;
  18275. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18276. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18277. new_dom->shared_lua_websockets = NULL;
  18278. #endif
  18279. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18280. if (!init_ssl_ctx(ctx, new_dom)) {
  18281. /* Init SSL failed */
  18282. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18283. mg_snprintf(NULL,
  18284. NULL, /* No truncation check for error buffers */
  18285. error->text,
  18286. error->text_buffer_size,
  18287. "%s",
  18288. "Initializing SSL context failed");
  18289. }
  18290. mg_free(new_dom);
  18291. return -3;
  18292. }
  18293. #endif
  18294. /* Add element to linked list. */
  18295. mg_lock_context(ctx);
  18296. idx = 0;
  18297. dom = &(ctx->dd);
  18298. for (;;) {
  18299. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18300. dom->config[AUTHENTICATION_DOMAIN])) {
  18301. /* Domain collision */
  18302. mg_cry_ctx_internal(ctx,
  18303. "domain %s already in use",
  18304. new_dom->config[AUTHENTICATION_DOMAIN]);
  18305. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18306. mg_snprintf(NULL,
  18307. NULL, /* No truncation check for error buffers */
  18308. error->text,
  18309. error->text_buffer_size,
  18310. "Domain %s specified by %s is already in use",
  18311. new_dom->config[AUTHENTICATION_DOMAIN],
  18312. config_options[AUTHENTICATION_DOMAIN].name);
  18313. }
  18314. mg_free(new_dom);
  18315. mg_unlock_context(ctx);
  18316. return -5;
  18317. }
  18318. /* Count number of domains */
  18319. idx++;
  18320. if (dom->next == NULL) {
  18321. dom->next = new_dom;
  18322. break;
  18323. }
  18324. dom = dom->next;
  18325. }
  18326. mg_unlock_context(ctx);
  18327. /* Return domain number */
  18328. return idx;
  18329. }
  18330. int
  18331. mg_start_domain(struct mg_context *ctx, const char **options)
  18332. {
  18333. return mg_start_domain2(ctx, options, NULL);
  18334. }
  18335. /* Feature check API function */
  18336. unsigned
  18337. mg_check_feature(unsigned feature)
  18338. {
  18339. static const unsigned feature_set = 0
  18340. /* Set bits for available features according to API documentation.
  18341. * This bit mask is created at compile time, according to the active
  18342. * preprocessor defines. It is a single const value at runtime. */
  18343. #if !defined(NO_FILES)
  18344. | MG_FEATURES_FILES
  18345. #endif
  18346. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18347. | MG_FEATURES_SSL
  18348. #endif
  18349. #if !defined(NO_CGI)
  18350. | MG_FEATURES_CGI
  18351. #endif
  18352. #if defined(USE_IPV6)
  18353. | MG_FEATURES_IPV6
  18354. #endif
  18355. #if defined(USE_WEBSOCKET)
  18356. | MG_FEATURES_WEBSOCKET
  18357. #endif
  18358. #if defined(USE_LUA)
  18359. | MG_FEATURES_LUA
  18360. #endif
  18361. #if defined(USE_DUKTAPE)
  18362. | MG_FEATURES_SSJS
  18363. #endif
  18364. #if !defined(NO_CACHING)
  18365. | MG_FEATURES_CACHE
  18366. #endif
  18367. #if defined(USE_SERVER_STATS)
  18368. | MG_FEATURES_STATS
  18369. #endif
  18370. #if defined(USE_ZLIB)
  18371. | MG_FEATURES_COMPRESSION
  18372. #endif
  18373. #if defined(USE_HTTP2)
  18374. | MG_FEATURES_HTTP2
  18375. #endif
  18376. #if defined(USE_X_DOM_SOCKET)
  18377. | MG_FEATURES_X_DOMAIN_SOCKET
  18378. #endif
  18379. /* Set some extra bits not defined in the API documentation.
  18380. * These bits may change without further notice. */
  18381. #if defined(MG_LEGACY_INTERFACE)
  18382. | 0x80000000u
  18383. #endif
  18384. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18385. | 0x40000000u
  18386. #endif
  18387. #if !defined(NO_RESPONSE_BUFFERING)
  18388. | 0x20000000u
  18389. #endif
  18390. #if defined(MEMORY_DEBUGGING)
  18391. | 0x10000000u
  18392. #endif
  18393. ;
  18394. return (feature & feature_set);
  18395. }
  18396. static size_t
  18397. mg_str_append(char **dst, char *end, const char *src)
  18398. {
  18399. size_t len = strlen(src);
  18400. if (*dst != end) {
  18401. /* Append src if enough space, or close dst. */
  18402. if ((size_t)(end - *dst) > len) {
  18403. strcpy(*dst, src);
  18404. *dst += len;
  18405. } else {
  18406. *dst = end;
  18407. }
  18408. }
  18409. return len;
  18410. }
  18411. /* Get system information. It can be printed or stored by the caller.
  18412. * Return the size of available information. */
  18413. int
  18414. mg_get_system_info(char *buffer, int buflen)
  18415. {
  18416. char *end, *append_eoobj = NULL, block[256];
  18417. size_t system_info_length = 0;
  18418. #if defined(_WIN32)
  18419. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18420. #else
  18421. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18422. #endif
  18423. if ((buffer == NULL) || (buflen < 1)) {
  18424. buflen = 0;
  18425. end = buffer;
  18426. } else {
  18427. *buffer = 0;
  18428. end = buffer + buflen;
  18429. }
  18430. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18431. /* has enough space to append eoobj */
  18432. append_eoobj = buffer;
  18433. if (end) {
  18434. end -= sizeof(eoobj) - 1;
  18435. }
  18436. }
  18437. system_info_length += mg_str_append(&buffer, end, "{");
  18438. /* Server version */
  18439. {
  18440. const char *version = mg_version();
  18441. mg_snprintf(NULL,
  18442. NULL,
  18443. block,
  18444. sizeof(block),
  18445. "%s\"version\" : \"%s\"",
  18446. eol,
  18447. version);
  18448. system_info_length += mg_str_append(&buffer, end, block);
  18449. }
  18450. /* System info */
  18451. {
  18452. #if defined(_WIN32)
  18453. DWORD dwVersion = 0;
  18454. DWORD dwMajorVersion = 0;
  18455. DWORD dwMinorVersion = 0;
  18456. SYSTEM_INFO si;
  18457. GetSystemInfo(&si);
  18458. #if defined(_MSC_VER)
  18459. #pragma warning(push)
  18460. /* GetVersion was declared deprecated */
  18461. #pragma warning(disable : 4996)
  18462. #endif
  18463. dwVersion = GetVersion();
  18464. #if defined(_MSC_VER)
  18465. #pragma warning(pop)
  18466. #endif
  18467. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18468. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18469. mg_snprintf(NULL,
  18470. NULL,
  18471. block,
  18472. sizeof(block),
  18473. ",%s\"os\" : \"Windows %u.%u\"",
  18474. eol,
  18475. (unsigned)dwMajorVersion,
  18476. (unsigned)dwMinorVersion);
  18477. system_info_length += mg_str_append(&buffer, end, block);
  18478. mg_snprintf(NULL,
  18479. NULL,
  18480. block,
  18481. sizeof(block),
  18482. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18483. eol,
  18484. (unsigned)si.wProcessorArchitecture,
  18485. (unsigned)si.dwNumberOfProcessors,
  18486. (unsigned)si.dwActiveProcessorMask);
  18487. system_info_length += mg_str_append(&buffer, end, block);
  18488. #elif defined(__ZEPHYR__)
  18489. mg_snprintf(NULL,
  18490. NULL,
  18491. block,
  18492. sizeof(block),
  18493. ",%s\"os\" : \"%s %s\"",
  18494. eol,
  18495. "Zephyr OS",
  18496. ZEPHYR_VERSION);
  18497. system_info_length += mg_str_append(&buffer, end, block);
  18498. #else
  18499. struct utsname name;
  18500. memset(&name, 0, sizeof(name));
  18501. uname(&name);
  18502. mg_snprintf(NULL,
  18503. NULL,
  18504. block,
  18505. sizeof(block),
  18506. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18507. eol,
  18508. name.sysname,
  18509. name.version,
  18510. name.release,
  18511. name.machine);
  18512. system_info_length += mg_str_append(&buffer, end, block);
  18513. #endif
  18514. }
  18515. /* Features */
  18516. {
  18517. mg_snprintf(NULL,
  18518. NULL,
  18519. block,
  18520. sizeof(block),
  18521. ",%s\"features\" : %lu"
  18522. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18523. eol,
  18524. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18525. eol,
  18526. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18527. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18528. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18529. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18530. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18531. : "",
  18532. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18533. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18534. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18535. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18536. system_info_length += mg_str_append(&buffer, end, block);
  18537. #if defined(USE_LUA)
  18538. mg_snprintf(NULL,
  18539. NULL,
  18540. block,
  18541. sizeof(block),
  18542. ",%s\"lua_version\" : \"%u (%s)\"",
  18543. eol,
  18544. (unsigned)LUA_VERSION_NUM,
  18545. LUA_RELEASE);
  18546. system_info_length += mg_str_append(&buffer, end, block);
  18547. #endif
  18548. #if defined(USE_DUKTAPE)
  18549. mg_snprintf(NULL,
  18550. NULL,
  18551. block,
  18552. sizeof(block),
  18553. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18554. eol,
  18555. (unsigned)DUK_VERSION / 10000,
  18556. ((unsigned)DUK_VERSION / 100) % 100,
  18557. (unsigned)DUK_VERSION % 100);
  18558. system_info_length += mg_str_append(&buffer, end, block);
  18559. #endif
  18560. }
  18561. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18562. {
  18563. #if defined(BUILD_DATE)
  18564. const char *bd = BUILD_DATE;
  18565. #else
  18566. #if defined(GCC_DIAGNOSTIC)
  18567. #if GCC_VERSION >= 40900
  18568. #pragma GCC diagnostic push
  18569. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18570. * does not work in some versions. If "BUILD_DATE" is defined to some
  18571. * string, it is used instead of __DATE__. */
  18572. #pragma GCC diagnostic ignored "-Wdate-time"
  18573. #endif
  18574. #endif
  18575. const char *bd = __DATE__;
  18576. #if defined(GCC_DIAGNOSTIC)
  18577. #if GCC_VERSION >= 40900
  18578. #pragma GCC diagnostic pop
  18579. #endif
  18580. #endif
  18581. #endif
  18582. mg_snprintf(
  18583. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18584. system_info_length += mg_str_append(&buffer, end, block);
  18585. }
  18586. /* Compiler information */
  18587. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18588. {
  18589. #if defined(_MSC_VER)
  18590. mg_snprintf(NULL,
  18591. NULL,
  18592. block,
  18593. sizeof(block),
  18594. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18595. eol,
  18596. (unsigned)_MSC_VER,
  18597. (unsigned)_MSC_FULL_VER);
  18598. system_info_length += mg_str_append(&buffer, end, block);
  18599. #elif defined(__MINGW64__)
  18600. mg_snprintf(NULL,
  18601. NULL,
  18602. block,
  18603. sizeof(block),
  18604. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18605. eol,
  18606. (unsigned)__MINGW64_VERSION_MAJOR,
  18607. (unsigned)__MINGW64_VERSION_MINOR);
  18608. system_info_length += mg_str_append(&buffer, end, block);
  18609. mg_snprintf(NULL,
  18610. NULL,
  18611. block,
  18612. sizeof(block),
  18613. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18614. eol,
  18615. (unsigned)__MINGW32_MAJOR_VERSION,
  18616. (unsigned)__MINGW32_MINOR_VERSION);
  18617. system_info_length += mg_str_append(&buffer, end, block);
  18618. #elif defined(__MINGW32__)
  18619. mg_snprintf(NULL,
  18620. NULL,
  18621. block,
  18622. sizeof(block),
  18623. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18624. eol,
  18625. (unsigned)__MINGW32_MAJOR_VERSION,
  18626. (unsigned)__MINGW32_MINOR_VERSION);
  18627. system_info_length += mg_str_append(&buffer, end, block);
  18628. #elif defined(__clang__)
  18629. mg_snprintf(NULL,
  18630. NULL,
  18631. block,
  18632. sizeof(block),
  18633. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18634. eol,
  18635. __clang_major__,
  18636. __clang_minor__,
  18637. __clang_patchlevel__,
  18638. __clang_version__);
  18639. system_info_length += mg_str_append(&buffer, end, block);
  18640. #elif defined(__GNUC__)
  18641. mg_snprintf(NULL,
  18642. NULL,
  18643. block,
  18644. sizeof(block),
  18645. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18646. eol,
  18647. (unsigned)__GNUC__,
  18648. (unsigned)__GNUC_MINOR__,
  18649. (unsigned)__GNUC_PATCHLEVEL__);
  18650. system_info_length += mg_str_append(&buffer, end, block);
  18651. #elif defined(__INTEL_COMPILER)
  18652. mg_snprintf(NULL,
  18653. NULL,
  18654. block,
  18655. sizeof(block),
  18656. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18657. eol,
  18658. (unsigned)__INTEL_COMPILER);
  18659. system_info_length += mg_str_append(&buffer, end, block);
  18660. #elif defined(__BORLANDC__)
  18661. mg_snprintf(NULL,
  18662. NULL,
  18663. block,
  18664. sizeof(block),
  18665. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18666. eol,
  18667. (unsigned)__BORLANDC__);
  18668. system_info_length += mg_str_append(&buffer, end, block);
  18669. #elif defined(__SUNPRO_C)
  18670. mg_snprintf(NULL,
  18671. NULL,
  18672. block,
  18673. sizeof(block),
  18674. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18675. eol,
  18676. (unsigned)__SUNPRO_C);
  18677. system_info_length += mg_str_append(&buffer, end, block);
  18678. #else
  18679. mg_snprintf(NULL,
  18680. NULL,
  18681. block,
  18682. sizeof(block),
  18683. ",%s\"compiler\" : \"other\"",
  18684. eol);
  18685. system_info_length += mg_str_append(&buffer, end, block);
  18686. #endif
  18687. }
  18688. /* Determine 32/64 bit data mode.
  18689. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18690. {
  18691. mg_snprintf(NULL,
  18692. NULL,
  18693. block,
  18694. sizeof(block),
  18695. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18696. "char:%u/%u, "
  18697. "ptr:%u, size:%u, time:%u\"",
  18698. eol,
  18699. (unsigned)sizeof(short),
  18700. (unsigned)sizeof(int),
  18701. (unsigned)sizeof(long),
  18702. (unsigned)sizeof(long long),
  18703. (unsigned)sizeof(float),
  18704. (unsigned)sizeof(double),
  18705. (unsigned)sizeof(long double),
  18706. (unsigned)sizeof(char),
  18707. (unsigned)sizeof(wchar_t),
  18708. (unsigned)sizeof(void *),
  18709. (unsigned)sizeof(size_t),
  18710. (unsigned)sizeof(time_t));
  18711. system_info_length += mg_str_append(&buffer, end, block);
  18712. }
  18713. /* Terminate string */
  18714. if (append_eoobj) {
  18715. strcat(append_eoobj, eoobj);
  18716. }
  18717. system_info_length += sizeof(eoobj) - 1;
  18718. return (int)system_info_length;
  18719. }
  18720. /* Get context information. It can be printed or stored by the caller.
  18721. * Return the size of available information. */
  18722. int
  18723. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18724. {
  18725. #if defined(USE_SERVER_STATS)
  18726. char *end, *append_eoobj = NULL, block[256];
  18727. size_t context_info_length = 0;
  18728. #if defined(_WIN32)
  18729. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18730. #else
  18731. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18732. #endif
  18733. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18734. if ((buffer == NULL) || (buflen < 1)) {
  18735. buflen = 0;
  18736. end = buffer;
  18737. } else {
  18738. *buffer = 0;
  18739. end = buffer + buflen;
  18740. }
  18741. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18742. /* has enough space to append eoobj */
  18743. append_eoobj = buffer;
  18744. end -= sizeof(eoobj) - 1;
  18745. }
  18746. context_info_length += mg_str_append(&buffer, end, "{");
  18747. if (ms) { /* <-- should be always true */
  18748. /* Memory information */
  18749. int blockCount = (int)ms->blockCount;
  18750. int64_t totalMemUsed = ms->totalMemUsed;
  18751. int64_t maxMemUsed = ms->maxMemUsed;
  18752. if (totalMemUsed > maxMemUsed) {
  18753. maxMemUsed = totalMemUsed;
  18754. }
  18755. mg_snprintf(NULL,
  18756. NULL,
  18757. block,
  18758. sizeof(block),
  18759. "%s\"memory\" : {%s"
  18760. "\"blocks\" : %i,%s"
  18761. "\"used\" : %" INT64_FMT ",%s"
  18762. "\"maxUsed\" : %" INT64_FMT "%s"
  18763. "}",
  18764. eol,
  18765. eol,
  18766. blockCount,
  18767. eol,
  18768. totalMemUsed,
  18769. eol,
  18770. maxMemUsed,
  18771. eol);
  18772. context_info_length += mg_str_append(&buffer, end, block);
  18773. }
  18774. if (ctx) {
  18775. /* Declare all variables at begin of the block, to comply
  18776. * with old C standards. */
  18777. char start_time_str[64] = {0};
  18778. char now_str[64] = {0};
  18779. time_t start_time = ctx->start_time;
  18780. time_t now = time(NULL);
  18781. int64_t total_data_read, total_data_written;
  18782. int active_connections = (int)ctx->active_connections;
  18783. int max_active_connections = (int)ctx->max_active_connections;
  18784. int total_connections = (int)ctx->total_connections;
  18785. if (active_connections > max_active_connections) {
  18786. max_active_connections = active_connections;
  18787. }
  18788. if (active_connections > total_connections) {
  18789. total_connections = active_connections;
  18790. }
  18791. /* Connections information */
  18792. mg_snprintf(NULL,
  18793. NULL,
  18794. block,
  18795. sizeof(block),
  18796. ",%s\"connections\" : {%s"
  18797. "\"active\" : %i,%s"
  18798. "\"maxActive\" : %i,%s"
  18799. "\"total\" : %i%s"
  18800. "}",
  18801. eol,
  18802. eol,
  18803. active_connections,
  18804. eol,
  18805. max_active_connections,
  18806. eol,
  18807. total_connections,
  18808. eol);
  18809. context_info_length += mg_str_append(&buffer, end, block);
  18810. /* Queue information */
  18811. #if !defined(ALTERNATIVE_QUEUE)
  18812. mg_snprintf(NULL,
  18813. NULL,
  18814. block,
  18815. sizeof(block),
  18816. ",%s\"queue\" : {%s"
  18817. "\"length\" : %i,%s"
  18818. "\"filled\" : %i,%s"
  18819. "\"maxFilled\" : %i,%s"
  18820. "\"full\" : %s%s"
  18821. "}",
  18822. eol,
  18823. eol,
  18824. ctx->sq_size,
  18825. eol,
  18826. ctx->sq_head - ctx->sq_tail,
  18827. eol,
  18828. ctx->sq_max_fill,
  18829. eol,
  18830. (ctx->sq_blocked ? "true" : "false"),
  18831. eol);
  18832. context_info_length += mg_str_append(&buffer, end, block);
  18833. #endif
  18834. /* Requests information */
  18835. mg_snprintf(NULL,
  18836. NULL,
  18837. block,
  18838. sizeof(block),
  18839. ",%s\"requests\" : {%s"
  18840. "\"total\" : %lu%s"
  18841. "}",
  18842. eol,
  18843. eol,
  18844. (unsigned long)ctx->total_requests,
  18845. eol);
  18846. context_info_length += mg_str_append(&buffer, end, block);
  18847. /* Data information */
  18848. total_data_read =
  18849. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18850. total_data_written =
  18851. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18852. mg_snprintf(NULL,
  18853. NULL,
  18854. block,
  18855. sizeof(block),
  18856. ",%s\"data\" : {%s"
  18857. "\"read\" : %" INT64_FMT ",%s"
  18858. "\"written\" : %" INT64_FMT "%s"
  18859. "}",
  18860. eol,
  18861. eol,
  18862. total_data_read,
  18863. eol,
  18864. total_data_written,
  18865. eol);
  18866. context_info_length += mg_str_append(&buffer, end, block);
  18867. /* Execution time information */
  18868. gmt_time_string(start_time_str,
  18869. sizeof(start_time_str) - 1,
  18870. &start_time);
  18871. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18872. mg_snprintf(NULL,
  18873. NULL,
  18874. block,
  18875. sizeof(block),
  18876. ",%s\"time\" : {%s"
  18877. "\"uptime\" : %.0f,%s"
  18878. "\"start\" : \"%s\",%s"
  18879. "\"now\" : \"%s\"%s"
  18880. "}",
  18881. eol,
  18882. eol,
  18883. difftime(now, start_time),
  18884. eol,
  18885. start_time_str,
  18886. eol,
  18887. now_str,
  18888. eol);
  18889. context_info_length += mg_str_append(&buffer, end, block);
  18890. }
  18891. /* Terminate string */
  18892. if (append_eoobj) {
  18893. strcat(append_eoobj, eoobj);
  18894. }
  18895. context_info_length += sizeof(eoobj) - 1;
  18896. return (int)context_info_length;
  18897. #else
  18898. (void)ctx;
  18899. if ((buffer != NULL) && (buflen > 0)) {
  18900. *buffer = 0;
  18901. }
  18902. return 0;
  18903. #endif
  18904. }
  18905. void
  18906. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18907. {
  18908. /* https://github.com/civetweb/civetweb/issues/727 */
  18909. if (conn != NULL) {
  18910. conn->must_close = 1;
  18911. }
  18912. }
  18913. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18914. /* Get connection information. It can be printed or stored by the caller.
  18915. * Return the size of available information. */
  18916. int
  18917. mg_get_connection_info(const struct mg_context *ctx,
  18918. int idx,
  18919. char *buffer,
  18920. int buflen)
  18921. {
  18922. const struct mg_connection *conn;
  18923. const struct mg_request_info *ri;
  18924. char *end, *append_eoobj = NULL, block[256];
  18925. size_t connection_info_length = 0;
  18926. int state = 0;
  18927. const char *state_str = "unknown";
  18928. #if defined(_WIN32)
  18929. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18930. #else
  18931. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18932. #endif
  18933. if ((buffer == NULL) || (buflen < 1)) {
  18934. buflen = 0;
  18935. end = buffer;
  18936. } else {
  18937. *buffer = 0;
  18938. end = buffer + buflen;
  18939. }
  18940. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18941. /* has enough space to append eoobj */
  18942. append_eoobj = buffer;
  18943. end -= sizeof(eoobj) - 1;
  18944. }
  18945. if ((ctx == NULL) || (idx < 0)) {
  18946. /* Parameter error */
  18947. return 0;
  18948. }
  18949. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18950. /* Out of range */
  18951. return 0;
  18952. }
  18953. /* Take connection [idx]. This connection is not locked in
  18954. * any way, so some other thread might use it. */
  18955. conn = (ctx->worker_connections) + idx;
  18956. /* Initialize output string */
  18957. connection_info_length += mg_str_append(&buffer, end, "{");
  18958. /* Init variables */
  18959. ri = &(conn->request_info);
  18960. #if defined(USE_SERVER_STATS)
  18961. state = conn->conn_state;
  18962. /* State as string */
  18963. switch (state) {
  18964. case 0:
  18965. state_str = "undefined";
  18966. break;
  18967. case 1:
  18968. state_str = "not used";
  18969. break;
  18970. case 2:
  18971. state_str = "init";
  18972. break;
  18973. case 3:
  18974. state_str = "ready";
  18975. break;
  18976. case 4:
  18977. state_str = "processing";
  18978. break;
  18979. case 5:
  18980. state_str = "processed";
  18981. break;
  18982. case 6:
  18983. state_str = "to close";
  18984. break;
  18985. case 7:
  18986. state_str = "closing";
  18987. break;
  18988. case 8:
  18989. state_str = "closed";
  18990. break;
  18991. case 9:
  18992. state_str = "done";
  18993. break;
  18994. }
  18995. #endif
  18996. /* Connection info */
  18997. if ((state >= 3) && (state < 9)) {
  18998. mg_snprintf(NULL,
  18999. NULL,
  19000. block,
  19001. sizeof(block),
  19002. "%s\"connection\" : {%s"
  19003. "\"remote\" : {%s"
  19004. "\"protocol\" : \"%s\",%s"
  19005. "\"addr\" : \"%s\",%s"
  19006. "\"port\" : %u%s"
  19007. "},%s"
  19008. "\"handled_requests\" : %u%s"
  19009. "}",
  19010. eol,
  19011. eol,
  19012. eol,
  19013. get_proto_name(conn),
  19014. eol,
  19015. ri->remote_addr,
  19016. eol,
  19017. ri->remote_port,
  19018. eol,
  19019. eol,
  19020. conn->handled_requests,
  19021. eol);
  19022. connection_info_length += mg_str_append(&buffer, end, block);
  19023. }
  19024. /* Request info */
  19025. if ((state >= 4) && (state < 6)) {
  19026. mg_snprintf(NULL,
  19027. NULL,
  19028. block,
  19029. sizeof(block),
  19030. "%s%s\"request_info\" : {%s"
  19031. "\"method\" : \"%s\",%s"
  19032. "\"uri\" : \"%s\",%s"
  19033. "\"query\" : %s%s%s%s"
  19034. "}",
  19035. (connection_info_length > 1 ? "," : ""),
  19036. eol,
  19037. eol,
  19038. ri->request_method,
  19039. eol,
  19040. ri->request_uri,
  19041. eol,
  19042. ri->query_string ? "\"" : "",
  19043. ri->query_string ? ri->query_string : "null",
  19044. ri->query_string ? "\"" : "",
  19045. eol);
  19046. connection_info_length += mg_str_append(&buffer, end, block);
  19047. }
  19048. /* Execution time information */
  19049. if ((state >= 2) && (state < 9)) {
  19050. char start_time_str[64] = {0};
  19051. char close_time_str[64] = {0};
  19052. time_t start_time = conn->conn_birth_time;
  19053. time_t close_time = 0;
  19054. double time_diff;
  19055. gmt_time_string(start_time_str,
  19056. sizeof(start_time_str) - 1,
  19057. &start_time);
  19058. #if defined(USE_SERVER_STATS)
  19059. close_time = conn->conn_close_time;
  19060. #endif
  19061. if (close_time != 0) {
  19062. time_diff = difftime(close_time, start_time);
  19063. gmt_time_string(close_time_str,
  19064. sizeof(close_time_str) - 1,
  19065. &close_time);
  19066. } else {
  19067. time_t now = time(NULL);
  19068. time_diff = difftime(now, start_time);
  19069. close_time_str[0] = 0; /* or use "now" ? */
  19070. }
  19071. mg_snprintf(NULL,
  19072. NULL,
  19073. block,
  19074. sizeof(block),
  19075. "%s%s\"time\" : {%s"
  19076. "\"uptime\" : %.0f,%s"
  19077. "\"start\" : \"%s\",%s"
  19078. "\"closed\" : \"%s\"%s"
  19079. "}",
  19080. (connection_info_length > 1 ? "," : ""),
  19081. eol,
  19082. eol,
  19083. time_diff,
  19084. eol,
  19085. start_time_str,
  19086. eol,
  19087. close_time_str,
  19088. eol);
  19089. connection_info_length += mg_str_append(&buffer, end, block);
  19090. }
  19091. /* Remote user name */
  19092. if ((ri->remote_user) && (state < 9)) {
  19093. mg_snprintf(NULL,
  19094. NULL,
  19095. block,
  19096. sizeof(block),
  19097. "%s%s\"user\" : {%s"
  19098. "\"name\" : \"%s\",%s"
  19099. "}",
  19100. (connection_info_length > 1 ? "," : ""),
  19101. eol,
  19102. eol,
  19103. ri->remote_user,
  19104. eol);
  19105. connection_info_length += mg_str_append(&buffer, end, block);
  19106. }
  19107. /* Data block */
  19108. if (state >= 3) {
  19109. mg_snprintf(NULL,
  19110. NULL,
  19111. block,
  19112. sizeof(block),
  19113. "%s%s\"data\" : {%s"
  19114. "\"read\" : %" INT64_FMT ",%s"
  19115. "\"written\" : %" INT64_FMT "%s"
  19116. "}",
  19117. (connection_info_length > 1 ? "," : ""),
  19118. eol,
  19119. eol,
  19120. conn->consumed_content,
  19121. eol,
  19122. conn->num_bytes_sent,
  19123. eol);
  19124. connection_info_length += mg_str_append(&buffer, end, block);
  19125. }
  19126. /* State */
  19127. mg_snprintf(NULL,
  19128. NULL,
  19129. block,
  19130. sizeof(block),
  19131. "%s%s\"state\" : \"%s\"",
  19132. (connection_info_length > 1 ? "," : ""),
  19133. eol,
  19134. state_str);
  19135. connection_info_length += mg_str_append(&buffer, end, block);
  19136. /* Terminate string */
  19137. if (append_eoobj) {
  19138. strcat(append_eoobj, eoobj);
  19139. }
  19140. connection_info_length += sizeof(eoobj) - 1;
  19141. return (int)connection_info_length;
  19142. }
  19143. #if 0
  19144. /* Get handler information. It can be printed or stored by the caller.
  19145. * Return the size of available information. */
  19146. int
  19147. mg_get_handler_info(struct mg_context *ctx,
  19148. char *buffer,
  19149. int buflen)
  19150. {
  19151. int handler_info_len = 0;
  19152. struct mg_handler_info *tmp_rh;
  19153. mg_lock_context(ctx);
  19154. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19155. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19156. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19157. }
  19158. handler_info_len += tmp_rh->uri_len;
  19159. switch (tmp_rh->handler_type) {
  19160. case REQUEST_HANDLER:
  19161. (void)tmp_rh->handler;
  19162. break;
  19163. case WEBSOCKET_HANDLER:
  19164. (void)tmp_rh->connect_handler;
  19165. (void) tmp_rh->ready_handler;
  19166. (void) tmp_rh->data_handler;
  19167. (void) tmp_rh->close_handler;
  19168. break;
  19169. case AUTH_HANDLER:
  19170. (void) tmp_rh->auth_handler;
  19171. break;
  19172. }
  19173. (void)cbdata;
  19174. }
  19175. mg_unlock_context(ctx);
  19176. return handler_info_len;
  19177. }
  19178. #endif
  19179. #endif
  19180. /* Initialize this library. This function does not need to be thread safe.
  19181. */
  19182. unsigned
  19183. mg_init_library(unsigned features)
  19184. {
  19185. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19186. unsigned features_inited = features_to_init;
  19187. if (mg_init_library_called <= 0) {
  19188. /* Not initialized yet */
  19189. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19190. return 0;
  19191. }
  19192. }
  19193. mg_global_lock();
  19194. if (mg_init_library_called <= 0) {
  19195. int i, len;
  19196. #if defined(_WIN32)
  19197. int file_mutex_init = 1;
  19198. int wsa = 1;
  19199. #else
  19200. int mutexattr_init = 1;
  19201. #endif
  19202. int failed = 1;
  19203. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19204. if (key_create == 0) {
  19205. #if defined(_WIN32)
  19206. file_mutex_init =
  19207. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19208. if (file_mutex_init == 0) {
  19209. /* Start WinSock */
  19210. WSADATA data;
  19211. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19212. }
  19213. #else
  19214. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19215. if (mutexattr_init == 0) {
  19216. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19217. PTHREAD_MUTEX_RECURSIVE);
  19218. }
  19219. #endif
  19220. }
  19221. if (failed) {
  19222. #if defined(_WIN32)
  19223. if (wsa == 0) {
  19224. (void)WSACleanup();
  19225. }
  19226. if (file_mutex_init == 0) {
  19227. (void)pthread_mutex_destroy(&global_log_file_lock);
  19228. }
  19229. #else
  19230. if (mutexattr_init == 0) {
  19231. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19232. }
  19233. #endif
  19234. if (key_create == 0) {
  19235. (void)pthread_key_delete(sTlsKey);
  19236. }
  19237. mg_global_unlock();
  19238. (void)pthread_mutex_destroy(&global_lock_mutex);
  19239. return 0;
  19240. }
  19241. #if defined(USE_LUA)
  19242. lua_init_optional_libraries();
  19243. #endif
  19244. len = 1;
  19245. for (i = 0; http_methods[i].name != NULL; i++) {
  19246. size_t sl = strlen(http_methods[i].name);
  19247. len += (int)sl;
  19248. if (i > 0) {
  19249. len += 2;
  19250. }
  19251. }
  19252. all_methods = mg_malloc(len);
  19253. if (!all_methods) {
  19254. /* Must never happen */
  19255. return 0;
  19256. }
  19257. all_methods[0] = 0;
  19258. for (i = 0; http_methods[i].name != NULL; i++) {
  19259. if (i > 0) {
  19260. strcat(all_methods, ", ");
  19261. strcat(all_methods, http_methods[i].name);
  19262. } else {
  19263. strcpy(all_methods, http_methods[i].name);
  19264. }
  19265. }
  19266. }
  19267. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19268. || defined(OPENSSL_API_3_0)) \
  19269. && !defined(NO_SSL)
  19270. if (features_to_init & MG_FEATURES_SSL) {
  19271. if (!mg_openssl_initialized) {
  19272. char ebuf[128];
  19273. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19274. mg_openssl_initialized = 1;
  19275. } else {
  19276. (void)ebuf;
  19277. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19278. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19279. }
  19280. } else {
  19281. /* ssl already initialized */
  19282. }
  19283. }
  19284. #endif
  19285. if (mg_init_library_called <= 0) {
  19286. mg_init_library_called = 1;
  19287. } else {
  19288. mg_init_library_called++;
  19289. }
  19290. mg_global_unlock();
  19291. return features_inited;
  19292. }
  19293. /* Un-initialize this library. */
  19294. unsigned
  19295. mg_exit_library(void)
  19296. {
  19297. if (mg_init_library_called <= 0) {
  19298. return 0;
  19299. }
  19300. mg_global_lock();
  19301. mg_init_library_called--;
  19302. if (mg_init_library_called == 0) {
  19303. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19304. if (mg_openssl_initialized) {
  19305. uninitialize_openssl();
  19306. mg_openssl_initialized = 0;
  19307. }
  19308. #endif
  19309. #if defined(_WIN32)
  19310. (void)WSACleanup();
  19311. (void)pthread_mutex_destroy(&global_log_file_lock);
  19312. #else
  19313. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19314. #endif
  19315. (void)pthread_key_delete(sTlsKey);
  19316. #if defined(USE_LUA)
  19317. lua_exit_optional_libraries();
  19318. #endif
  19319. mg_free(all_methods);
  19320. all_methods = NULL;
  19321. mg_global_unlock();
  19322. (void)pthread_mutex_destroy(&global_lock_mutex);
  19323. return 1;
  19324. }
  19325. mg_global_unlock();
  19326. return 1;
  19327. }
  19328. /* End of civetweb.c */