civetweb.c 571 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568
  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. #define ERRNO ((int)(GetLastError()))
  487. #define NO_SOCKLEN_T
  488. #if defined(_WIN64) || defined(__MINGW64__)
  489. #if !defined(SSL_LIB)
  490. #if defined(OPENSSL_API_3_0)
  491. #define SSL_LIB "libssl-3-x64.dll"
  492. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  493. #endif
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  497. #endif /* OPENSSL_API_1_1 */
  498. #if defined(OPENSSL_API_1_0)
  499. #define SSL_LIB "ssleay64.dll"
  500. #define CRYPTO_LIB "libeay64.dll"
  501. #endif /* OPENSSL_API_1_0 */
  502. #endif
  503. #else /* defined(_WIN64) || defined(__MINGW64__) */
  504. #if !defined(SSL_LIB)
  505. #if defined(OPENSSL_API_3_0)
  506. #define SSL_LIB "libssl-3.dll"
  507. #define CRYPTO_LIB "libcrypto-3.dll"
  508. #endif
  509. #if defined(OPENSSL_API_1_1)
  510. #define SSL_LIB "libssl-1_1.dll"
  511. #define CRYPTO_LIB "libcrypto-1_1.dll"
  512. #endif /* OPENSSL_API_1_1 */
  513. #if defined(OPENSSL_API_1_0)
  514. #define SSL_LIB "ssleay32.dll"
  515. #define CRYPTO_LIB "libeay32.dll"
  516. #endif /* OPENSSL_API_1_0 */
  517. #endif /* SSL_LIB */
  518. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  519. #define O_NONBLOCK (0)
  520. #if !defined(W_OK)
  521. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  522. #endif
  523. #define _POSIX_
  524. #define INT64_FMT "I64d"
  525. #define UINT64_FMT "I64u"
  526. #define WINCDECL __cdecl
  527. #define vsnprintf_impl _vsnprintf
  528. #define access _access
  529. #define mg_sleep(x) (Sleep(x))
  530. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  531. #if !defined(popen)
  532. #define popen(x, y) (_popen(x, y))
  533. #endif
  534. #if !defined(pclose)
  535. #define pclose(x) (_pclose(x))
  536. #endif
  537. #define close(x) (_close(x))
  538. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  539. #define RTLD_LAZY (0)
  540. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  541. #define fdopen(x, y) (_fdopen((x), (y)))
  542. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  543. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  544. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  545. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  546. #define sleep(x) (Sleep((x)*1000))
  547. #define rmdir(x) (_rmdir(x))
  548. #if defined(_WIN64) || !defined(__MINGW32__)
  549. /* Only MinGW 32 bit is missing this function */
  550. #define timegm(x) (_mkgmtime(x))
  551. #else
  552. time_t timegm(struct tm *tm);
  553. #define NEED_TIMEGM
  554. #endif
  555. #if !defined(fileno)
  556. #define fileno(x) (_fileno(x))
  557. #endif /* !fileno MINGW #defines fileno */
  558. typedef struct {
  559. CRITICAL_SECTION sec; /* Immovable */
  560. } pthread_mutex_t;
  561. typedef DWORD pthread_key_t;
  562. typedef HANDLE pthread_t;
  563. typedef struct {
  564. pthread_mutex_t threadIdSec;
  565. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  566. } pthread_cond_t;
  567. #if !defined(__clockid_t_defined)
  568. typedef DWORD clockid_t;
  569. #endif
  570. #if !defined(CLOCK_MONOTONIC)
  571. #define CLOCK_MONOTONIC (1)
  572. #endif
  573. #if !defined(CLOCK_REALTIME)
  574. #define CLOCK_REALTIME (2)
  575. #endif
  576. #if !defined(CLOCK_THREAD)
  577. #define CLOCK_THREAD (3)
  578. #endif
  579. #if !defined(CLOCK_PROCESS)
  580. #define CLOCK_PROCESS (4)
  581. #endif
  582. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  583. #define _TIMESPEC_DEFINED
  584. #endif
  585. #if !defined(_TIMESPEC_DEFINED)
  586. struct timespec {
  587. time_t tv_sec; /* seconds */
  588. long tv_nsec; /* nanoseconds */
  589. };
  590. #endif
  591. #if !defined(WIN_PTHREADS_TIME_H)
  592. #define MUST_IMPLEMENT_CLOCK_GETTIME
  593. #endif
  594. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  595. #define clock_gettime mg_clock_gettime
  596. static int
  597. clock_gettime(clockid_t clk_id, struct timespec *tp)
  598. {
  599. FILETIME ft;
  600. ULARGE_INTEGER li, li2;
  601. BOOL ok = FALSE;
  602. double d;
  603. static double perfcnt_per_sec = 0.0;
  604. static BOOL initialized = FALSE;
  605. if (!initialized) {
  606. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  607. perfcnt_per_sec = 1.0 / li.QuadPart;
  608. initialized = TRUE;
  609. }
  610. if (tp) {
  611. memset(tp, 0, sizeof(*tp));
  612. if (clk_id == CLOCK_REALTIME) {
  613. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  614. GetSystemTimeAsFileTime(&ft);
  615. li.LowPart = ft.dwLowDateTime;
  616. li.HighPart = ft.dwHighDateTime;
  617. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  618. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  619. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  620. ok = TRUE;
  621. /* END: CLOCK_REALTIME */
  622. } else if (clk_id == CLOCK_MONOTONIC) {
  623. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  624. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  625. d = li.QuadPart * perfcnt_per_sec;
  626. tp->tv_sec = (time_t)d;
  627. d -= (double)tp->tv_sec;
  628. tp->tv_nsec = (long)(d * 1.0E9);
  629. ok = TRUE;
  630. /* END: CLOCK_MONOTONIC */
  631. } else if (clk_id == CLOCK_THREAD) {
  632. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  633. FILETIME t_create, t_exit, t_kernel, t_user;
  634. if (GetThreadTimes(GetCurrentThread(),
  635. &t_create,
  636. &t_exit,
  637. &t_kernel,
  638. &t_user)) {
  639. li.LowPart = t_user.dwLowDateTime;
  640. li.HighPart = t_user.dwHighDateTime;
  641. li2.LowPart = t_kernel.dwLowDateTime;
  642. li2.HighPart = t_kernel.dwHighDateTime;
  643. li.QuadPart += li2.QuadPart;
  644. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  645. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  646. ok = TRUE;
  647. }
  648. /* END: CLOCK_THREAD */
  649. } else if (clk_id == CLOCK_PROCESS) {
  650. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  651. FILETIME t_create, t_exit, t_kernel, t_user;
  652. if (GetProcessTimes(GetCurrentProcess(),
  653. &t_create,
  654. &t_exit,
  655. &t_kernel,
  656. &t_user)) {
  657. li.LowPart = t_user.dwLowDateTime;
  658. li.HighPart = t_user.dwHighDateTime;
  659. li2.LowPart = t_kernel.dwLowDateTime;
  660. li2.HighPart = t_kernel.dwHighDateTime;
  661. li.QuadPart += li2.QuadPart;
  662. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  663. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  664. ok = TRUE;
  665. }
  666. /* END: CLOCK_PROCESS */
  667. } else {
  668. /* BEGIN: unknown clock */
  669. /* ok = FALSE; already set by init */
  670. /* END: unknown clock */
  671. }
  672. }
  673. return ok ? 0 : -1;
  674. }
  675. #endif
  676. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  677. static int pthread_mutex_lock(pthread_mutex_t *);
  678. static int pthread_mutex_unlock(pthread_mutex_t *);
  679. static void path_to_unicode(const struct mg_connection *conn,
  680. const char *path,
  681. wchar_t *wbuf,
  682. size_t wbuf_len);
  683. /* All file operations need to be rewritten to solve #246. */
  684. struct mg_file;
  685. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  686. /* POSIX dirent interface */
  687. struct dirent {
  688. char d_name[UTF8_PATH_MAX];
  689. };
  690. typedef struct DIR {
  691. HANDLE handle;
  692. WIN32_FIND_DATAW info;
  693. struct dirent result;
  694. } DIR;
  695. #if defined(HAVE_POLL)
  696. #define mg_pollfd pollfd
  697. #else
  698. struct mg_pollfd {
  699. SOCKET fd;
  700. short events;
  701. short revents;
  702. };
  703. #endif
  704. /* Mark required libraries */
  705. #if defined(_MSC_VER)
  706. #pragma comment(lib, "Ws2_32.lib")
  707. #endif
  708. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  709. #include <inttypes.h>
  710. /* Linux & co. internally use UTF8 */
  711. #define UTF8_PATH_MAX (PATH_MAX)
  712. typedef const void *SOCK_OPT_TYPE;
  713. #if defined(ANDROID)
  714. typedef unsigned short int in_port_t;
  715. #endif
  716. #if !defined(__ZEPHYR__)
  717. #include <arpa/inet.h>
  718. #include <ctype.h>
  719. #include <dirent.h>
  720. #include <grp.h>
  721. #include <limits.h>
  722. #include <netdb.h>
  723. #include <netinet/in.h>
  724. #include <netinet/tcp.h>
  725. #include <pthread.h>
  726. #include <pwd.h>
  727. #include <stdarg.h>
  728. #include <stddef.h>
  729. #include <stdio.h>
  730. #include <stdlib.h>
  731. #include <string.h>
  732. #include <sys/poll.h>
  733. #include <sys/socket.h>
  734. #include <sys/time.h>
  735. #include <sys/utsname.h>
  736. #include <sys/wait.h>
  737. #include <time.h>
  738. #include <unistd.h>
  739. #if defined(USE_X_DOM_SOCKET)
  740. #include <sys/un.h>
  741. #endif
  742. #endif
  743. #define vsnprintf_impl vsnprintf
  744. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  745. #include <dlfcn.h>
  746. #endif
  747. #if defined(__MACH__)
  748. #define SSL_LIB "libssl.dylib"
  749. #define CRYPTO_LIB "libcrypto.dylib"
  750. #else
  751. #if !defined(SSL_LIB)
  752. #define SSL_LIB "libssl.so"
  753. #endif
  754. #if !defined(CRYPTO_LIB)
  755. #define CRYPTO_LIB "libcrypto.so"
  756. #endif
  757. #endif
  758. #if !defined(O_BINARY)
  759. #define O_BINARY (0)
  760. #endif /* O_BINARY */
  761. #define closesocket(a) (close(a))
  762. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  763. #define mg_remove(conn, x) (remove(x))
  764. #define mg_sleep(x) (usleep((x)*1000))
  765. #define mg_opendir(conn, x) (opendir(x))
  766. #define mg_closedir(x) (closedir(x))
  767. #define mg_readdir(x) (readdir(x))
  768. #define ERRNO (errno)
  769. #define INVALID_SOCKET (-1)
  770. #define INT64_FMT PRId64
  771. #define UINT64_FMT PRIu64
  772. typedef int SOCKET;
  773. #define WINCDECL
  774. #if defined(__hpux)
  775. /* HPUX 11 does not have monotonic, fall back to realtime */
  776. #if !defined(CLOCK_MONOTONIC)
  777. #define CLOCK_MONOTONIC CLOCK_REALTIME
  778. #endif
  779. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  780. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  781. * the prototypes use int* rather than socklen_t* which matches the
  782. * actual library expectation. When called with the wrong size arg
  783. * accept() returns a zero client inet addr and check_acl() always
  784. * fails. Since socklen_t is widely used below, just force replace
  785. * their typedef with int. - DTL
  786. */
  787. #define socklen_t int
  788. #endif /* hpux */
  789. #define mg_pollfd pollfd
  790. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  791. /* In case our C library is missing "timegm", provide an implementation */
  792. #if defined(NEED_TIMEGM)
  793. static inline int
  794. is_leap(int y)
  795. {
  796. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  797. }
  798. static inline int
  799. count_leap(int y)
  800. {
  801. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  802. }
  803. time_t
  804. timegm(struct tm *tm)
  805. {
  806. static const unsigned short ydays[] = {
  807. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  808. int year = tm->tm_year + 1900;
  809. int mon = tm->tm_mon;
  810. int mday = tm->tm_mday - 1;
  811. int hour = tm->tm_hour;
  812. int min = tm->tm_min;
  813. int sec = tm->tm_sec;
  814. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  815. || (mday >= ydays[mon + 1] - ydays[mon]
  816. + (mon == 1 && is_leap(year) ? 1 : 0))
  817. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  818. return -1;
  819. time_t res = year - 1970;
  820. res *= 365;
  821. res += mday;
  822. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  823. res += count_leap(year);
  824. res *= 24;
  825. res += hour;
  826. res *= 60;
  827. res += min;
  828. res *= 60;
  829. res += sec;
  830. return res;
  831. }
  832. #endif /* NEED_TIMEGM */
  833. /* va_copy should always be a macro, C99 and C++11 - DTL */
  834. #if !defined(va_copy)
  835. #define va_copy(x, y) ((x) = (y))
  836. #endif
  837. #if defined(_WIN32)
  838. /* Create substitutes for POSIX functions in Win32. */
  839. #if defined(GCC_DIAGNOSTIC)
  840. /* Show no warning in case system functions are not used. */
  841. #pragma GCC diagnostic push
  842. #pragma GCC diagnostic ignored "-Wunused-function"
  843. #endif
  844. static pthread_mutex_t global_log_file_lock;
  845. FUNCTION_MAY_BE_UNUSED
  846. static DWORD
  847. pthread_self(void)
  848. {
  849. return GetCurrentThreadId();
  850. }
  851. FUNCTION_MAY_BE_UNUSED
  852. static int
  853. pthread_key_create(
  854. pthread_key_t *key,
  855. void (*_ignored)(void *) /* destructor not supported for Windows */
  856. )
  857. {
  858. (void)_ignored;
  859. if ((key != 0)) {
  860. *key = TlsAlloc();
  861. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  862. }
  863. return -2;
  864. }
  865. FUNCTION_MAY_BE_UNUSED
  866. static int
  867. pthread_key_delete(pthread_key_t key)
  868. {
  869. return TlsFree(key) ? 0 : 1;
  870. }
  871. FUNCTION_MAY_BE_UNUSED
  872. static int
  873. pthread_setspecific(pthread_key_t key, void *value)
  874. {
  875. return TlsSetValue(key, value) ? 0 : 1;
  876. }
  877. FUNCTION_MAY_BE_UNUSED
  878. static void *
  879. pthread_getspecific(pthread_key_t key)
  880. {
  881. return TlsGetValue(key);
  882. }
  883. #if defined(GCC_DIAGNOSTIC)
  884. /* Enable unused function warning again */
  885. #pragma GCC diagnostic pop
  886. #endif
  887. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  888. #else
  889. static pthread_mutexattr_t pthread_mutex_attr;
  890. #endif /* _WIN32 */
  891. #if defined(GCC_DIAGNOSTIC)
  892. /* Show no warning in case system functions are not used. */
  893. #pragma GCC diagnostic push
  894. #pragma GCC diagnostic ignored "-Wunused-function"
  895. #endif /* defined(GCC_DIAGNOSTIC) */
  896. #if defined(__clang__)
  897. /* Show no warning in case system functions are not used. */
  898. #pragma clang diagnostic push
  899. #pragma clang diagnostic ignored "-Wunused-function"
  900. #endif
  901. static pthread_mutex_t global_lock_mutex;
  902. FUNCTION_MAY_BE_UNUSED
  903. static void
  904. mg_global_lock(void)
  905. {
  906. (void)pthread_mutex_lock(&global_lock_mutex);
  907. }
  908. FUNCTION_MAY_BE_UNUSED
  909. static void
  910. mg_global_unlock(void)
  911. {
  912. (void)pthread_mutex_unlock(&global_lock_mutex);
  913. }
  914. #if defined(_WIN64)
  915. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  916. #elif defined(_WIN32)
  917. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  918. #endif
  919. /* Atomic functions working on ptrdiff_t ("signed size_t").
  920. * Operations: Increment, Decrement, Add, Maximum.
  921. * Up to size_t, they do not an atomic "load" operation.
  922. */
  923. FUNCTION_MAY_BE_UNUSED
  924. static ptrdiff_t
  925. mg_atomic_inc(volatile ptrdiff_t *addr)
  926. {
  927. ptrdiff_t ret;
  928. #if defined(_WIN64) && !defined(NO_ATOMICS)
  929. ret = InterlockedIncrement64(addr);
  930. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  931. ret = InterlockedIncrement(addr);
  932. #elif defined(__GNUC__) \
  933. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  934. && !defined(NO_ATOMICS)
  935. ret = __sync_add_and_fetch(addr, 1);
  936. #else
  937. mg_global_lock();
  938. ret = (++(*addr));
  939. mg_global_unlock();
  940. #endif
  941. return ret;
  942. }
  943. FUNCTION_MAY_BE_UNUSED
  944. static ptrdiff_t
  945. mg_atomic_dec(volatile ptrdiff_t *addr)
  946. {
  947. ptrdiff_t ret;
  948. #if defined(_WIN64) && !defined(NO_ATOMICS)
  949. ret = InterlockedDecrement64(addr);
  950. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  951. ret = InterlockedDecrement(addr);
  952. #elif defined(__GNUC__) \
  953. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  954. && !defined(NO_ATOMICS)
  955. ret = __sync_sub_and_fetch(addr, 1);
  956. #else
  957. mg_global_lock();
  958. ret = (--(*addr));
  959. mg_global_unlock();
  960. #endif
  961. return ret;
  962. }
  963. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  964. static ptrdiff_t
  965. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  966. {
  967. ptrdiff_t ret;
  968. #if defined(_WIN64) && !defined(NO_ATOMICS)
  969. ret = InterlockedAdd64(addr, value);
  970. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  971. ret = InterlockedExchangeAdd(addr, value) + value;
  972. #elif defined(__GNUC__) \
  973. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  974. && !defined(NO_ATOMICS)
  975. ret = __sync_add_and_fetch(addr, value);
  976. #else
  977. mg_global_lock();
  978. *addr += value;
  979. ret = (*addr);
  980. mg_global_unlock();
  981. #endif
  982. return ret;
  983. }
  984. FUNCTION_MAY_BE_UNUSED
  985. static ptrdiff_t
  986. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  987. ptrdiff_t oldval,
  988. ptrdiff_t newval)
  989. {
  990. ptrdiff_t ret;
  991. #if defined(_WIN64) && !defined(NO_ATOMICS)
  992. ret = InterlockedCompareExchange64(addr, newval, oldval);
  993. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  994. ret = InterlockedCompareExchange(addr, newval, oldval);
  995. #elif defined(__GNUC__) \
  996. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  997. && !defined(NO_ATOMICS)
  998. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  999. #else
  1000. mg_global_lock();
  1001. ret = *addr;
  1002. if ((ret != newval) && (ret == oldval)) {
  1003. *addr = newval;
  1004. }
  1005. mg_global_unlock();
  1006. #endif
  1007. return ret;
  1008. }
  1009. static void
  1010. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1011. {
  1012. register ptrdiff_t tmp = *addr;
  1013. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1014. while (tmp < value) {
  1015. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1016. }
  1017. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1018. while (tmp < value) {
  1019. tmp = InterlockedCompareExchange(addr, value, tmp);
  1020. }
  1021. #elif defined(__GNUC__) \
  1022. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1023. && !defined(NO_ATOMICS)
  1024. while (tmp < value) {
  1025. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1026. }
  1027. #else
  1028. mg_global_lock();
  1029. if (*addr < value) {
  1030. *addr = value;
  1031. }
  1032. mg_global_unlock();
  1033. #endif
  1034. }
  1035. static int64_t
  1036. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1037. {
  1038. int64_t ret;
  1039. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1040. ret = InterlockedAdd64(addr, value);
  1041. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1042. ret = InterlockedExchangeAdd64(addr, value) + value;
  1043. #elif defined(__GNUC__) \
  1044. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1045. && !defined(NO_ATOMICS)
  1046. ret = __sync_add_and_fetch(addr, value);
  1047. #else
  1048. mg_global_lock();
  1049. *addr += value;
  1050. ret = (*addr);
  1051. mg_global_unlock();
  1052. #endif
  1053. return ret;
  1054. }
  1055. #endif
  1056. #if defined(GCC_DIAGNOSTIC)
  1057. /* Show no warning in case system functions are not used. */
  1058. #pragma GCC diagnostic pop
  1059. #endif /* defined(GCC_DIAGNOSTIC) */
  1060. #if defined(__clang__)
  1061. /* Show no warning in case system functions are not used. */
  1062. #pragma clang diagnostic pop
  1063. #endif
  1064. #if defined(USE_SERVER_STATS)
  1065. struct mg_memory_stat {
  1066. volatile ptrdiff_t totalMemUsed;
  1067. volatile ptrdiff_t maxMemUsed;
  1068. volatile ptrdiff_t blockCount;
  1069. };
  1070. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1071. static void *
  1072. mg_malloc_ex(size_t size,
  1073. struct mg_context *ctx,
  1074. const char *file,
  1075. unsigned line)
  1076. {
  1077. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1078. void *memory = 0;
  1079. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1080. #if defined(MEMORY_DEBUGGING)
  1081. char mallocStr[256];
  1082. #else
  1083. (void)file;
  1084. (void)line;
  1085. #endif
  1086. if (data) {
  1087. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1088. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1089. mg_atomic_inc(&mstat->blockCount);
  1090. ((uintptr_t *)data)[0] = size;
  1091. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1092. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1093. }
  1094. #if defined(MEMORY_DEBUGGING)
  1095. sprintf(mallocStr,
  1096. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1097. memory,
  1098. (unsigned long)size,
  1099. (unsigned long)mstat->totalMemUsed,
  1100. (unsigned long)mstat->blockCount,
  1101. file,
  1102. line);
  1103. DEBUG_TRACE("%s", mallocStr);
  1104. #endif
  1105. return memory;
  1106. }
  1107. static void *
  1108. mg_calloc_ex(size_t count,
  1109. size_t size,
  1110. struct mg_context *ctx,
  1111. const char *file,
  1112. unsigned line)
  1113. {
  1114. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1115. if (data) {
  1116. memset(data, 0, size * count);
  1117. }
  1118. return data;
  1119. }
  1120. static void
  1121. mg_free_ex(void *memory, const char *file, unsigned line)
  1122. {
  1123. #if defined(MEMORY_DEBUGGING)
  1124. char mallocStr[256];
  1125. #else
  1126. (void)file;
  1127. (void)line;
  1128. #endif
  1129. if (memory) {
  1130. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1131. uintptr_t size = ((uintptr_t *)data)[0];
  1132. struct mg_memory_stat *mstat =
  1133. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1134. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1135. mg_atomic_dec(&mstat->blockCount);
  1136. #if defined(MEMORY_DEBUGGING)
  1137. sprintf(mallocStr,
  1138. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1139. memory,
  1140. (unsigned long)size,
  1141. (unsigned long)mstat->totalMemUsed,
  1142. (unsigned long)mstat->blockCount,
  1143. file,
  1144. line);
  1145. DEBUG_TRACE("%s", mallocStr);
  1146. #endif
  1147. free(data);
  1148. }
  1149. }
  1150. static void *
  1151. mg_realloc_ex(void *memory,
  1152. size_t newsize,
  1153. struct mg_context *ctx,
  1154. const char *file,
  1155. unsigned line)
  1156. {
  1157. void *data;
  1158. void *_realloc;
  1159. uintptr_t oldsize;
  1160. #if defined(MEMORY_DEBUGGING)
  1161. char mallocStr[256];
  1162. #else
  1163. (void)file;
  1164. (void)line;
  1165. #endif
  1166. if (newsize) {
  1167. if (memory) {
  1168. /* Reallocate existing block */
  1169. struct mg_memory_stat *mstat;
  1170. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1171. oldsize = ((uintptr_t *)data)[0];
  1172. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1173. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1174. if (_realloc) {
  1175. data = _realloc;
  1176. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1177. #if defined(MEMORY_DEBUGGING)
  1178. sprintf(mallocStr,
  1179. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1180. memory,
  1181. (unsigned long)oldsize,
  1182. (unsigned long)mstat->totalMemUsed,
  1183. (unsigned long)mstat->blockCount,
  1184. file,
  1185. line);
  1186. DEBUG_TRACE("%s", mallocStr);
  1187. #endif
  1188. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1189. #if defined(MEMORY_DEBUGGING)
  1190. sprintf(mallocStr,
  1191. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1192. memory,
  1193. (unsigned long)newsize,
  1194. (unsigned long)mstat->totalMemUsed,
  1195. (unsigned long)mstat->blockCount,
  1196. file,
  1197. line);
  1198. DEBUG_TRACE("%s", mallocStr);
  1199. #endif
  1200. *(uintptr_t *)data = newsize;
  1201. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1202. } else {
  1203. #if defined(MEMORY_DEBUGGING)
  1204. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1205. #endif
  1206. return _realloc;
  1207. }
  1208. } else {
  1209. /* Allocate new block */
  1210. data = mg_malloc_ex(newsize, ctx, file, line);
  1211. }
  1212. } else {
  1213. /* Free existing block */
  1214. data = 0;
  1215. mg_free_ex(memory, file, line);
  1216. }
  1217. return data;
  1218. }
  1219. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1220. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1222. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1223. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1224. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1226. #else /* USE_SERVER_STATS */
  1227. static __inline void *
  1228. mg_malloc(size_t a)
  1229. {
  1230. return malloc(a);
  1231. }
  1232. static __inline void *
  1233. mg_calloc(size_t a, size_t b)
  1234. {
  1235. return calloc(a, b);
  1236. }
  1237. static __inline void *
  1238. mg_realloc(void *a, size_t b)
  1239. {
  1240. return realloc(a, b);
  1241. }
  1242. static __inline void
  1243. mg_free(void *a)
  1244. {
  1245. free(a);
  1246. }
  1247. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1248. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1249. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1250. #define mg_free_ctx(a, c) mg_free(a)
  1251. #endif /* USE_SERVER_STATS */
  1252. static void mg_vsnprintf(const struct mg_connection *conn,
  1253. int *truncated,
  1254. char *buf,
  1255. size_t buflen,
  1256. const char *fmt,
  1257. va_list ap);
  1258. static void mg_snprintf(const struct mg_connection *conn,
  1259. int *truncated,
  1260. char *buf,
  1261. size_t buflen,
  1262. PRINTF_FORMAT_STRING(const char *fmt),
  1263. ...) PRINTF_ARGS(5, 6);
  1264. /* This following lines are just meant as a reminder to use the mg-functions
  1265. * for memory management */
  1266. #if defined(malloc)
  1267. #undef malloc
  1268. #endif
  1269. #if defined(calloc)
  1270. #undef calloc
  1271. #endif
  1272. #if defined(realloc)
  1273. #undef realloc
  1274. #endif
  1275. #if defined(free)
  1276. #undef free
  1277. #endif
  1278. #if defined(snprintf)
  1279. #undef snprintf
  1280. #endif
  1281. #if defined(vsnprintf)
  1282. #undef vsnprintf
  1283. #endif
  1284. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1285. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1286. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1287. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1288. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1289. #if defined(_WIN32)
  1290. /* vsnprintf must not be used in any system,
  1291. * but this define only works well for Windows. */
  1292. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1293. #endif
  1294. /* mg_init_library counter */
  1295. static int mg_init_library_called = 0;
  1296. #if !defined(NO_SSL)
  1297. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1298. || defined(OPENSSL_API_3_0)
  1299. static int mg_openssl_initialized = 0;
  1300. #endif
  1301. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1302. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1303. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1304. #endif
  1305. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1306. && defined(OPENSSL_API_3_0)
  1307. #error "Multiple OPENSSL_API versions defined"
  1308. #endif
  1309. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1310. || defined(OPENSSL_API_3_0)) \
  1311. && defined(USE_MBEDTLS)
  1312. #error "Multiple SSL libraries defined"
  1313. #endif
  1314. #endif
  1315. static pthread_key_t sTlsKey; /* Thread local storage index */
  1316. static volatile ptrdiff_t thread_idx_max = 0;
  1317. #if defined(MG_LEGACY_INTERFACE)
  1318. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1319. #endif
  1320. struct mg_workerTLS {
  1321. int is_master;
  1322. unsigned long thread_idx;
  1323. void *user_ptr;
  1324. #if defined(_WIN32)
  1325. HANDLE pthread_cond_helper_mutex;
  1326. struct mg_workerTLS *next_waiting_thread;
  1327. #endif
  1328. const char *alpn_proto;
  1329. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1330. char txtbuf[4];
  1331. #endif
  1332. };
  1333. #if defined(GCC_DIAGNOSTIC)
  1334. /* Show no warning in case system functions are not used. */
  1335. #pragma GCC diagnostic push
  1336. #pragma GCC diagnostic ignored "-Wunused-function"
  1337. #endif /* defined(GCC_DIAGNOSTIC) */
  1338. #if defined(__clang__)
  1339. /* Show no warning in case system functions are not used. */
  1340. #pragma clang diagnostic push
  1341. #pragma clang diagnostic ignored "-Wunused-function"
  1342. #endif
  1343. /* Get a unique thread ID as unsigned long, independent from the data type
  1344. * of thread IDs defined by the operating system API.
  1345. * If two calls to mg_current_thread_id return the same value, they calls
  1346. * are done from the same thread. If they return different values, they are
  1347. * done from different threads. (Provided this function is used in the same
  1348. * process context and threads are not repeatedly created and deleted, but
  1349. * CivetWeb does not do that).
  1350. * This function must match the signature required for SSL id callbacks:
  1351. * CRYPTO_set_id_callback
  1352. */
  1353. FUNCTION_MAY_BE_UNUSED
  1354. static unsigned long
  1355. mg_current_thread_id(void)
  1356. {
  1357. #if defined(_WIN32)
  1358. return GetCurrentThreadId();
  1359. #else
  1360. #if defined(__clang__)
  1361. #pragma clang diagnostic push
  1362. #pragma clang diagnostic ignored "-Wunreachable-code"
  1363. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1364. * or not, so one of the two conditions will be unreachable by construction.
  1365. * Unfortunately the C standard does not define a way to check this at
  1366. * compile time, since the #if preprocessor conditions can not use the
  1367. * sizeof operator as an argument. */
  1368. #endif
  1369. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1370. /* This is the problematic case for CRYPTO_set_id_callback:
  1371. * The OS pthread_t can not be cast to unsigned long. */
  1372. struct mg_workerTLS *tls =
  1373. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1374. if (tls == NULL) {
  1375. /* SSL called from an unknown thread: Create some thread index.
  1376. */
  1377. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1378. tls->is_master = -2; /* -2 means "3rd party thread" */
  1379. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1380. pthread_setspecific(sTlsKey, tls);
  1381. }
  1382. return tls->thread_idx;
  1383. } else {
  1384. /* pthread_t may be any data type, so a simple cast to unsigned long
  1385. * can rise a warning/error, depending on the platform.
  1386. * Here memcpy is used as an anything-to-anything cast. */
  1387. unsigned long ret = 0;
  1388. pthread_t t = pthread_self();
  1389. memcpy(&ret, &t, sizeof(pthread_t));
  1390. return ret;
  1391. }
  1392. #if defined(__clang__)
  1393. #pragma clang diagnostic pop
  1394. #endif
  1395. #endif
  1396. }
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static uint64_t
  1399. mg_get_current_time_ns(void)
  1400. {
  1401. struct timespec tsnow;
  1402. clock_gettime(CLOCK_REALTIME, &tsnow);
  1403. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1404. }
  1405. #if defined(GCC_DIAGNOSTIC)
  1406. /* Show no warning in case system functions are not used. */
  1407. #pragma GCC diagnostic pop
  1408. #endif /* defined(GCC_DIAGNOSTIC) */
  1409. #if defined(__clang__)
  1410. /* Show no warning in case system functions are not used. */
  1411. #pragma clang diagnostic pop
  1412. #endif
  1413. #if defined(NEED_DEBUG_TRACE_FUNC)
  1414. static void
  1415. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1416. {
  1417. va_list args;
  1418. struct timespec tsnow;
  1419. /* Get some operating system independent thread id */
  1420. unsigned long thread_id = mg_current_thread_id();
  1421. clock_gettime(CLOCK_REALTIME, &tsnow);
  1422. flockfile(DEBUG_TRACE_STREAM);
  1423. fprintf(DEBUG_TRACE_STREAM,
  1424. "*** %lu.%09lu %lu %s:%u: ",
  1425. (unsigned long)tsnow.tv_sec,
  1426. (unsigned long)tsnow.tv_nsec,
  1427. thread_id,
  1428. func,
  1429. line);
  1430. va_start(args, fmt);
  1431. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1432. va_end(args);
  1433. putc('\n', DEBUG_TRACE_STREAM);
  1434. fflush(DEBUG_TRACE_STREAM);
  1435. funlockfile(DEBUG_TRACE_STREAM);
  1436. }
  1437. #endif /* NEED_DEBUG_TRACE_FUNC */
  1438. #define MD5_STATIC static
  1439. #include "md5.inl"
  1440. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1441. #if defined(NO_SOCKLEN_T)
  1442. typedef int socklen_t;
  1443. #endif /* NO_SOCKLEN_T */
  1444. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1445. #if !defined(MSG_NOSIGNAL)
  1446. #define MSG_NOSIGNAL (0)
  1447. #endif
  1448. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1449. #if defined(USE_MBEDTLS)
  1450. /* mbedTLS */
  1451. #include "mod_mbedtls.inl"
  1452. #elif defined(NO_SSL)
  1453. /* no SSL */
  1454. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1455. typedef struct SSL_CTX SSL_CTX;
  1456. #elif defined(NO_SSL_DL)
  1457. /* OpenSSL without dynamic loading */
  1458. #include <openssl/bn.h>
  1459. #include <openssl/conf.h>
  1460. #include <openssl/crypto.h>
  1461. #include <openssl/dh.h>
  1462. #include <openssl/engine.h>
  1463. #include <openssl/err.h>
  1464. #include <openssl/opensslv.h>
  1465. #include <openssl/pem.h>
  1466. #include <openssl/ssl.h>
  1467. #include <openssl/tls1.h>
  1468. #include <openssl/x509.h>
  1469. #if defined(WOLFSSL_VERSION)
  1470. /* Additional defines for WolfSSL, see
  1471. * https://github.com/civetweb/civetweb/issues/583 */
  1472. #include "wolfssl_extras.inl"
  1473. #endif
  1474. #if defined(OPENSSL_IS_BORINGSSL)
  1475. /* From boringssl/src/include/openssl/mem.h:
  1476. *
  1477. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1478. * However, that was written in a time before Valgrind and ASAN. Since we now
  1479. * have those tools, the OpenSSL allocation functions are simply macros around
  1480. * the standard memory functions.
  1481. *
  1482. * #define OPENSSL_free free */
  1483. #define free free
  1484. // disable for boringssl
  1485. #define CONF_modules_unload(a) ((void)0)
  1486. #define ENGINE_cleanup() ((void)0)
  1487. #endif
  1488. /* If OpenSSL headers are included, automatically select the API version */
  1489. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1490. #if !defined(OPENSSL_API_3_0)
  1491. #define OPENSSL_API_3_0
  1492. #endif
  1493. #define OPENSSL_REMOVE_THREAD_STATE()
  1494. #else
  1495. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1496. #if !defined(OPENSSL_API_1_1)
  1497. #define OPENSSL_API_1_1
  1498. #endif
  1499. #define OPENSSL_REMOVE_THREAD_STATE()
  1500. #else
  1501. #if !defined(OPENSSL_API_1_0)
  1502. #define OPENSSL_API_1_0
  1503. #endif
  1504. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1505. #endif
  1506. #endif
  1507. #else
  1508. /* SSL loaded dynamically from DLL / shared object */
  1509. /* Add all prototypes here, to be independent from OpenSSL source
  1510. * installation. */
  1511. #include "openssl_dl.inl"
  1512. #endif /* Various SSL bindings */
  1513. #if !defined(NO_CACHING)
  1514. static const char month_names[][4] = {"Jan",
  1515. "Feb",
  1516. "Mar",
  1517. "Apr",
  1518. "May",
  1519. "Jun",
  1520. "Jul",
  1521. "Aug",
  1522. "Sep",
  1523. "Oct",
  1524. "Nov",
  1525. "Dec"};
  1526. #endif /* !NO_CACHING */
  1527. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1528. * the union u. */
  1529. union usa {
  1530. struct sockaddr sa;
  1531. struct sockaddr_in sin;
  1532. #if defined(USE_IPV6)
  1533. struct sockaddr_in6 sin6;
  1534. #endif
  1535. #if defined(USE_X_DOM_SOCKET)
  1536. struct sockaddr_un sun;
  1537. #endif
  1538. };
  1539. #if defined(USE_X_DOM_SOCKET)
  1540. static unsigned short
  1541. USA_IN_PORT_UNSAFE(union usa *s)
  1542. {
  1543. if (s->sa.sa_family == AF_INET)
  1544. return s->sin.sin_port;
  1545. #if defined(USE_IPV6)
  1546. if (s->sa.sa_family == AF_INET6)
  1547. return s->sin6.sin6_port;
  1548. #endif
  1549. return 0;
  1550. }
  1551. #endif
  1552. #if defined(USE_IPV6)
  1553. #define USA_IN_PORT_UNSAFE(s) \
  1554. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1555. #else
  1556. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1557. #endif
  1558. /* Describes a string (chunk of memory). */
  1559. struct vec {
  1560. const char *ptr;
  1561. size_t len;
  1562. };
  1563. struct mg_file_stat {
  1564. /* File properties filled by mg_stat: */
  1565. uint64_t size;
  1566. time_t last_modified;
  1567. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1568. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1569. * case we need a "Content-Eencoding: gzip" header */
  1570. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1571. };
  1572. struct mg_file_access {
  1573. /* File properties filled by mg_fopen: */
  1574. FILE *fp;
  1575. };
  1576. struct mg_file {
  1577. struct mg_file_stat stat;
  1578. struct mg_file_access access;
  1579. };
  1580. #define STRUCT_FILE_INITIALIZER \
  1581. { \
  1582. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1583. { \
  1584. (FILE *)NULL \
  1585. } \
  1586. }
  1587. /* Describes listening socket, or socket which was accept()-ed by the master
  1588. * thread and queued for future handling by the worker thread. */
  1589. struct socket {
  1590. SOCKET sock; /* Listening socket */
  1591. union usa lsa; /* Local socket address */
  1592. union usa rsa; /* Remote socket address */
  1593. unsigned char is_ssl; /* Is port SSL-ed */
  1594. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1595. * port */
  1596. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1597. };
  1598. /* Enum const for all options must be in sync with
  1599. * static struct mg_option config_options[]
  1600. * This is tested in the unit test (test/private.c)
  1601. * "Private Config Options"
  1602. */
  1603. enum {
  1604. /* Once for each server */
  1605. LISTENING_PORTS,
  1606. NUM_THREADS,
  1607. RUN_AS_USER,
  1608. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1609. * socket option typedef TCP_NODELAY. */
  1610. MAX_REQUEST_SIZE,
  1611. LINGER_TIMEOUT,
  1612. CONNECTION_QUEUE_SIZE,
  1613. LISTEN_BACKLOG_SIZE,
  1614. #if defined(__linux__)
  1615. ALLOW_SENDFILE_CALL,
  1616. #endif
  1617. #if defined(_WIN32)
  1618. CASE_SENSITIVE_FILES,
  1619. #endif
  1620. THROTTLE,
  1621. ENABLE_KEEP_ALIVE,
  1622. REQUEST_TIMEOUT,
  1623. KEEP_ALIVE_TIMEOUT,
  1624. #if defined(USE_WEBSOCKET)
  1625. WEBSOCKET_TIMEOUT,
  1626. ENABLE_WEBSOCKET_PING_PONG,
  1627. #endif
  1628. DECODE_URL,
  1629. DECODE_QUERY_STRING,
  1630. #if defined(USE_LUA)
  1631. LUA_BACKGROUND_SCRIPT,
  1632. LUA_BACKGROUND_SCRIPT_PARAMS,
  1633. #endif
  1634. #if defined(USE_HTTP2)
  1635. ENABLE_HTTP2,
  1636. #endif
  1637. /* Once for each domain */
  1638. DOCUMENT_ROOT,
  1639. ACCESS_LOG_FILE,
  1640. ERROR_LOG_FILE,
  1641. CGI_EXTENSIONS,
  1642. CGI_ENVIRONMENT,
  1643. CGI_INTERPRETER,
  1644. CGI_INTERPRETER_ARGS,
  1645. #if defined(USE_TIMERS)
  1646. CGI_TIMEOUT,
  1647. #endif
  1648. CGI2_EXTENSIONS,
  1649. CGI2_ENVIRONMENT,
  1650. CGI2_INTERPRETER,
  1651. CGI2_INTERPRETER_ARGS,
  1652. #if defined(USE_TIMERS)
  1653. CGI2_TIMEOUT,
  1654. #endif
  1655. #if defined(USE_4_CGI)
  1656. CGI3_EXTENSIONS,
  1657. CGI3_ENVIRONMENT,
  1658. CGI3_INTERPRETER,
  1659. CGI3_INTERPRETER_ARGS,
  1660. #if defined(USE_TIMERS)
  1661. CGI3_TIMEOUT,
  1662. #endif
  1663. CGI4_EXTENSIONS,
  1664. CGI4_ENVIRONMENT,
  1665. CGI4_INTERPRETER,
  1666. CGI4_INTERPRETER_ARGS,
  1667. #if defined(USE_TIMERS)
  1668. CGI4_TIMEOUT,
  1669. #endif
  1670. #endif
  1671. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1672. PROTECT_URI,
  1673. AUTHENTICATION_DOMAIN,
  1674. ENABLE_AUTH_DOMAIN_CHECK,
  1675. SSI_EXTENSIONS,
  1676. ENABLE_DIRECTORY_LISTING,
  1677. GLOBAL_PASSWORDS_FILE,
  1678. INDEX_FILES,
  1679. ACCESS_CONTROL_LIST,
  1680. EXTRA_MIME_TYPES,
  1681. SSL_CERTIFICATE,
  1682. SSL_CERTIFICATE_CHAIN,
  1683. URL_REWRITE_PATTERN,
  1684. HIDE_FILES,
  1685. SSL_DO_VERIFY_PEER,
  1686. SSL_CACHE_TIMEOUT,
  1687. SSL_CA_PATH,
  1688. SSL_CA_FILE,
  1689. SSL_VERIFY_DEPTH,
  1690. SSL_DEFAULT_VERIFY_PATHS,
  1691. SSL_CIPHER_LIST,
  1692. SSL_PROTOCOL_VERSION,
  1693. SSL_SHORT_TRUST,
  1694. #if defined(USE_LUA)
  1695. LUA_PRELOAD_FILE,
  1696. LUA_SCRIPT_EXTENSIONS,
  1697. LUA_SERVER_PAGE_EXTENSIONS,
  1698. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1699. LUA_DEBUG_PARAMS,
  1700. #endif
  1701. #endif
  1702. #if defined(USE_DUKTAPE)
  1703. DUKTAPE_SCRIPT_EXTENSIONS,
  1704. #endif
  1705. #if defined(USE_WEBSOCKET)
  1706. WEBSOCKET_ROOT,
  1707. #endif
  1708. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1709. LUA_WEBSOCKET_EXTENSIONS,
  1710. #endif
  1711. ACCESS_CONTROL_ALLOW_ORIGIN,
  1712. ACCESS_CONTROL_ALLOW_METHODS,
  1713. ACCESS_CONTROL_ALLOW_HEADERS,
  1714. ERROR_PAGES,
  1715. #if !defined(NO_CACHING)
  1716. STATIC_FILE_MAX_AGE,
  1717. STATIC_FILE_CACHE_CONTROL,
  1718. #endif
  1719. #if !defined(NO_SSL)
  1720. STRICT_HTTPS_MAX_AGE,
  1721. #endif
  1722. ADDITIONAL_HEADER,
  1723. ALLOW_INDEX_SCRIPT_SUB_RES,
  1724. NUM_OPTIONS
  1725. };
  1726. /* Config option name, config types, default value.
  1727. * Must be in the same order as the enum const above.
  1728. */
  1729. static const struct mg_option config_options[] = {
  1730. /* Once for each server */
  1731. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1732. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1733. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1734. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1735. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1736. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1737. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1738. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1739. #if defined(__linux__)
  1740. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1741. #endif
  1742. #if defined(_WIN32)
  1743. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1744. #endif
  1745. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1746. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1747. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1748. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1749. #if defined(USE_WEBSOCKET)
  1750. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1751. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1752. #endif
  1753. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1754. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1755. #if defined(USE_LUA)
  1756. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1757. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1758. #endif
  1759. #if defined(USE_HTTP2)
  1760. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1761. #endif
  1762. /* Once for each domain */
  1763. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1764. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1765. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1766. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1767. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1768. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1769. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1770. #if defined(USE_TIMERS)
  1771. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1772. #endif
  1773. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1774. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1775. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1776. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1777. #if defined(USE_TIMERS)
  1778. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1779. #endif
  1780. #if defined(USE_4_CGI)
  1781. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1782. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1783. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1784. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1785. #if defined(USE_TIMERS)
  1786. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1787. #endif
  1788. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1789. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1790. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1791. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1792. #if defined(USE_TIMERS)
  1793. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1794. #endif
  1795. #endif
  1796. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1797. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1798. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1799. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1800. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1801. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1802. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1803. {"index_files",
  1804. MG_CONFIG_TYPE_STRING_LIST,
  1805. #if defined(USE_LUA)
  1806. "index.xhtml,index.html,index.htm,"
  1807. "index.lp,index.lsp,index.lua,index.cgi,"
  1808. "index.shtml,index.php"},
  1809. #else
  1810. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1811. #endif
  1812. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1813. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1814. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1815. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1816. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1817. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1818. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1819. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1820. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1821. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1822. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1823. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1824. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1825. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1826. * as a minimum in 2020 */
  1827. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1828. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1829. #if defined(USE_LUA)
  1830. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1831. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1832. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1833. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1834. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1835. #endif
  1836. #endif
  1837. #if defined(USE_DUKTAPE)
  1838. /* The support for duktape is still in alpha version state.
  1839. * The name of this config option might change. */
  1840. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1841. #endif
  1842. #if defined(USE_WEBSOCKET)
  1843. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1844. #endif
  1845. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1846. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1847. #endif
  1848. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1849. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1850. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1851. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1852. #if !defined(NO_CACHING)
  1853. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1854. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1855. #endif
  1856. #if !defined(NO_SSL)
  1857. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1858. #endif
  1859. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1860. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1861. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1862. /* Check if the config_options and the corresponding enum have compatible
  1863. * sizes. */
  1864. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1865. == (NUM_OPTIONS + 1),
  1866. "config_options and enum not sync");
  1867. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1868. struct mg_handler_info {
  1869. /* Name/Pattern of the URI. */
  1870. char *uri;
  1871. size_t uri_len;
  1872. /* handler type */
  1873. int handler_type;
  1874. /* Handler for http/https or authorization requests. */
  1875. mg_request_handler handler;
  1876. unsigned int refcount;
  1877. int removing;
  1878. /* Handler for ws/wss (websocket) requests. */
  1879. mg_websocket_connect_handler connect_handler;
  1880. mg_websocket_ready_handler ready_handler;
  1881. mg_websocket_data_handler data_handler;
  1882. mg_websocket_close_handler close_handler;
  1883. /* accepted subprotocols for ws/wss requests. */
  1884. struct mg_websocket_subprotocols *subprotocols;
  1885. /* Handler for authorization requests */
  1886. mg_authorization_handler auth_handler;
  1887. /* User supplied argument for the handler function. */
  1888. void *cbdata;
  1889. /* next handler in a linked list */
  1890. struct mg_handler_info *next;
  1891. };
  1892. enum {
  1893. CONTEXT_INVALID,
  1894. CONTEXT_SERVER,
  1895. CONTEXT_HTTP_CLIENT,
  1896. CONTEXT_WS_CLIENT
  1897. };
  1898. struct mg_domain_context {
  1899. SSL_CTX *ssl_ctx; /* SSL context */
  1900. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1901. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1902. int64_t ssl_cert_last_mtime;
  1903. /* Server nonce */
  1904. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1905. unsigned long nonce_count; /* Used nonces, used for authentication */
  1906. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1907. /* linked list of shared lua websockets */
  1908. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1909. #endif
  1910. /* Linked list of domains */
  1911. struct mg_domain_context *next;
  1912. };
  1913. /* Stop flag can be "volatile" or require a lock.
  1914. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1915. * states a read operation for int is always atomic. */
  1916. #if defined(STOP_FLAG_NEEDS_LOCK)
  1917. typedef ptrdiff_t volatile stop_flag_t;
  1918. static int
  1919. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  1920. {
  1921. stop_flag_t sf = mg_atomic_add(f, 0);
  1922. return (sf == 0);
  1923. }
  1924. static int
  1925. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1926. {
  1927. stop_flag_t sf = mg_atomic_add(f, 0);
  1928. return (sf == 2);
  1929. }
  1930. static void
  1931. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1932. {
  1933. stop_flag_t sf;
  1934. do {
  1935. sf = mg_atomic_compare_and_swap(f, *f, v);
  1936. } while (sf != v);
  1937. }
  1938. #else /* STOP_FLAG_NEEDS_LOCK */
  1939. typedef int volatile stop_flag_t;
  1940. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1941. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1942. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1943. #endif /* STOP_FLAG_NEEDS_LOCK */
  1944. struct mg_context {
  1945. /* Part 1 - Physical context:
  1946. * This holds threads, ports, timeouts, ...
  1947. * set for the entire server, independent from the
  1948. * addressed hostname.
  1949. */
  1950. /* Connection related */
  1951. int context_type; /* See CONTEXT_* above */
  1952. struct socket *listening_sockets;
  1953. struct mg_pollfd *listening_socket_fds;
  1954. unsigned int num_listening_sockets;
  1955. struct mg_connection *worker_connections; /* The connection struct, pre-
  1956. * allocated for each worker */
  1957. #if defined(USE_SERVER_STATS)
  1958. volatile ptrdiff_t active_connections;
  1959. volatile ptrdiff_t max_active_connections;
  1960. volatile ptrdiff_t total_connections;
  1961. volatile ptrdiff_t total_requests;
  1962. volatile int64_t total_data_read;
  1963. volatile int64_t total_data_written;
  1964. #endif
  1965. /* Thread related */
  1966. stop_flag_t stop_flag; /* Should we stop event loop */
  1967. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1968. pthread_t masterthreadid; /* The master thread ID */
  1969. unsigned int
  1970. cfg_worker_threads; /* The number of configured worker threads. */
  1971. pthread_t *worker_threadids; /* The worker thread IDs */
  1972. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1973. /* Connection to thread dispatching */
  1974. #if defined(ALTERNATIVE_QUEUE)
  1975. struct socket *client_socks;
  1976. void **client_wait_events;
  1977. #else
  1978. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  1979. worker thread */
  1980. volatile int sq_head; /* Head of the socket queue */
  1981. volatile int sq_tail; /* Tail of the socket queue */
  1982. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1983. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1984. volatile int sq_blocked; /* Status information: sq is full */
  1985. int sq_size; /* No of elements in socket queue */
  1986. #if defined(USE_SERVER_STATS)
  1987. int sq_max_fill;
  1988. #endif /* USE_SERVER_STATS */
  1989. #endif /* ALTERNATIVE_QUEUE */
  1990. /* Memory related */
  1991. unsigned int max_request_size; /* The max request size */
  1992. #if defined(USE_SERVER_STATS)
  1993. struct mg_memory_stat ctx_memory;
  1994. #endif
  1995. /* Operating system related */
  1996. char *systemName; /* What operating system is running */
  1997. time_t start_time; /* Server start time, used for authentication
  1998. * and for diagnstics. */
  1999. #if defined(USE_TIMERS)
  2000. struct ttimers *timers;
  2001. #endif
  2002. /* Lua specific: Background operations and shared websockets */
  2003. #if defined(USE_LUA)
  2004. void *lua_background_state; /* lua_State (here as void *) */
  2005. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2006. int lua_bg_log_available; /* Use Lua background state for access log */
  2007. #endif
  2008. /* Server nonce */
  2009. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2010. * ssl_cert_last_mtime, nonce_count, and
  2011. * next (linked list) */
  2012. /* Server callbacks */
  2013. struct mg_callbacks callbacks; /* User-defined callback function */
  2014. void *user_data; /* User-defined data */
  2015. /* Part 2 - Logical domain:
  2016. * This holds hostname, TLS certificate, document root, ...
  2017. * set for a domain hosted at the server.
  2018. * There may be multiple domains hosted at one physical server.
  2019. * The default domain "dd" is the first element of a list of
  2020. * domains.
  2021. */
  2022. struct mg_domain_context dd; /* default domain */
  2023. };
  2024. #if defined(USE_SERVER_STATS)
  2025. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2026. static struct mg_memory_stat *
  2027. get_memory_stat(struct mg_context *ctx)
  2028. {
  2029. if (ctx) {
  2030. return &(ctx->ctx_memory);
  2031. }
  2032. return &mg_common_memory;
  2033. }
  2034. #endif
  2035. enum {
  2036. CONNECTION_TYPE_INVALID = 0,
  2037. CONNECTION_TYPE_REQUEST = 1,
  2038. CONNECTION_TYPE_RESPONSE = 2
  2039. };
  2040. enum {
  2041. PROTOCOL_TYPE_HTTP1 = 0,
  2042. PROTOCOL_TYPE_WEBSOCKET = 1,
  2043. PROTOCOL_TYPE_HTTP2 = 2
  2044. };
  2045. #if defined(USE_HTTP2)
  2046. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2047. #define HTTP2_DYN_TABLE_SIZE (256)
  2048. #endif
  2049. struct mg_http2_connection {
  2050. uint32_t stream_id;
  2051. uint32_t dyn_table_size;
  2052. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2053. };
  2054. #endif
  2055. struct mg_connection {
  2056. int connection_type; /* see CONNECTION_TYPE_* above */
  2057. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2058. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2059. fully sent */
  2060. #if defined(USE_HTTP2)
  2061. struct mg_http2_connection http2;
  2062. #endif
  2063. struct mg_request_info request_info;
  2064. struct mg_response_info response_info;
  2065. struct mg_context *phys_ctx;
  2066. struct mg_domain_context *dom_ctx;
  2067. #if defined(USE_SERVER_STATS)
  2068. int conn_state; /* 0 = undef, numerical value may change in different
  2069. * versions. For the current definition, see
  2070. * mg_get_connection_info_impl */
  2071. #endif
  2072. SSL *ssl; /* SSL descriptor */
  2073. struct socket client; /* Connected client */
  2074. time_t conn_birth_time; /* Time (wall clock) when connection was
  2075. * established */
  2076. #if defined(USE_SERVER_STATS)
  2077. time_t conn_close_time; /* Time (wall clock) when connection was
  2078. * closed (or 0 if still open) */
  2079. double processing_time; /* Procesing time for one request. */
  2080. #endif
  2081. struct timespec req_time; /* Time (since system start) when the request
  2082. * was received */
  2083. int64_t num_bytes_sent; /* Total bytes sent to client */
  2084. int64_t content_len; /* How many bytes of content can be read
  2085. * !is_chunked: Content-Length header value
  2086. * or -1 (until connection closed,
  2087. * not allowed for a request)
  2088. * is_chunked: >= 0, appended gradually
  2089. */
  2090. int64_t consumed_content; /* How many bytes of content have been read */
  2091. int is_chunked; /* Transfer-Encoding is chunked:
  2092. * 0 = not chunked,
  2093. * 1 = chunked, not yet, or some data read,
  2094. * 2 = chunked, has error,
  2095. * 3 = chunked, all data read except trailer,
  2096. * 4 = chunked, all data read
  2097. */
  2098. char *buf; /* Buffer for received data */
  2099. char *path_info; /* PATH_INFO part of the URL */
  2100. int must_close; /* 1 if connection must be closed */
  2101. int accept_gzip; /* 1 if gzip encoding is accepted */
  2102. int in_error_handler; /* 1 if in handler for user defined error
  2103. * pages */
  2104. #if defined(USE_WEBSOCKET)
  2105. int in_websocket_handling; /* 1 if in read_websocket */
  2106. #endif
  2107. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2108. && defined(MG_EXPERIMENTAL_INTERFACES)
  2109. /* Parameters for websocket data compression according to rfc7692 */
  2110. int websocket_deflate_server_max_windows_bits;
  2111. int websocket_deflate_client_max_windows_bits;
  2112. int websocket_deflate_server_no_context_takeover;
  2113. int websocket_deflate_client_no_context_takeover;
  2114. int websocket_deflate_initialized;
  2115. int websocket_deflate_flush;
  2116. z_stream websocket_deflate_state;
  2117. z_stream websocket_inflate_state;
  2118. #endif
  2119. int handled_requests; /* Number of requests handled by this connection
  2120. */
  2121. int buf_size; /* Buffer size */
  2122. int request_len; /* Size of the request + headers in a buffer */
  2123. int data_len; /* Total size of data in a buffer */
  2124. int status_code; /* HTTP reply status code, e.g. 200 */
  2125. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2126. * throttle */
  2127. time_t last_throttle_time; /* Last time throttled data was sent */
  2128. int last_throttle_bytes; /* Bytes sent this second */
  2129. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2130. * atomic transmissions for websockets */
  2131. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2132. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2133. #endif
  2134. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2135. * for quick access */
  2136. };
  2137. /* Directory entry */
  2138. struct de {
  2139. struct mg_connection *conn;
  2140. char *file_name;
  2141. struct mg_file_stat file;
  2142. };
  2143. #define mg_cry_internal(conn, fmt, ...) \
  2144. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2145. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2146. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2147. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2148. struct mg_context *ctx,
  2149. const char *func,
  2150. unsigned line,
  2151. const char *fmt,
  2152. ...) PRINTF_ARGS(5, 6);
  2153. #if !defined(NO_THREAD_NAME)
  2154. #if defined(_WIN32) && defined(_MSC_VER)
  2155. /* Set the thread name for debugging purposes in Visual Studio
  2156. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2157. */
  2158. #pragma pack(push, 8)
  2159. typedef struct tagTHREADNAME_INFO {
  2160. DWORD dwType; /* Must be 0x1000. */
  2161. LPCSTR szName; /* Pointer to name (in user addr space). */
  2162. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2163. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2164. } THREADNAME_INFO;
  2165. #pragma pack(pop)
  2166. #elif defined(__linux__)
  2167. #include <sys/prctl.h>
  2168. #include <sys/sendfile.h>
  2169. #if defined(ALTERNATIVE_QUEUE)
  2170. #include <sys/eventfd.h>
  2171. #endif /* ALTERNATIVE_QUEUE */
  2172. #if defined(ALTERNATIVE_QUEUE)
  2173. static void *
  2174. event_create(void)
  2175. {
  2176. int evhdl = eventfd(0, EFD_CLOEXEC);
  2177. int *ret;
  2178. if (evhdl == -1) {
  2179. /* Linux uses -1 on error, Windows NULL. */
  2180. /* However, Linux does not return 0 on success either. */
  2181. return 0;
  2182. }
  2183. ret = (int *)mg_malloc(sizeof(int));
  2184. if (ret) {
  2185. *ret = evhdl;
  2186. } else {
  2187. (void)close(evhdl);
  2188. }
  2189. return (void *)ret;
  2190. }
  2191. static int
  2192. event_wait(void *eventhdl)
  2193. {
  2194. uint64_t u;
  2195. int evhdl, s;
  2196. if (!eventhdl) {
  2197. /* error */
  2198. return 0;
  2199. }
  2200. evhdl = *(int *)eventhdl;
  2201. s = (int)read(evhdl, &u, sizeof(u));
  2202. if (s != sizeof(u)) {
  2203. /* error */
  2204. return 0;
  2205. }
  2206. (void)u; /* the value is not required */
  2207. return 1;
  2208. }
  2209. static int
  2210. event_signal(void *eventhdl)
  2211. {
  2212. uint64_t u = 1;
  2213. int evhdl, s;
  2214. if (!eventhdl) {
  2215. /* error */
  2216. return 0;
  2217. }
  2218. evhdl = *(int *)eventhdl;
  2219. s = (int)write(evhdl, &u, sizeof(u));
  2220. if (s != sizeof(u)) {
  2221. /* error */
  2222. return 0;
  2223. }
  2224. return 1;
  2225. }
  2226. static void
  2227. event_destroy(void *eventhdl)
  2228. {
  2229. int evhdl;
  2230. if (!eventhdl) {
  2231. /* error */
  2232. return;
  2233. }
  2234. evhdl = *(int *)eventhdl;
  2235. close(evhdl);
  2236. mg_free(eventhdl);
  2237. }
  2238. #endif
  2239. #endif
  2240. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2241. struct posix_event {
  2242. pthread_mutex_t mutex;
  2243. pthread_cond_t cond;
  2244. int signaled;
  2245. };
  2246. static void *
  2247. event_create(void)
  2248. {
  2249. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2250. if (ret == 0) {
  2251. /* out of memory */
  2252. return 0;
  2253. }
  2254. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2255. /* pthread mutex not available */
  2256. mg_free(ret);
  2257. return 0;
  2258. }
  2259. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2260. /* pthread cond not available */
  2261. pthread_mutex_destroy(&(ret->mutex));
  2262. mg_free(ret);
  2263. return 0;
  2264. }
  2265. ret->signaled = 0;
  2266. return (void *)ret;
  2267. }
  2268. static int
  2269. event_wait(void *eventhdl)
  2270. {
  2271. struct posix_event *ev = (struct posix_event *)eventhdl;
  2272. pthread_mutex_lock(&(ev->mutex));
  2273. while (!ev->signaled) {
  2274. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2275. }
  2276. ev->signaled = 0;
  2277. pthread_mutex_unlock(&(ev->mutex));
  2278. return 1;
  2279. }
  2280. static int
  2281. event_signal(void *eventhdl)
  2282. {
  2283. struct posix_event *ev = (struct posix_event *)eventhdl;
  2284. pthread_mutex_lock(&(ev->mutex));
  2285. pthread_cond_signal(&(ev->cond));
  2286. ev->signaled = 1;
  2287. pthread_mutex_unlock(&(ev->mutex));
  2288. return 1;
  2289. }
  2290. static void
  2291. event_destroy(void *eventhdl)
  2292. {
  2293. struct posix_event *ev = (struct posix_event *)eventhdl;
  2294. pthread_cond_destroy(&(ev->cond));
  2295. pthread_mutex_destroy(&(ev->mutex));
  2296. mg_free(ev);
  2297. }
  2298. #endif
  2299. static void
  2300. mg_set_thread_name(const char *name)
  2301. {
  2302. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2303. mg_snprintf(
  2304. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2305. #if defined(_WIN32)
  2306. #if defined(_MSC_VER)
  2307. /* Windows and Visual Studio Compiler */
  2308. __try {
  2309. THREADNAME_INFO info;
  2310. info.dwType = 0x1000;
  2311. info.szName = threadName;
  2312. info.dwThreadID = ~0U;
  2313. info.dwFlags = 0;
  2314. RaiseException(0x406D1388,
  2315. 0,
  2316. sizeof(info) / sizeof(ULONG_PTR),
  2317. (ULONG_PTR *)&info);
  2318. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2319. }
  2320. #elif defined(__MINGW32__)
  2321. /* No option known to set thread name for MinGW known */
  2322. #endif
  2323. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2324. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2325. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2326. #if defined(__MACH__)
  2327. /* OS X only current thread name can be changed */
  2328. (void)pthread_setname_np(threadName);
  2329. #else
  2330. (void)pthread_setname_np(pthread_self(), threadName);
  2331. #endif
  2332. #elif defined(__linux__)
  2333. /* On Linux we can use the prctl function.
  2334. * When building for Linux Standard Base (LSB) use
  2335. * NO_THREAD_NAME. However, thread names are a big
  2336. * help for debugging, so the stadard is to set them.
  2337. */
  2338. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2339. #endif
  2340. }
  2341. #else /* !defined(NO_THREAD_NAME) */
  2342. void
  2343. mg_set_thread_name(const char *threadName)
  2344. {
  2345. }
  2346. #endif
  2347. const struct mg_option *
  2348. mg_get_valid_options(void)
  2349. {
  2350. return config_options;
  2351. }
  2352. /* Do not open file (unused) */
  2353. #define MG_FOPEN_MODE_NONE (0)
  2354. /* Open file for read only access */
  2355. #define MG_FOPEN_MODE_READ (1)
  2356. /* Open file for writing, create and overwrite */
  2357. #define MG_FOPEN_MODE_WRITE (2)
  2358. /* Open file for writing, create and append */
  2359. #define MG_FOPEN_MODE_APPEND (4)
  2360. static int
  2361. is_file_opened(const struct mg_file_access *fileacc)
  2362. {
  2363. if (!fileacc) {
  2364. return 0;
  2365. }
  2366. return (fileacc->fp != NULL);
  2367. }
  2368. #if !defined(NO_FILESYSTEMS)
  2369. static int mg_stat(const struct mg_connection *conn,
  2370. const char *path,
  2371. struct mg_file_stat *filep);
  2372. /* Reject files with special characters (for Windows) */
  2373. static int
  2374. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2375. {
  2376. const uint8_t *c = (const uint8_t *)path;
  2377. (void)conn; /* not used */
  2378. if ((c == NULL) || (c[0] == 0)) {
  2379. /* Null pointer or empty path --> suspicious */
  2380. return 1;
  2381. }
  2382. #if defined(_WIN32)
  2383. while (*c) {
  2384. if (*c < 32) {
  2385. /* Control character */
  2386. return 1;
  2387. }
  2388. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2389. /* stdin/stdout redirection character */
  2390. return 1;
  2391. }
  2392. if ((*c == '*') || (*c == '?')) {
  2393. /* Wildcard character */
  2394. return 1;
  2395. }
  2396. if (*c == '"') {
  2397. /* Windows quotation */
  2398. return 1;
  2399. }
  2400. c++;
  2401. }
  2402. #endif
  2403. /* Nothing suspicious found */
  2404. return 0;
  2405. }
  2406. /* mg_fopen will open a file either in memory or on the disk.
  2407. * The input parameter path is a string in UTF-8 encoding.
  2408. * The input parameter mode is MG_FOPEN_MODE_*
  2409. * On success, fp will be set in the output struct mg_file.
  2410. * All status members will also be set.
  2411. * The function returns 1 on success, 0 on error. */
  2412. static int
  2413. mg_fopen(const struct mg_connection *conn,
  2414. const char *path,
  2415. int mode,
  2416. struct mg_file *filep)
  2417. {
  2418. int found;
  2419. if (!filep) {
  2420. return 0;
  2421. }
  2422. filep->access.fp = NULL;
  2423. if (mg_path_suspicious(conn, path)) {
  2424. return 0;
  2425. }
  2426. /* filep is initialized in mg_stat: all fields with memset to,
  2427. * some fields like size and modification date with values */
  2428. found = mg_stat(conn, path, &(filep->stat));
  2429. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2430. /* file does not exist and will not be created */
  2431. return 0;
  2432. }
  2433. #if defined(_WIN32)
  2434. {
  2435. wchar_t wbuf[UTF16_PATH_MAX];
  2436. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2437. switch (mode) {
  2438. case MG_FOPEN_MODE_READ:
  2439. filep->access.fp = _wfopen(wbuf, L"rb");
  2440. break;
  2441. case MG_FOPEN_MODE_WRITE:
  2442. filep->access.fp = _wfopen(wbuf, L"wb");
  2443. break;
  2444. case MG_FOPEN_MODE_APPEND:
  2445. filep->access.fp = _wfopen(wbuf, L"ab");
  2446. break;
  2447. }
  2448. }
  2449. #else
  2450. /* Linux et al already use unicode. No need to convert. */
  2451. switch (mode) {
  2452. case MG_FOPEN_MODE_READ:
  2453. filep->access.fp = fopen(path, "r");
  2454. break;
  2455. case MG_FOPEN_MODE_WRITE:
  2456. filep->access.fp = fopen(path, "w");
  2457. break;
  2458. case MG_FOPEN_MODE_APPEND:
  2459. filep->access.fp = fopen(path, "a");
  2460. break;
  2461. }
  2462. #endif
  2463. if (!found) {
  2464. /* File did not exist before fopen was called.
  2465. * Maybe it has been created now. Get stat info
  2466. * like creation time now. */
  2467. found = mg_stat(conn, path, &(filep->stat));
  2468. (void)found;
  2469. }
  2470. /* return OK if file is opened */
  2471. return (filep->access.fp != NULL);
  2472. }
  2473. /* return 0 on success, just like fclose */
  2474. static int
  2475. mg_fclose(struct mg_file_access *fileacc)
  2476. {
  2477. int ret = -1;
  2478. if (fileacc != NULL) {
  2479. if (fileacc->fp != NULL) {
  2480. ret = fclose(fileacc->fp);
  2481. }
  2482. /* reset all members of fileacc */
  2483. memset(fileacc, 0, sizeof(*fileacc));
  2484. }
  2485. return ret;
  2486. }
  2487. #endif /* NO_FILESYSTEMS */
  2488. static void
  2489. mg_strlcpy(char *dst, const char *src, size_t n)
  2490. {
  2491. for (; *src != '\0' && n > 1; n--) {
  2492. *dst++ = *src++;
  2493. }
  2494. *dst = '\0';
  2495. }
  2496. static int
  2497. lowercase(const char *s)
  2498. {
  2499. return tolower((unsigned char)*s);
  2500. }
  2501. int
  2502. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2503. {
  2504. int diff = 0;
  2505. if (len > 0) {
  2506. do {
  2507. diff = lowercase(s1++) - lowercase(s2++);
  2508. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2509. }
  2510. return diff;
  2511. }
  2512. int
  2513. mg_strcasecmp(const char *s1, const char *s2)
  2514. {
  2515. int diff;
  2516. do {
  2517. diff = lowercase(s1++) - lowercase(s2++);
  2518. } while (diff == 0 && s1[-1] != '\0');
  2519. return diff;
  2520. }
  2521. static char *
  2522. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2523. {
  2524. char *p;
  2525. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2526. * defined */
  2527. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2528. mg_strlcpy(p, ptr, len + 1);
  2529. }
  2530. return p;
  2531. }
  2532. static char *
  2533. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2534. {
  2535. return mg_strndup_ctx(str, strlen(str), ctx);
  2536. }
  2537. static char *
  2538. mg_strdup(const char *str)
  2539. {
  2540. return mg_strndup_ctx(str, strlen(str), NULL);
  2541. }
  2542. static const char *
  2543. mg_strcasestr(const char *big_str, const char *small_str)
  2544. {
  2545. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2546. if (big_len >= small_len) {
  2547. for (i = 0; i <= (big_len - small_len); i++) {
  2548. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2549. return big_str + i;
  2550. }
  2551. }
  2552. }
  2553. return NULL;
  2554. }
  2555. /* Return null terminated string of given maximum length.
  2556. * Report errors if length is exceeded. */
  2557. static void
  2558. mg_vsnprintf(const struct mg_connection *conn,
  2559. int *truncated,
  2560. char *buf,
  2561. size_t buflen,
  2562. const char *fmt,
  2563. va_list ap)
  2564. {
  2565. int n, ok;
  2566. if (buflen == 0) {
  2567. if (truncated) {
  2568. *truncated = 1;
  2569. }
  2570. return;
  2571. }
  2572. #if defined(__clang__)
  2573. #pragma clang diagnostic push
  2574. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2575. /* Using fmt as a non-literal is intended here, since it is mostly called
  2576. * indirectly by mg_snprintf */
  2577. #endif
  2578. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2579. ok = (n >= 0) && ((size_t)n < buflen);
  2580. #if defined(__clang__)
  2581. #pragma clang diagnostic pop
  2582. #endif
  2583. if (ok) {
  2584. if (truncated) {
  2585. *truncated = 0;
  2586. }
  2587. } else {
  2588. if (truncated) {
  2589. *truncated = 1;
  2590. }
  2591. mg_cry_internal(conn,
  2592. "truncating vsnprintf buffer: [%.*s]",
  2593. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2594. buf);
  2595. n = (int)buflen - 1;
  2596. }
  2597. buf[n] = '\0';
  2598. }
  2599. static void
  2600. mg_snprintf(const struct mg_connection *conn,
  2601. int *truncated,
  2602. char *buf,
  2603. size_t buflen,
  2604. const char *fmt,
  2605. ...)
  2606. {
  2607. va_list ap;
  2608. va_start(ap, fmt);
  2609. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2610. va_end(ap);
  2611. }
  2612. static int
  2613. get_option_index(const char *name)
  2614. {
  2615. int i;
  2616. for (i = 0; config_options[i].name != NULL; i++) {
  2617. if (strcmp(config_options[i].name, name) == 0) {
  2618. return i;
  2619. }
  2620. }
  2621. return -1;
  2622. }
  2623. const char *
  2624. mg_get_option(const struct mg_context *ctx, const char *name)
  2625. {
  2626. int i;
  2627. if ((i = get_option_index(name)) == -1) {
  2628. return NULL;
  2629. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2630. return "";
  2631. } else {
  2632. return ctx->dd.config[i];
  2633. }
  2634. }
  2635. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2636. struct mg_context *
  2637. mg_get_context(const struct mg_connection *conn)
  2638. {
  2639. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2640. }
  2641. void *
  2642. mg_get_user_data(const struct mg_context *ctx)
  2643. {
  2644. return (ctx == NULL) ? NULL : ctx->user_data;
  2645. }
  2646. void *
  2647. mg_get_user_context_data(const struct mg_connection *conn)
  2648. {
  2649. return mg_get_user_data(mg_get_context(conn));
  2650. }
  2651. void *
  2652. mg_get_thread_pointer(const struct mg_connection *conn)
  2653. {
  2654. /* both methods should return the same pointer */
  2655. if (conn) {
  2656. /* quick access, in case conn is known */
  2657. return conn->tls_user_ptr;
  2658. } else {
  2659. /* otherwise get pointer from thread local storage (TLS) */
  2660. struct mg_workerTLS *tls =
  2661. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2662. return tls->user_ptr;
  2663. }
  2664. }
  2665. void
  2666. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2667. {
  2668. if (const_conn != NULL) {
  2669. /* Const cast, since "const struct mg_connection *" does not mean
  2670. * the connection object is not modified. Here "const" is used,
  2671. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2672. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2673. conn->request_info.conn_data = data;
  2674. }
  2675. }
  2676. void *
  2677. mg_get_user_connection_data(const struct mg_connection *conn)
  2678. {
  2679. if (conn != NULL) {
  2680. return conn->request_info.conn_data;
  2681. }
  2682. return NULL;
  2683. }
  2684. int
  2685. mg_get_server_ports(const struct mg_context *ctx,
  2686. int size,
  2687. struct mg_server_port *ports)
  2688. {
  2689. int i, cnt = 0;
  2690. if (size <= 0) {
  2691. return -1;
  2692. }
  2693. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2694. if (!ctx) {
  2695. return -1;
  2696. }
  2697. if (!ctx->listening_sockets) {
  2698. return -1;
  2699. }
  2700. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2701. ports[cnt].port =
  2702. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2703. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2704. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2705. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2706. /* IPv4 */
  2707. ports[cnt].protocol = 1;
  2708. cnt++;
  2709. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2710. /* IPv6 */
  2711. ports[cnt].protocol = 3;
  2712. cnt++;
  2713. }
  2714. }
  2715. return cnt;
  2716. }
  2717. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2718. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2719. #endif
  2720. static void
  2721. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2722. {
  2723. buf[0] = '\0';
  2724. if (!usa) {
  2725. return;
  2726. }
  2727. if (usa->sa.sa_family == AF_INET) {
  2728. getnameinfo(&usa->sa,
  2729. sizeof(usa->sin),
  2730. buf,
  2731. (unsigned)len,
  2732. NULL,
  2733. 0,
  2734. NI_NUMERICHOST);
  2735. }
  2736. #if defined(USE_IPV6)
  2737. else if (usa->sa.sa_family == AF_INET6) {
  2738. getnameinfo(&usa->sa,
  2739. sizeof(usa->sin6),
  2740. buf,
  2741. (unsigned)len,
  2742. NULL,
  2743. 0,
  2744. NI_NUMERICHOST);
  2745. }
  2746. #endif
  2747. #if defined(USE_X_DOM_SOCKET)
  2748. else if (usa->sa.sa_family == AF_UNIX) {
  2749. /* TODO: Define a remote address for unix domain sockets.
  2750. * This code will always return "localhost", identical to http+tcp:
  2751. getnameinfo(&usa->sa,
  2752. sizeof(usa->sun),
  2753. buf,
  2754. (unsigned)len,
  2755. NULL,
  2756. 0,
  2757. NI_NUMERICHOST);
  2758. */
  2759. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2760. buf[len] = 0;
  2761. }
  2762. #endif
  2763. }
  2764. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2765. * included in all responses other than 100, 101, 5xx. */
  2766. static void
  2767. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2768. {
  2769. #if !defined(REENTRANT_TIME)
  2770. struct tm *tm;
  2771. tm = ((t != NULL) ? gmtime(t) : NULL);
  2772. if (tm != NULL) {
  2773. #else
  2774. struct tm _tm;
  2775. struct tm *tm = &_tm;
  2776. if (t != NULL) {
  2777. gmtime_r(t, tm);
  2778. #endif
  2779. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2780. } else {
  2781. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2782. buf[buf_len - 1] = '\0';
  2783. }
  2784. }
  2785. /* difftime for struct timespec. Return value is in seconds. */
  2786. static double
  2787. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2788. {
  2789. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2790. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2791. }
  2792. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2793. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2794. const char *func,
  2795. unsigned line,
  2796. const char *fmt,
  2797. va_list ap);
  2798. #include "external_mg_cry_internal_impl.inl"
  2799. #elif !defined(NO_FILESYSTEMS)
  2800. /* Print error message to the opened error log stream. */
  2801. static void
  2802. mg_cry_internal_impl(const struct mg_connection *conn,
  2803. const char *func,
  2804. unsigned line,
  2805. const char *fmt,
  2806. va_list ap)
  2807. {
  2808. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2809. struct mg_file fi;
  2810. time_t timestamp;
  2811. /* Unused, in the RELEASE build */
  2812. (void)func;
  2813. (void)line;
  2814. #if defined(GCC_DIAGNOSTIC)
  2815. #pragma GCC diagnostic push
  2816. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2817. #endif
  2818. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2819. #if defined(GCC_DIAGNOSTIC)
  2820. #pragma GCC diagnostic pop
  2821. #endif
  2822. buf[sizeof(buf) - 1] = 0;
  2823. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2824. if (!conn) {
  2825. puts(buf);
  2826. return;
  2827. }
  2828. /* Do not lock when getting the callback value, here and below.
  2829. * I suppose this is fine, since function cannot disappear in the
  2830. * same way string option can. */
  2831. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2832. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2833. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2834. if (mg_fopen(conn,
  2835. conn->dom_ctx->config[ERROR_LOG_FILE],
  2836. MG_FOPEN_MODE_APPEND,
  2837. &fi)
  2838. == 0) {
  2839. fi.access.fp = NULL;
  2840. }
  2841. } else {
  2842. fi.access.fp = NULL;
  2843. }
  2844. if (fi.access.fp != NULL) {
  2845. flockfile(fi.access.fp);
  2846. timestamp = time(NULL);
  2847. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2848. fprintf(fi.access.fp,
  2849. "[%010lu] [error] [client %s] ",
  2850. (unsigned long)timestamp,
  2851. src_addr);
  2852. if (conn->request_info.request_method != NULL) {
  2853. fprintf(fi.access.fp,
  2854. "%s %s: ",
  2855. conn->request_info.request_method,
  2856. conn->request_info.request_uri
  2857. ? conn->request_info.request_uri
  2858. : "");
  2859. }
  2860. fprintf(fi.access.fp, "%s", buf);
  2861. fputc('\n', fi.access.fp);
  2862. fflush(fi.access.fp);
  2863. funlockfile(fi.access.fp);
  2864. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2865. * mg_cry here anyway ;-) */
  2866. }
  2867. }
  2868. }
  2869. #else
  2870. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2871. #endif /* Externally provided function */
  2872. /* Construct fake connection structure. Used for logging, if connection
  2873. * is not applicable at the moment of logging. */
  2874. static struct mg_connection *
  2875. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2876. {
  2877. static const struct mg_connection conn_zero = {0};
  2878. *fc = conn_zero;
  2879. fc->phys_ctx = ctx;
  2880. fc->dom_ctx = &(ctx->dd);
  2881. return fc;
  2882. }
  2883. static void
  2884. mg_cry_internal_wrap(const struct mg_connection *conn,
  2885. struct mg_context *ctx,
  2886. const char *func,
  2887. unsigned line,
  2888. const char *fmt,
  2889. ...)
  2890. {
  2891. va_list ap;
  2892. va_start(ap, fmt);
  2893. if (!conn && ctx) {
  2894. struct mg_connection fc;
  2895. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2896. } else {
  2897. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2898. }
  2899. va_end(ap);
  2900. }
  2901. void
  2902. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2903. {
  2904. va_list ap;
  2905. va_start(ap, fmt);
  2906. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2907. va_end(ap);
  2908. }
  2909. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2910. const char *
  2911. mg_version(void)
  2912. {
  2913. return CIVETWEB_VERSION;
  2914. }
  2915. const struct mg_request_info *
  2916. mg_get_request_info(const struct mg_connection *conn)
  2917. {
  2918. if (!conn) {
  2919. return NULL;
  2920. }
  2921. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2922. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2923. char txt[16];
  2924. struct mg_workerTLS *tls =
  2925. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2926. sprintf(txt, "%03i", conn->response_info.status_code);
  2927. if (strlen(txt) == 3) {
  2928. memcpy(tls->txtbuf, txt, 4);
  2929. } else {
  2930. strcpy(tls->txtbuf, "ERR");
  2931. }
  2932. ((struct mg_connection *)conn)->request_info.local_uri =
  2933. tls->txtbuf; /* use thread safe buffer */
  2934. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2935. tls->txtbuf; /* use the same thread safe buffer */
  2936. ((struct mg_connection *)conn)->request_info.request_uri =
  2937. tls->txtbuf; /* use the same thread safe buffer */
  2938. ((struct mg_connection *)conn)->request_info.num_headers =
  2939. conn->response_info.num_headers;
  2940. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2941. conn->response_info.http_headers,
  2942. sizeof(conn->response_info.http_headers));
  2943. } else
  2944. #endif
  2945. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2946. return NULL;
  2947. }
  2948. return &conn->request_info;
  2949. }
  2950. const struct mg_response_info *
  2951. mg_get_response_info(const struct mg_connection *conn)
  2952. {
  2953. if (!conn) {
  2954. return NULL;
  2955. }
  2956. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2957. return NULL;
  2958. }
  2959. return &conn->response_info;
  2960. }
  2961. static const char *
  2962. get_proto_name(const struct mg_connection *conn)
  2963. {
  2964. #if defined(__clang__)
  2965. #pragma clang diagnostic push
  2966. #pragma clang diagnostic ignored "-Wunreachable-code"
  2967. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2968. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2969. * unreachable, but splitting into four different #ifdef clauses here is
  2970. * more complicated.
  2971. */
  2972. #endif
  2973. const struct mg_request_info *ri = &conn->request_info;
  2974. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2975. ? (ri->is_ssl ? "wss" : "ws")
  2976. : (ri->is_ssl ? "https" : "http"));
  2977. return proto;
  2978. #if defined(__clang__)
  2979. #pragma clang diagnostic pop
  2980. #endif
  2981. }
  2982. static int
  2983. mg_construct_local_link(const struct mg_connection *conn,
  2984. char *buf,
  2985. size_t buflen,
  2986. const char *define_proto,
  2987. int define_port,
  2988. const char *define_uri)
  2989. {
  2990. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2991. return -1;
  2992. } else {
  2993. int truncated = 0;
  2994. const struct mg_request_info *ri = &conn->request_info;
  2995. const char *proto =
  2996. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  2997. const char *uri =
  2998. (define_uri != NULL)
  2999. ? define_uri
  3000. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3001. int port = (define_port > 0) ? define_port : ri->server_port;
  3002. int default_port = 80;
  3003. if (uri == NULL) {
  3004. return -1;
  3005. }
  3006. #if defined(USE_X_DOM_SOCKET)
  3007. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3008. /* TODO: Define and document a link for UNIX domain sockets. */
  3009. /* There seems to be no official standard for this.
  3010. * Common uses seem to be "httpunix://", "http.unix://" or
  3011. * "http+unix://" as a protocol definition string, followed by
  3012. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3013. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3014. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3015. * "" (completely skipping the server name part). In any case, the
  3016. * last part is the server local path. */
  3017. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3018. mg_snprintf(conn,
  3019. &truncated,
  3020. buf,
  3021. buflen,
  3022. "%s.unix://%s%s",
  3023. proto,
  3024. server_name,
  3025. ri->local_uri);
  3026. default_port = 0;
  3027. return 0;
  3028. }
  3029. #endif
  3030. if (define_proto) {
  3031. /* If we got a protocol name, use the default port accordingly. */
  3032. if ((0 == strcmp(define_proto, "https"))
  3033. || (0 == strcmp(define_proto, "wss"))) {
  3034. default_port = 443;
  3035. }
  3036. } else if (ri->is_ssl) {
  3037. /* If we did not get a protocol name, use TLS as default if it is
  3038. * already used. */
  3039. default_port = 443;
  3040. }
  3041. {
  3042. #if defined(USE_IPV6)
  3043. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3044. #endif
  3045. int auth_domain_check_enabled =
  3046. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3047. && (!mg_strcasecmp(
  3048. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3049. const char *server_domain =
  3050. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3051. char portstr[16];
  3052. char server_ip[48];
  3053. if (port != default_port) {
  3054. sprintf(portstr, ":%u", (unsigned)port);
  3055. } else {
  3056. portstr[0] = 0;
  3057. }
  3058. if (!auth_domain_check_enabled || !server_domain) {
  3059. sockaddr_to_string(server_ip,
  3060. sizeof(server_ip),
  3061. &conn->client.lsa);
  3062. server_domain = server_ip;
  3063. }
  3064. mg_snprintf(conn,
  3065. &truncated,
  3066. buf,
  3067. buflen,
  3068. #if defined(USE_IPV6)
  3069. "%s://%s%s%s%s%s",
  3070. proto,
  3071. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3072. server_domain,
  3073. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3074. #else
  3075. "%s://%s%s%s",
  3076. proto,
  3077. server_domain,
  3078. #endif
  3079. portstr,
  3080. ri->local_uri);
  3081. if (truncated) {
  3082. return -1;
  3083. }
  3084. return 0;
  3085. }
  3086. }
  3087. }
  3088. int
  3089. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3090. {
  3091. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3092. }
  3093. /* Skip the characters until one of the delimiters characters found.
  3094. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3095. * Advance pointer to buffer to the next word. Return found 0-terminated
  3096. * word.
  3097. * Delimiters can be quoted with quotechar. */
  3098. static char *
  3099. skip_quoted(char **buf,
  3100. const char *delimiters,
  3101. const char *whitespace,
  3102. char quotechar)
  3103. {
  3104. char *p, *begin_word, *end_word, *end_whitespace;
  3105. begin_word = *buf;
  3106. end_word = begin_word + strcspn(begin_word, delimiters);
  3107. /* Check for quotechar */
  3108. if (end_word > begin_word) {
  3109. p = end_word - 1;
  3110. while (*p == quotechar) {
  3111. /* While the delimiter is quoted, look for the next delimiter.
  3112. */
  3113. /* This happens, e.g., in calls from parse_auth_header,
  3114. * if the user name contains a " character. */
  3115. /* If there is anything beyond end_word, copy it. */
  3116. if (*end_word != '\0') {
  3117. size_t end_off = strcspn(end_word + 1, delimiters);
  3118. memmove(p, end_word, end_off + 1);
  3119. p += end_off; /* p must correspond to end_word - 1 */
  3120. end_word += end_off + 1;
  3121. } else {
  3122. *p = '\0';
  3123. break;
  3124. }
  3125. }
  3126. for (p++; p < end_word; p++) {
  3127. *p = '\0';
  3128. }
  3129. }
  3130. if (*end_word == '\0') {
  3131. *buf = end_word;
  3132. } else {
  3133. #if defined(GCC_DIAGNOSTIC)
  3134. /* Disable spurious conversion warning for GCC */
  3135. #pragma GCC diagnostic push
  3136. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3137. #endif /* defined(GCC_DIAGNOSTIC) */
  3138. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3139. #if defined(GCC_DIAGNOSTIC)
  3140. #pragma GCC diagnostic pop
  3141. #endif /* defined(GCC_DIAGNOSTIC) */
  3142. for (p = end_word; p < end_whitespace; p++) {
  3143. *p = '\0';
  3144. }
  3145. *buf = end_whitespace;
  3146. }
  3147. return begin_word;
  3148. }
  3149. /* Return HTTP header value, or NULL if not found. */
  3150. static const char *
  3151. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3152. {
  3153. int i;
  3154. for (i = 0; i < num_hdr; i++) {
  3155. if (!mg_strcasecmp(name, hdr[i].name)) {
  3156. return hdr[i].value;
  3157. }
  3158. }
  3159. return NULL;
  3160. }
  3161. #if defined(USE_WEBSOCKET)
  3162. /* Retrieve requested HTTP header multiple values, and return the number of
  3163. * found occurrences */
  3164. static int
  3165. get_req_headers(const struct mg_request_info *ri,
  3166. const char *name,
  3167. const char **output,
  3168. int output_max_size)
  3169. {
  3170. int i;
  3171. int cnt = 0;
  3172. if (ri) {
  3173. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3174. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3175. output[cnt++] = ri->http_headers[i].value;
  3176. }
  3177. }
  3178. }
  3179. return cnt;
  3180. }
  3181. #endif
  3182. const char *
  3183. mg_get_header(const struct mg_connection *conn, const char *name)
  3184. {
  3185. if (!conn) {
  3186. return NULL;
  3187. }
  3188. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3189. return get_header(conn->request_info.http_headers,
  3190. conn->request_info.num_headers,
  3191. name);
  3192. }
  3193. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3194. return get_header(conn->response_info.http_headers,
  3195. conn->response_info.num_headers,
  3196. name);
  3197. }
  3198. return NULL;
  3199. }
  3200. static const char *
  3201. get_http_version(const struct mg_connection *conn)
  3202. {
  3203. if (!conn) {
  3204. return NULL;
  3205. }
  3206. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3207. return conn->request_info.http_version;
  3208. }
  3209. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3210. return conn->response_info.http_version;
  3211. }
  3212. return NULL;
  3213. }
  3214. /* A helper function for traversing a comma separated list of values.
  3215. * It returns a list pointer shifted to the next value, or NULL if the end
  3216. * of the list found.
  3217. * Value is stored in val vector. If value has form "x=y", then eq_val
  3218. * vector is initialized to point to the "y" part, and val vector length
  3219. * is adjusted to point only to "x". */
  3220. static const char *
  3221. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3222. {
  3223. int end;
  3224. reparse:
  3225. if (val == NULL || list == NULL || *list == '\0') {
  3226. /* End of the list */
  3227. return NULL;
  3228. }
  3229. /* Skip over leading LWS */
  3230. while (*list == ' ' || *list == '\t')
  3231. list++;
  3232. val->ptr = list;
  3233. if ((list = strchr(val->ptr, ',')) != NULL) {
  3234. /* Comma found. Store length and shift the list ptr */
  3235. val->len = ((size_t)(list - val->ptr));
  3236. list++;
  3237. } else {
  3238. /* This value is the last one */
  3239. list = val->ptr + strlen(val->ptr);
  3240. val->len = ((size_t)(list - val->ptr));
  3241. }
  3242. /* Adjust length for trailing LWS */
  3243. end = (int)val->len - 1;
  3244. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3245. end--;
  3246. val->len = (size_t)(end) + (size_t)(1);
  3247. if (val->len == 0) {
  3248. /* Ignore any empty entries. */
  3249. goto reparse;
  3250. }
  3251. if (eq_val != NULL) {
  3252. /* Value has form "x=y", adjust pointers and lengths
  3253. * so that val points to "x", and eq_val points to "y". */
  3254. eq_val->len = 0;
  3255. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3256. if (eq_val->ptr != NULL) {
  3257. eq_val->ptr++; /* Skip over '=' character */
  3258. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3259. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3260. }
  3261. }
  3262. return list;
  3263. }
  3264. /* A helper function for checking if a comma separated list of values
  3265. * contains
  3266. * the given option (case insensitvely).
  3267. * 'header' can be NULL, in which case false is returned. */
  3268. static int
  3269. header_has_option(const char *header, const char *option)
  3270. {
  3271. struct vec opt_vec;
  3272. struct vec eq_vec;
  3273. DEBUG_ASSERT(option != NULL);
  3274. DEBUG_ASSERT(option[0] != '\0');
  3275. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3276. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3277. return 1;
  3278. }
  3279. return 0;
  3280. }
  3281. /* Perform case-insensitive match of string against pattern */
  3282. static ptrdiff_t
  3283. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3284. {
  3285. const char *or_str;
  3286. ptrdiff_t i, j, len, res;
  3287. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3288. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3289. return (res > 0) ? res
  3290. : match_prefix(or_str + 1,
  3291. (size_t)((pattern + pattern_len)
  3292. - (or_str + 1)),
  3293. str);
  3294. }
  3295. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3296. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3297. continue;
  3298. } else if (pattern[i] == '$') {
  3299. return (str[j] == '\0') ? j : -1;
  3300. } else if (pattern[i] == '*') {
  3301. i++;
  3302. if (pattern[i] == '*') {
  3303. i++;
  3304. len = (ptrdiff_t)strlen(str + j);
  3305. } else {
  3306. len = (ptrdiff_t)strcspn(str + j, "/");
  3307. }
  3308. if (i == (ptrdiff_t)pattern_len) {
  3309. return j + len;
  3310. }
  3311. do {
  3312. res = match_prefix(pattern + i,
  3313. (pattern_len - (size_t)i),
  3314. str + j + len);
  3315. } while (res == -1 && len-- > 0);
  3316. return (res == -1) ? -1 : j + res + len;
  3317. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3318. return -1;
  3319. }
  3320. }
  3321. return (ptrdiff_t)j;
  3322. }
  3323. static ptrdiff_t
  3324. match_prefix_strlen(const char *pattern, const char *str)
  3325. {
  3326. if (pattern == NULL) {
  3327. return -1;
  3328. }
  3329. return match_prefix(pattern, strlen(pattern), str);
  3330. }
  3331. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3332. * This function must tolerate situations when connection info is not
  3333. * set up, for example if request parsing failed. */
  3334. static int
  3335. should_keep_alive(const struct mg_connection *conn)
  3336. {
  3337. const char *http_version;
  3338. const char *header;
  3339. /* First satisfy needs of the server */
  3340. if ((conn == NULL) || conn->must_close) {
  3341. /* Close, if civetweb framework needs to close */
  3342. return 0;
  3343. }
  3344. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3345. /* Close, if keep alive is not enabled */
  3346. return 0;
  3347. }
  3348. /* Check explicit wish of the client */
  3349. header = mg_get_header(conn, "Connection");
  3350. if (header) {
  3351. /* If there is a connection header from the client, obey */
  3352. if (header_has_option(header, "keep-alive")) {
  3353. return 1;
  3354. }
  3355. return 0;
  3356. }
  3357. /* Use default of the standard */
  3358. http_version = get_http_version(conn);
  3359. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3360. /* HTTP 1.1 default is keep alive */
  3361. return 1;
  3362. }
  3363. /* HTTP 1.0 (and earlier) default is to close the connection */
  3364. return 0;
  3365. }
  3366. static int
  3367. should_decode_url(const struct mg_connection *conn)
  3368. {
  3369. if (!conn || !conn->dom_ctx) {
  3370. return 0;
  3371. }
  3372. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3373. }
  3374. static int
  3375. should_decode_query_string(const struct mg_connection *conn)
  3376. {
  3377. if (!conn || !conn->dom_ctx) {
  3378. return 0;
  3379. }
  3380. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3381. == 0);
  3382. }
  3383. static const char *
  3384. suggest_connection_header(const struct mg_connection *conn)
  3385. {
  3386. return should_keep_alive(conn) ? "keep-alive" : "close";
  3387. }
  3388. #include "response.inl"
  3389. static void
  3390. send_no_cache_header(struct mg_connection *conn)
  3391. {
  3392. /* Send all current and obsolete cache opt-out directives. */
  3393. mg_response_header_add(conn,
  3394. "Cache-Control",
  3395. "no-cache, no-store, "
  3396. "must-revalidate, private, max-age=0",
  3397. -1);
  3398. mg_response_header_add(conn, "Expires", "0", -1);
  3399. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3400. /* Obsolete, but still send it for HTTP/1.0 */
  3401. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3402. }
  3403. }
  3404. static void
  3405. send_static_cache_header(struct mg_connection *conn)
  3406. {
  3407. #if !defined(NO_CACHING)
  3408. int max_age;
  3409. char val[64];
  3410. const char *cache_control =
  3411. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3412. /* If there is a full cache-control option configured,0 use it */
  3413. if (cache_control != NULL) {
  3414. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3415. return;
  3416. }
  3417. /* Read the server config to check how long a file may be cached.
  3418. * The configuration is in seconds. */
  3419. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3420. if (max_age <= 0) {
  3421. /* 0 means "do not cache". All values <0 are reserved
  3422. * and may be used differently in the future. */
  3423. /* If a file should not be cached, do not only send
  3424. * max-age=0, but also pragmas and Expires headers. */
  3425. send_no_cache_header(conn);
  3426. return;
  3427. }
  3428. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3429. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3430. /* See also https://www.mnot.net/cache_docs/ */
  3431. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3432. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3433. * leap
  3434. * year to 31622400 seconds. For the moment, we just send whatever has
  3435. * been configured, still the behavior for >1 year should be considered
  3436. * as undefined. */
  3437. mg_snprintf(
  3438. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3439. mg_response_header_add(conn, "Cache-Control", val, -1);
  3440. #else /* NO_CACHING */
  3441. send_no_cache_header(conn);
  3442. #endif /* !NO_CACHING */
  3443. }
  3444. static void
  3445. send_additional_header(struct mg_connection *conn)
  3446. {
  3447. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3448. #if !defined(NO_SSL)
  3449. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3450. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3451. if (max_age >= 0) {
  3452. char val[64];
  3453. mg_snprintf(conn,
  3454. NULL,
  3455. val,
  3456. sizeof(val),
  3457. "max-age=%lu",
  3458. (unsigned long)max_age);
  3459. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3460. }
  3461. }
  3462. #endif
  3463. if (header && header[0]) {
  3464. mg_response_header_add_lines(conn, header);
  3465. }
  3466. }
  3467. #if !defined(NO_FILESYSTEMS)
  3468. static void handle_file_based_request(struct mg_connection *conn,
  3469. const char *path,
  3470. struct mg_file *filep);
  3471. #endif /* NO_FILESYSTEMS */
  3472. const char *
  3473. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3474. {
  3475. /* See IANA HTTP status code assignment:
  3476. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3477. */
  3478. switch (response_code) {
  3479. /* RFC2616 Section 10.1 - Informational 1xx */
  3480. case 100:
  3481. return "Continue"; /* RFC2616 Section 10.1.1 */
  3482. case 101:
  3483. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3484. case 102:
  3485. return "Processing"; /* RFC2518 Section 10.1 */
  3486. /* RFC2616 Section 10.2 - Successful 2xx */
  3487. case 200:
  3488. return "OK"; /* RFC2616 Section 10.2.1 */
  3489. case 201:
  3490. return "Created"; /* RFC2616 Section 10.2.2 */
  3491. case 202:
  3492. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3493. case 203:
  3494. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3495. case 204:
  3496. return "No Content"; /* RFC2616 Section 10.2.5 */
  3497. case 205:
  3498. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3499. case 206:
  3500. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3501. case 207:
  3502. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3503. */
  3504. case 208:
  3505. return "Already Reported"; /* RFC5842 Section 7.1 */
  3506. case 226:
  3507. return "IM used"; /* RFC3229 Section 10.4.1 */
  3508. /* RFC2616 Section 10.3 - Redirection 3xx */
  3509. case 300:
  3510. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3511. case 301:
  3512. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3513. case 302:
  3514. return "Found"; /* RFC2616 Section 10.3.3 */
  3515. case 303:
  3516. return "See Other"; /* RFC2616 Section 10.3.4 */
  3517. case 304:
  3518. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3519. case 305:
  3520. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3521. case 307:
  3522. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3523. case 308:
  3524. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3525. /* RFC2616 Section 10.4 - Client Error 4xx */
  3526. case 400:
  3527. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3528. case 401:
  3529. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3530. case 402:
  3531. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3532. case 403:
  3533. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3534. case 404:
  3535. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3536. case 405:
  3537. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3538. case 406:
  3539. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3540. case 407:
  3541. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3542. case 408:
  3543. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3544. case 409:
  3545. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3546. case 410:
  3547. return "Gone"; /* RFC2616 Section 10.4.11 */
  3548. case 411:
  3549. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3550. case 412:
  3551. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3552. case 413:
  3553. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3554. case 414:
  3555. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3556. case 415:
  3557. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3558. case 416:
  3559. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3560. */
  3561. case 417:
  3562. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3563. case 421:
  3564. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3565. case 422:
  3566. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3567. * Section 11.2 */
  3568. case 423:
  3569. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3570. case 424:
  3571. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3572. * Section 11.4 */
  3573. case 426:
  3574. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3575. case 428:
  3576. return "Precondition Required"; /* RFC 6585, Section 3 */
  3577. case 429:
  3578. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3579. case 431:
  3580. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3581. case 451:
  3582. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3583. * Section 3 */
  3584. /* RFC2616 Section 10.5 - Server Error 5xx */
  3585. case 500:
  3586. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3587. case 501:
  3588. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3589. case 502:
  3590. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3591. case 503:
  3592. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3593. case 504:
  3594. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3595. case 505:
  3596. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3597. case 506:
  3598. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3599. case 507:
  3600. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3601. * Section 11.5 */
  3602. case 508:
  3603. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3604. case 510:
  3605. return "Not Extended"; /* RFC 2774, Section 7 */
  3606. case 511:
  3607. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3608. /* Other status codes, not shown in the IANA HTTP status code
  3609. * assignment.
  3610. * E.g., "de facto" standards due to common use, ... */
  3611. case 418:
  3612. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3613. case 419:
  3614. return "Authentication Timeout"; /* common use */
  3615. case 420:
  3616. return "Enhance Your Calm"; /* common use */
  3617. case 440:
  3618. return "Login Timeout"; /* common use */
  3619. case 509:
  3620. return "Bandwidth Limit Exceeded"; /* common use */
  3621. default:
  3622. /* This error code is unknown. This should not happen. */
  3623. if (conn) {
  3624. mg_cry_internal(conn,
  3625. "Unknown HTTP response code: %u",
  3626. response_code);
  3627. }
  3628. /* Return at least a category according to RFC 2616 Section 10. */
  3629. if (response_code >= 100 && response_code < 200) {
  3630. /* Unknown informational status code */
  3631. return "Information";
  3632. }
  3633. if (response_code >= 200 && response_code < 300) {
  3634. /* Unknown success code */
  3635. return "Success";
  3636. }
  3637. if (response_code >= 300 && response_code < 400) {
  3638. /* Unknown redirection code */
  3639. return "Redirection";
  3640. }
  3641. if (response_code >= 400 && response_code < 500) {
  3642. /* Unknown request error code */
  3643. return "Client Error";
  3644. }
  3645. if (response_code >= 500 && response_code < 600) {
  3646. /* Unknown server error code */
  3647. return "Server Error";
  3648. }
  3649. /* Response code not even within reasonable range */
  3650. return "";
  3651. }
  3652. }
  3653. static int
  3654. mg_send_http_error_impl(struct mg_connection *conn,
  3655. int status,
  3656. const char *fmt,
  3657. va_list args)
  3658. {
  3659. char errmsg_buf[MG_BUF_LEN];
  3660. va_list ap;
  3661. int has_body;
  3662. #if !defined(NO_FILESYSTEMS)
  3663. char path_buf[UTF8_PATH_MAX];
  3664. int len, i, page_handler_found, scope, truncated;
  3665. const char *error_handler = NULL;
  3666. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3667. const char *error_page_file_ext, *tstr;
  3668. #endif /* NO_FILESYSTEMS */
  3669. int handled_by_callback = 0;
  3670. if ((conn == NULL) || (fmt == NULL)) {
  3671. return -2;
  3672. }
  3673. /* Set status (for log) */
  3674. conn->status_code = status;
  3675. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3676. has_body = ((status > 199) && (status != 204) && (status != 304));
  3677. /* Prepare message in buf, if required */
  3678. if (has_body
  3679. || (!conn->in_error_handler
  3680. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3681. /* Store error message in errmsg_buf */
  3682. va_copy(ap, args);
  3683. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3684. va_end(ap);
  3685. /* In a debug build, print all html errors */
  3686. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3687. }
  3688. /* If there is a http_error callback, call it.
  3689. * But don't do it recursively, if callback calls mg_send_http_error again.
  3690. */
  3691. if (!conn->in_error_handler
  3692. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3693. /* Mark in_error_handler to avoid recursion and call user callback. */
  3694. conn->in_error_handler = 1;
  3695. handled_by_callback =
  3696. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3697. == 0);
  3698. conn->in_error_handler = 0;
  3699. }
  3700. if (!handled_by_callback) {
  3701. /* Check for recursion */
  3702. if (conn->in_error_handler) {
  3703. DEBUG_TRACE(
  3704. "Recursion when handling error %u - fall back to default",
  3705. status);
  3706. #if !defined(NO_FILESYSTEMS)
  3707. } else {
  3708. /* Send user defined error pages, if defined */
  3709. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3710. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3711. page_handler_found = 0;
  3712. if (error_handler != NULL) {
  3713. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3714. switch (scope) {
  3715. case 1: /* Handler for specific error, e.g. 404 error */
  3716. mg_snprintf(conn,
  3717. &truncated,
  3718. path_buf,
  3719. sizeof(path_buf) - 32,
  3720. "%serror%03u.",
  3721. error_handler,
  3722. status);
  3723. break;
  3724. case 2: /* Handler for error group, e.g., 5xx error
  3725. * handler
  3726. * for all server errors (500-599) */
  3727. mg_snprintf(conn,
  3728. &truncated,
  3729. path_buf,
  3730. sizeof(path_buf) - 32,
  3731. "%serror%01uxx.",
  3732. error_handler,
  3733. status / 100);
  3734. break;
  3735. default: /* Handler for all errors */
  3736. mg_snprintf(conn,
  3737. &truncated,
  3738. path_buf,
  3739. sizeof(path_buf) - 32,
  3740. "%serror.",
  3741. error_handler);
  3742. break;
  3743. }
  3744. /* String truncation in buf may only occur if
  3745. * error_handler is too long. This string is
  3746. * from the config, not from a client. */
  3747. (void)truncated;
  3748. /* The following code is redundant, but it should avoid
  3749. * false positives in static source code analyzers and
  3750. * vulnerability scanners.
  3751. */
  3752. path_buf[sizeof(path_buf) - 32] = 0;
  3753. len = (int)strlen(path_buf);
  3754. if (len > (int)sizeof(path_buf) - 32) {
  3755. len = (int)sizeof(path_buf) - 32;
  3756. }
  3757. /* Start with the file extenstion from the configuration. */
  3758. tstr = strchr(error_page_file_ext, '.');
  3759. while (tstr) {
  3760. for (i = 1;
  3761. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3762. i++) {
  3763. /* buffer overrun is not possible here, since
  3764. * (i < 32) && (len < sizeof(path_buf) - 32)
  3765. * ==> (i + len) < sizeof(path_buf) */
  3766. path_buf[len + i - 1] = tstr[i];
  3767. }
  3768. /* buffer overrun is not possible here, since
  3769. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3770. * ==> (i + len) <= sizeof(path_buf) */
  3771. path_buf[len + i - 1] = 0;
  3772. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3773. DEBUG_TRACE("Check error page %s - found",
  3774. path_buf);
  3775. page_handler_found = 1;
  3776. break;
  3777. }
  3778. DEBUG_TRACE("Check error page %s - not found",
  3779. path_buf);
  3780. /* Continue with the next file extenstion from the
  3781. * configuration (if there is a next one). */
  3782. tstr = strchr(tstr + i, '.');
  3783. }
  3784. }
  3785. }
  3786. if (page_handler_found) {
  3787. conn->in_error_handler = 1;
  3788. handle_file_based_request(conn, path_buf, &error_page_file);
  3789. conn->in_error_handler = 0;
  3790. return 0;
  3791. }
  3792. #endif /* NO_FILESYSTEMS */
  3793. }
  3794. /* No custom error page. Send default error page. */
  3795. conn->must_close = 1;
  3796. mg_response_header_start(conn, status);
  3797. send_no_cache_header(conn);
  3798. send_additional_header(conn);
  3799. if (has_body) {
  3800. mg_response_header_add(conn,
  3801. "Content-Type",
  3802. "text/plain; charset=utf-8",
  3803. -1);
  3804. }
  3805. mg_response_header_send(conn);
  3806. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3807. if (has_body) {
  3808. /* For other errors, send a generic error message. */
  3809. const char *status_text = mg_get_response_code_text(conn, status);
  3810. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3811. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3812. } else {
  3813. /* No body allowed. Close the connection. */
  3814. DEBUG_TRACE("Error %i", status);
  3815. }
  3816. }
  3817. return 0;
  3818. }
  3819. int
  3820. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3821. {
  3822. va_list ap;
  3823. int ret;
  3824. va_start(ap, fmt);
  3825. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3826. va_end(ap);
  3827. return ret;
  3828. }
  3829. int
  3830. mg_send_http_ok(struct mg_connection *conn,
  3831. const char *mime_type,
  3832. long long content_length)
  3833. {
  3834. if ((mime_type == NULL) || (*mime_type == 0)) {
  3835. /* No content type defined: default to text/html */
  3836. mime_type = "text/html";
  3837. }
  3838. mg_response_header_start(conn, 200);
  3839. send_no_cache_header(conn);
  3840. send_additional_header(conn);
  3841. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3842. if (content_length < 0) {
  3843. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3844. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3845. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3846. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3847. }
  3848. } else {
  3849. char len[32];
  3850. int trunc = 0;
  3851. mg_snprintf(conn,
  3852. &trunc,
  3853. len,
  3854. sizeof(len),
  3855. "%" UINT64_FMT,
  3856. (uint64_t)content_length);
  3857. if (!trunc) {
  3858. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3859. * !trunc is always true */
  3860. mg_response_header_add(conn, "Content-Length", len, -1);
  3861. }
  3862. }
  3863. mg_response_header_send(conn);
  3864. return 0;
  3865. }
  3866. int
  3867. mg_send_http_redirect(struct mg_connection *conn,
  3868. const char *target_url,
  3869. int redirect_code)
  3870. {
  3871. /* Send a 30x redirect response.
  3872. *
  3873. * Redirect types (status codes):
  3874. *
  3875. * Status | Perm/Temp | Method | Version
  3876. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3877. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3878. * 303 | temporary | always use GET | HTTP/1.1
  3879. * 307 | temporary | always keep method | HTTP/1.1
  3880. * 308 | permanent | always keep method | HTTP/1.1
  3881. */
  3882. const char *redirect_text;
  3883. int ret;
  3884. size_t content_len = 0;
  3885. #if defined(MG_SEND_REDIRECT_BODY)
  3886. char reply[MG_BUF_LEN];
  3887. #endif
  3888. /* In case redirect_code=0, use 307. */
  3889. if (redirect_code == 0) {
  3890. redirect_code = 307;
  3891. }
  3892. /* In case redirect_code is none of the above, return error. */
  3893. if ((redirect_code != 301) && (redirect_code != 302)
  3894. && (redirect_code != 303) && (redirect_code != 307)
  3895. && (redirect_code != 308)) {
  3896. /* Parameter error */
  3897. return -2;
  3898. }
  3899. /* Get proper text for response code */
  3900. redirect_text = mg_get_response_code_text(conn, redirect_code);
  3901. /* If target_url is not defined, redirect to "/". */
  3902. if ((target_url == NULL) || (*target_url == 0)) {
  3903. target_url = "/";
  3904. }
  3905. #if defined(MG_SEND_REDIRECT_BODY)
  3906. /* TODO: condition name? */
  3907. /* Prepare a response body with a hyperlink.
  3908. *
  3909. * According to RFC2616 (and RFC1945 before):
  3910. * Unless the request method was HEAD, the entity of the
  3911. * response SHOULD contain a short hypertext note with a hyperlink to
  3912. * the new URI(s).
  3913. *
  3914. * However, this response body is not useful in M2M communication.
  3915. * Probably the original reason in the RFC was, clients not supporting
  3916. * a 30x HTTP redirect could still show the HTML page and let the user
  3917. * press the link. Since current browsers support 30x HTTP, the additional
  3918. * HTML body does not seem to make sense anymore.
  3919. *
  3920. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3921. * but it only notes:
  3922. * The server's response payload usually contains a short
  3923. * hypertext note with a hyperlink to the new URI(s).
  3924. *
  3925. * Deactivated by default. If you need the 30x body, set the define.
  3926. */
  3927. mg_snprintf(
  3928. conn,
  3929. NULL /* ignore truncation */,
  3930. reply,
  3931. sizeof(reply),
  3932. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3933. redirect_text,
  3934. target_url,
  3935. target_url);
  3936. content_len = strlen(reply);
  3937. #endif
  3938. /* Do not send any additional header. For all other options,
  3939. * including caching, there are suitable defaults. */
  3940. ret = mg_printf(conn,
  3941. "HTTP/1.1 %i %s\r\n"
  3942. "Location: %s\r\n"
  3943. "Content-Length: %u\r\n"
  3944. "Connection: %s\r\n\r\n",
  3945. redirect_code,
  3946. redirect_text,
  3947. target_url,
  3948. (unsigned int)content_len,
  3949. suggest_connection_header(conn));
  3950. #if defined(MG_SEND_REDIRECT_BODY)
  3951. /* Send response body */
  3952. if (ret > 0) {
  3953. /* ... unless it is a HEAD request */
  3954. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3955. ret = mg_write(conn, reply, content_len);
  3956. }
  3957. }
  3958. #endif
  3959. return (ret > 0) ? ret : -1;
  3960. }
  3961. #if defined(_WIN32)
  3962. /* Create substitutes for POSIX functions in Win32. */
  3963. #if defined(GCC_DIAGNOSTIC)
  3964. /* Show no warning in case system functions are not used. */
  3965. #pragma GCC diagnostic push
  3966. #pragma GCC diagnostic ignored "-Wunused-function"
  3967. #endif
  3968. static int
  3969. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3970. {
  3971. (void)unused;
  3972. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3973. InitializeCriticalSection(&mutex->sec);
  3974. return 0;
  3975. }
  3976. static int
  3977. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3978. {
  3979. DeleteCriticalSection(&mutex->sec);
  3980. return 0;
  3981. }
  3982. static int
  3983. pthread_mutex_lock(pthread_mutex_t *mutex)
  3984. {
  3985. EnterCriticalSection(&mutex->sec);
  3986. return 0;
  3987. }
  3988. static int
  3989. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3990. {
  3991. LeaveCriticalSection(&mutex->sec);
  3992. return 0;
  3993. }
  3994. FUNCTION_MAY_BE_UNUSED
  3995. static int
  3996. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3997. {
  3998. (void)unused;
  3999. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4000. cv->waiting_thread = NULL;
  4001. return 0;
  4002. }
  4003. FUNCTION_MAY_BE_UNUSED
  4004. static int
  4005. pthread_cond_timedwait(pthread_cond_t *cv,
  4006. pthread_mutex_t *mutex,
  4007. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4008. {
  4009. struct mg_workerTLS **ptls,
  4010. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4011. int ok;
  4012. uint64_t nsnow, nswaitabs;
  4013. int64_t nswaitrel;
  4014. DWORD mswaitrel;
  4015. pthread_mutex_lock(&cv->threadIdSec);
  4016. /* Add this thread to cv's waiting list */
  4017. ptls = &cv->waiting_thread;
  4018. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4019. ;
  4020. tls->next_waiting_thread = NULL;
  4021. *ptls = tls;
  4022. pthread_mutex_unlock(&cv->threadIdSec);
  4023. if (abstime) {
  4024. nsnow = mg_get_current_time_ns();
  4025. nswaitabs =
  4026. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4027. nswaitrel = nswaitabs - nsnow;
  4028. if (nswaitrel < 0) {
  4029. nswaitrel = 0;
  4030. }
  4031. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4032. } else {
  4033. mswaitrel = (DWORD)INFINITE;
  4034. }
  4035. pthread_mutex_unlock(mutex);
  4036. ok = (WAIT_OBJECT_0
  4037. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4038. if (!ok) {
  4039. ok = 1;
  4040. pthread_mutex_lock(&cv->threadIdSec);
  4041. ptls = &cv->waiting_thread;
  4042. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4043. if (*ptls == tls) {
  4044. *ptls = tls->next_waiting_thread;
  4045. ok = 0;
  4046. break;
  4047. }
  4048. }
  4049. pthread_mutex_unlock(&cv->threadIdSec);
  4050. if (ok) {
  4051. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4052. (DWORD)INFINITE);
  4053. }
  4054. }
  4055. /* This thread has been removed from cv's waiting list */
  4056. pthread_mutex_lock(mutex);
  4057. return ok ? 0 : -1;
  4058. }
  4059. FUNCTION_MAY_BE_UNUSED
  4060. static int
  4061. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4062. {
  4063. return pthread_cond_timedwait(cv, mutex, NULL);
  4064. }
  4065. FUNCTION_MAY_BE_UNUSED
  4066. static int
  4067. pthread_cond_signal(pthread_cond_t *cv)
  4068. {
  4069. HANDLE wkup = NULL;
  4070. BOOL ok = FALSE;
  4071. pthread_mutex_lock(&cv->threadIdSec);
  4072. if (cv->waiting_thread) {
  4073. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4074. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4075. ok = SetEvent(wkup);
  4076. DEBUG_ASSERT(ok);
  4077. }
  4078. pthread_mutex_unlock(&cv->threadIdSec);
  4079. return ok ? 0 : 1;
  4080. }
  4081. FUNCTION_MAY_BE_UNUSED
  4082. static int
  4083. pthread_cond_broadcast(pthread_cond_t *cv)
  4084. {
  4085. pthread_mutex_lock(&cv->threadIdSec);
  4086. while (cv->waiting_thread) {
  4087. pthread_cond_signal(cv);
  4088. }
  4089. pthread_mutex_unlock(&cv->threadIdSec);
  4090. return 0;
  4091. }
  4092. FUNCTION_MAY_BE_UNUSED
  4093. static int
  4094. pthread_cond_destroy(pthread_cond_t *cv)
  4095. {
  4096. pthread_mutex_lock(&cv->threadIdSec);
  4097. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4098. pthread_mutex_unlock(&cv->threadIdSec);
  4099. pthread_mutex_destroy(&cv->threadIdSec);
  4100. return 0;
  4101. }
  4102. #if defined(ALTERNATIVE_QUEUE)
  4103. FUNCTION_MAY_BE_UNUSED
  4104. static void *
  4105. event_create(void)
  4106. {
  4107. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4108. }
  4109. FUNCTION_MAY_BE_UNUSED
  4110. static int
  4111. event_wait(void *eventhdl)
  4112. {
  4113. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4114. return (res == WAIT_OBJECT_0);
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. event_signal(void *eventhdl)
  4119. {
  4120. return (int)SetEvent((HANDLE)eventhdl);
  4121. }
  4122. FUNCTION_MAY_BE_UNUSED
  4123. static void
  4124. event_destroy(void *eventhdl)
  4125. {
  4126. CloseHandle((HANDLE)eventhdl);
  4127. }
  4128. #endif
  4129. #if defined(GCC_DIAGNOSTIC)
  4130. /* Enable unused function warning again */
  4131. #pragma GCC diagnostic pop
  4132. #endif
  4133. /* For Windows, change all slashes to backslashes in path names. */
  4134. static void
  4135. change_slashes_to_backslashes(char *path)
  4136. {
  4137. int i;
  4138. for (i = 0; path[i] != '\0'; i++) {
  4139. if (path[i] == '/') {
  4140. path[i] = '\\';
  4141. }
  4142. /* remove double backslash (check i > 0 to preserve UNC paths,
  4143. * like \\server\file.txt) */
  4144. if ((i > 0) && (path[i] == '\\')) {
  4145. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4146. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4147. }
  4148. }
  4149. }
  4150. }
  4151. static int
  4152. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4153. {
  4154. int diff;
  4155. do {
  4156. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4157. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4158. s1++;
  4159. s2++;
  4160. } while ((diff == 0) && (s1[-1] != L'\0'));
  4161. return diff;
  4162. }
  4163. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4164. * wbuf and wbuf_len is a target buffer and its length. */
  4165. static void
  4166. path_to_unicode(const struct mg_connection *conn,
  4167. const char *path,
  4168. wchar_t *wbuf,
  4169. size_t wbuf_len)
  4170. {
  4171. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4172. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4173. DWORD long_len, err;
  4174. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4175. mg_strlcpy(buf, path, sizeof(buf));
  4176. change_slashes_to_backslashes(buf);
  4177. /* Convert to Unicode and back. If doubly-converted string does not
  4178. * match the original, something is fishy, reject. */
  4179. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4180. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4181. WideCharToMultiByte(
  4182. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4183. if (strcmp(buf, buf2) != 0) {
  4184. wbuf[0] = L'\0';
  4185. }
  4186. /* Windows file systems are not case sensitive, but you can still use
  4187. * uppercase and lowercase letters (on all modern file systems).
  4188. * The server can check if the URI uses the same upper/lowercase
  4189. * letters an the file system, effectively making Windows servers
  4190. * case sensitive (like Linux servers are). It is still not possible
  4191. * to use two files with the same name in different cases on Windows
  4192. * (like /a and /A) - this would be possible in Linux.
  4193. * As a default, Windows is not case sensitive, but the case sensitive
  4194. * file name check can be activated by an additional configuration. */
  4195. if (conn) {
  4196. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4197. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4198. "yes")) {
  4199. /* Use case sensitive compare function */
  4200. fcompare = wcscmp;
  4201. }
  4202. }
  4203. (void)conn; /* conn is currently unused */
  4204. /* Only accept a full file path, not a Windows short (8.3) path. */
  4205. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4206. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4207. if (long_len == 0) {
  4208. err = GetLastError();
  4209. if (err == ERROR_FILE_NOT_FOUND) {
  4210. /* File does not exist. This is not always a problem here. */
  4211. return;
  4212. }
  4213. }
  4214. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4215. /* Short name is used. */
  4216. wbuf[0] = L'\0';
  4217. }
  4218. }
  4219. #if !defined(NO_FILESYSTEMS)
  4220. /* Get file information, return 1 if file exists, 0 if not */
  4221. static int
  4222. mg_stat(const struct mg_connection *conn,
  4223. const char *path,
  4224. struct mg_file_stat *filep)
  4225. {
  4226. wchar_t wbuf[UTF16_PATH_MAX];
  4227. WIN32_FILE_ATTRIBUTE_DATA info;
  4228. time_t creation_time;
  4229. size_t len;
  4230. if (!filep) {
  4231. return 0;
  4232. }
  4233. memset(filep, 0, sizeof(*filep));
  4234. if (mg_path_suspicious(conn, path)) {
  4235. return 0;
  4236. }
  4237. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4238. /* Windows happily opens files with some garbage at the end of file name.
  4239. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4240. * "a.cgi", despite one would expect an error back. */
  4241. len = strlen(path);
  4242. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4243. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4244. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4245. filep->last_modified =
  4246. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4247. info.ftLastWriteTime.dwHighDateTime);
  4248. /* On Windows, the file creation time can be higher than the
  4249. * modification time, e.g. when a file is copied.
  4250. * Since the Last-Modified timestamp is used for caching
  4251. * it should be based on the most recent timestamp. */
  4252. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4253. info.ftCreationTime.dwHighDateTime);
  4254. if (creation_time > filep->last_modified) {
  4255. filep->last_modified = creation_time;
  4256. }
  4257. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4258. return 1;
  4259. }
  4260. return 0;
  4261. }
  4262. #endif
  4263. static int
  4264. mg_remove(const struct mg_connection *conn, const char *path)
  4265. {
  4266. wchar_t wbuf[UTF16_PATH_MAX];
  4267. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4268. return DeleteFileW(wbuf) ? 0 : -1;
  4269. }
  4270. static int
  4271. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4272. {
  4273. wchar_t wbuf[UTF16_PATH_MAX];
  4274. (void)mode;
  4275. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4276. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4277. }
  4278. /* Create substitutes for POSIX functions in Win32. */
  4279. #if defined(GCC_DIAGNOSTIC)
  4280. /* Show no warning in case system functions are not used. */
  4281. #pragma GCC diagnostic push
  4282. #pragma GCC diagnostic ignored "-Wunused-function"
  4283. #endif
  4284. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4285. FUNCTION_MAY_BE_UNUSED
  4286. static DIR *
  4287. mg_opendir(const struct mg_connection *conn, const char *name)
  4288. {
  4289. DIR *dir = NULL;
  4290. wchar_t wpath[UTF16_PATH_MAX];
  4291. DWORD attrs;
  4292. if (name == NULL) {
  4293. SetLastError(ERROR_BAD_ARGUMENTS);
  4294. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4295. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4296. } else {
  4297. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4298. attrs = GetFileAttributesW(wpath);
  4299. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4300. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4301. (void)wcscat(wpath, L"\\*");
  4302. dir->handle = FindFirstFileW(wpath, &dir->info);
  4303. dir->result.d_name[0] = '\0';
  4304. } else {
  4305. mg_free(dir);
  4306. dir = NULL;
  4307. }
  4308. }
  4309. return dir;
  4310. }
  4311. FUNCTION_MAY_BE_UNUSED
  4312. static int
  4313. mg_closedir(DIR *dir)
  4314. {
  4315. int result = 0;
  4316. if (dir != NULL) {
  4317. if (dir->handle != INVALID_HANDLE_VALUE)
  4318. result = FindClose(dir->handle) ? 0 : -1;
  4319. mg_free(dir);
  4320. } else {
  4321. result = -1;
  4322. SetLastError(ERROR_BAD_ARGUMENTS);
  4323. }
  4324. return result;
  4325. }
  4326. FUNCTION_MAY_BE_UNUSED
  4327. static struct dirent *
  4328. mg_readdir(DIR *dir)
  4329. {
  4330. struct dirent *result = 0;
  4331. if (dir) {
  4332. if (dir->handle != INVALID_HANDLE_VALUE) {
  4333. result = &dir->result;
  4334. (void)WideCharToMultiByte(CP_UTF8,
  4335. 0,
  4336. dir->info.cFileName,
  4337. -1,
  4338. result->d_name,
  4339. sizeof(result->d_name),
  4340. NULL,
  4341. NULL);
  4342. if (!FindNextFileW(dir->handle, &dir->info)) {
  4343. (void)FindClose(dir->handle);
  4344. dir->handle = INVALID_HANDLE_VALUE;
  4345. }
  4346. } else {
  4347. SetLastError(ERROR_FILE_NOT_FOUND);
  4348. }
  4349. } else {
  4350. SetLastError(ERROR_BAD_ARGUMENTS);
  4351. }
  4352. return result;
  4353. }
  4354. #if !defined(HAVE_POLL)
  4355. #undef POLLIN
  4356. #undef POLLPRI
  4357. #undef POLLOUT
  4358. #undef POLLERR
  4359. #define POLLIN (1) /* Data ready - read will not block. */
  4360. #define POLLPRI (2) /* Priority data ready. */
  4361. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4362. #define POLLERR (8) /* Error event */
  4363. FUNCTION_MAY_BE_UNUSED
  4364. static int
  4365. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4366. {
  4367. struct timeval tv;
  4368. fd_set rset;
  4369. fd_set wset;
  4370. fd_set eset;
  4371. unsigned int i;
  4372. int result;
  4373. SOCKET maxfd = 0;
  4374. memset(&tv, 0, sizeof(tv));
  4375. tv.tv_sec = milliseconds / 1000;
  4376. tv.tv_usec = (milliseconds % 1000) * 1000;
  4377. FD_ZERO(&rset);
  4378. FD_ZERO(&wset);
  4379. FD_ZERO(&eset);
  4380. for (i = 0; i < n; i++) {
  4381. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4382. if (pfd[i].events & POLLIN) {
  4383. FD_SET(pfd[i].fd, &rset);
  4384. }
  4385. if (pfd[i].events & POLLOUT) {
  4386. FD_SET(pfd[i].fd, &wset);
  4387. }
  4388. /* Check for errors for any FD in the set */
  4389. FD_SET(pfd[i].fd, &eset);
  4390. }
  4391. pfd[i].revents = 0;
  4392. if (pfd[i].fd > maxfd) {
  4393. maxfd = pfd[i].fd;
  4394. }
  4395. }
  4396. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4397. for (i = 0; i < n; i++) {
  4398. if (FD_ISSET(pfd[i].fd, &rset)) {
  4399. pfd[i].revents |= POLLIN;
  4400. }
  4401. if (FD_ISSET(pfd[i].fd, &wset)) {
  4402. pfd[i].revents |= POLLOUT;
  4403. }
  4404. if (FD_ISSET(pfd[i].fd, &eset)) {
  4405. pfd[i].revents |= POLLERR;
  4406. }
  4407. }
  4408. }
  4409. /* We should subtract the time used in select from remaining
  4410. * "milliseconds", in particular if called from mg_poll with a
  4411. * timeout quantum.
  4412. * Unfortunately, the remaining time is not stored in "tv" in all
  4413. * implementations, so the result in "tv" must be considered undefined.
  4414. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4415. return result;
  4416. }
  4417. #endif /* HAVE_POLL */
  4418. #if defined(GCC_DIAGNOSTIC)
  4419. /* Enable unused function warning again */
  4420. #pragma GCC diagnostic pop
  4421. #endif
  4422. static void
  4423. set_close_on_exec(SOCKET sock,
  4424. const struct mg_connection *conn /* may be null */,
  4425. struct mg_context *ctx /* may be null */)
  4426. {
  4427. (void)conn; /* Unused. */
  4428. (void)ctx;
  4429. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4430. }
  4431. int
  4432. mg_start_thread(mg_thread_func_t f, void *p)
  4433. {
  4434. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4435. /* Compile-time option to control stack size, e.g.
  4436. * -DUSE_STACK_SIZE=16384
  4437. */
  4438. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4439. == ((uintptr_t)(-1L)))
  4440. ? -1
  4441. : 0);
  4442. #else
  4443. return (
  4444. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4445. ? -1
  4446. : 0);
  4447. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4448. }
  4449. /* Start a thread storing the thread context. */
  4450. static int
  4451. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4452. void *p,
  4453. pthread_t *threadidptr)
  4454. {
  4455. uintptr_t uip;
  4456. HANDLE threadhandle;
  4457. int result = -1;
  4458. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4459. threadhandle = (HANDLE)uip;
  4460. if ((uip != 0) && (threadidptr != NULL)) {
  4461. *threadidptr = threadhandle;
  4462. result = 0;
  4463. }
  4464. return result;
  4465. }
  4466. /* Wait for a thread to finish. */
  4467. static int
  4468. mg_join_thread(pthread_t threadid)
  4469. {
  4470. int result;
  4471. DWORD dwevent;
  4472. result = -1;
  4473. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4474. if (dwevent == WAIT_FAILED) {
  4475. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4476. } else {
  4477. if (dwevent == WAIT_OBJECT_0) {
  4478. CloseHandle(threadid);
  4479. result = 0;
  4480. }
  4481. }
  4482. return result;
  4483. }
  4484. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4485. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4486. /* Create substitutes for POSIX functions in Win32. */
  4487. #if defined(GCC_DIAGNOSTIC)
  4488. /* Show no warning in case system functions are not used. */
  4489. #pragma GCC diagnostic push
  4490. #pragma GCC diagnostic ignored "-Wunused-function"
  4491. #endif
  4492. FUNCTION_MAY_BE_UNUSED
  4493. static HANDLE
  4494. dlopen(const char *dll_name, int flags)
  4495. {
  4496. wchar_t wbuf[UTF16_PATH_MAX];
  4497. (void)flags;
  4498. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4499. return LoadLibraryW(wbuf);
  4500. }
  4501. FUNCTION_MAY_BE_UNUSED
  4502. static int
  4503. dlclose(void *handle)
  4504. {
  4505. int result;
  4506. if (FreeLibrary((HMODULE)handle) != 0) {
  4507. result = 0;
  4508. } else {
  4509. result = -1;
  4510. }
  4511. return result;
  4512. }
  4513. #if defined(GCC_DIAGNOSTIC)
  4514. /* Enable unused function warning again */
  4515. #pragma GCC diagnostic pop
  4516. #endif
  4517. #endif
  4518. #if !defined(NO_CGI)
  4519. #define SIGKILL (0)
  4520. static int
  4521. kill(pid_t pid, int sig_num)
  4522. {
  4523. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4524. (void)CloseHandle((HANDLE)pid);
  4525. return 0;
  4526. }
  4527. #if !defined(WNOHANG)
  4528. #define WNOHANG (1)
  4529. #endif
  4530. static pid_t
  4531. waitpid(pid_t pid, int *status, int flags)
  4532. {
  4533. DWORD timeout = INFINITE;
  4534. DWORD waitres;
  4535. (void)status; /* Currently not used by any client here */
  4536. if ((flags | WNOHANG) == WNOHANG) {
  4537. timeout = 0;
  4538. }
  4539. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4540. if (waitres == WAIT_OBJECT_0) {
  4541. return pid;
  4542. }
  4543. if (waitres == WAIT_TIMEOUT) {
  4544. return 0;
  4545. }
  4546. return (pid_t)-1;
  4547. }
  4548. static void
  4549. trim_trailing_whitespaces(char *s)
  4550. {
  4551. char *e = s + strlen(s);
  4552. while ((e > s) && isspace((unsigned char)e[-1])) {
  4553. *(--e) = '\0';
  4554. }
  4555. }
  4556. static pid_t
  4557. spawn_process(struct mg_connection *conn,
  4558. const char *prog,
  4559. char *envblk,
  4560. char *envp[],
  4561. int fdin[2],
  4562. int fdout[2],
  4563. int fderr[2],
  4564. const char *dir,
  4565. unsigned char cgi_config_idx)
  4566. {
  4567. HANDLE me;
  4568. char *interp;
  4569. char *interp_arg = 0;
  4570. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4571. int truncated;
  4572. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4573. STARTUPINFOA si;
  4574. PROCESS_INFORMATION pi = {0};
  4575. (void)envp;
  4576. memset(&si, 0, sizeof(si));
  4577. si.cb = sizeof(si);
  4578. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4579. si.wShowWindow = SW_HIDE;
  4580. me = GetCurrentProcess();
  4581. DuplicateHandle(me,
  4582. (HANDLE)_get_osfhandle(fdin[0]),
  4583. me,
  4584. &si.hStdInput,
  4585. 0,
  4586. TRUE,
  4587. DUPLICATE_SAME_ACCESS);
  4588. DuplicateHandle(me,
  4589. (HANDLE)_get_osfhandle(fdout[1]),
  4590. me,
  4591. &si.hStdOutput,
  4592. 0,
  4593. TRUE,
  4594. DUPLICATE_SAME_ACCESS);
  4595. DuplicateHandle(me,
  4596. (HANDLE)_get_osfhandle(fderr[1]),
  4597. me,
  4598. &si.hStdError,
  4599. 0,
  4600. TRUE,
  4601. DUPLICATE_SAME_ACCESS);
  4602. /* Mark handles that should not be inherited. See
  4603. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4604. */
  4605. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4606. HANDLE_FLAG_INHERIT,
  4607. 0);
  4608. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4609. HANDLE_FLAG_INHERIT,
  4610. 0);
  4611. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4612. HANDLE_FLAG_INHERIT,
  4613. 0);
  4614. /* First check, if there is a CGI interpreter configured for all CGI
  4615. * scripts. */
  4616. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4617. if (interp != NULL) {
  4618. /* If there is a configured interpreter, check for additional arguments
  4619. */
  4620. interp_arg =
  4621. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4622. } else {
  4623. /* Otherwise, the interpreter must be stated in the first line of the
  4624. * CGI script file, after a #! (shebang) mark. */
  4625. buf[0] = buf[1] = '\0';
  4626. /* Get the full script path */
  4627. mg_snprintf(
  4628. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4629. if (truncated) {
  4630. pi.hProcess = (pid_t)-1;
  4631. goto spawn_cleanup;
  4632. }
  4633. /* Open the script file, to read the first line */
  4634. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4635. /* Read the first line of the script into the buffer */
  4636. mg_fgets(buf, sizeof(buf), &file);
  4637. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4638. buf[sizeof(buf) - 1] = '\0';
  4639. }
  4640. if ((buf[0] == '#') && (buf[1] == '!')) {
  4641. trim_trailing_whitespaces(buf + 2);
  4642. } else {
  4643. buf[2] = '\0';
  4644. }
  4645. interp = buf + 2;
  4646. }
  4647. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4648. if (interp[0] != '\0') {
  4649. /* This is an interpreted script file. We must call the interpreter. */
  4650. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4651. mg_snprintf(conn,
  4652. &truncated,
  4653. cmdline,
  4654. sizeof(cmdline),
  4655. "\"%s\" %s \"%s\\%s\"",
  4656. interp,
  4657. interp_arg,
  4658. full_dir,
  4659. prog);
  4660. } else {
  4661. mg_snprintf(conn,
  4662. &truncated,
  4663. cmdline,
  4664. sizeof(cmdline),
  4665. "\"%s\" \"%s\\%s\"",
  4666. interp,
  4667. full_dir,
  4668. prog);
  4669. }
  4670. } else {
  4671. /* This is (probably) a compiled program. We call it directly. */
  4672. mg_snprintf(conn,
  4673. &truncated,
  4674. cmdline,
  4675. sizeof(cmdline),
  4676. "\"%s\\%s\"",
  4677. full_dir,
  4678. prog);
  4679. }
  4680. if (truncated) {
  4681. pi.hProcess = (pid_t)-1;
  4682. goto spawn_cleanup;
  4683. }
  4684. DEBUG_TRACE("Running [%s]", cmdline);
  4685. if (CreateProcessA(NULL,
  4686. cmdline,
  4687. NULL,
  4688. NULL,
  4689. TRUE,
  4690. CREATE_NEW_PROCESS_GROUP,
  4691. envblk,
  4692. NULL,
  4693. &si,
  4694. &pi)
  4695. == 0) {
  4696. mg_cry_internal(
  4697. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4698. pi.hProcess = (pid_t)-1;
  4699. /* goto spawn_cleanup; */
  4700. }
  4701. spawn_cleanup:
  4702. (void)CloseHandle(si.hStdOutput);
  4703. (void)CloseHandle(si.hStdError);
  4704. (void)CloseHandle(si.hStdInput);
  4705. if (pi.hThread != NULL) {
  4706. (void)CloseHandle(pi.hThread);
  4707. }
  4708. return (pid_t)pi.hProcess;
  4709. }
  4710. #endif /* !NO_CGI */
  4711. static int
  4712. set_blocking_mode(SOCKET sock)
  4713. {
  4714. unsigned long non_blocking = 0;
  4715. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4716. }
  4717. static int
  4718. set_non_blocking_mode(SOCKET sock)
  4719. {
  4720. unsigned long non_blocking = 1;
  4721. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4722. }
  4723. #else
  4724. #if !defined(NO_FILESYSTEMS)
  4725. static int
  4726. mg_stat(const struct mg_connection *conn,
  4727. const char *path,
  4728. struct mg_file_stat *filep)
  4729. {
  4730. struct stat st;
  4731. if (!filep) {
  4732. return 0;
  4733. }
  4734. memset(filep, 0, sizeof(*filep));
  4735. if (mg_path_suspicious(conn, path)) {
  4736. return 0;
  4737. }
  4738. if (0 == stat(path, &st)) {
  4739. filep->size = (uint64_t)(st.st_size);
  4740. filep->last_modified = st.st_mtime;
  4741. filep->is_directory = S_ISDIR(st.st_mode);
  4742. return 1;
  4743. }
  4744. return 0;
  4745. }
  4746. #endif /* NO_FILESYSTEMS */
  4747. static void
  4748. set_close_on_exec(int fd,
  4749. const struct mg_connection *conn /* may be null */,
  4750. struct mg_context *ctx /* may be null */)
  4751. {
  4752. #if defined(__ZEPHYR__)
  4753. (void)fd;
  4754. (void)conn;
  4755. (void)ctx;
  4756. #else
  4757. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4758. if (conn || ctx) {
  4759. struct mg_connection fc;
  4760. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4761. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4762. __func__,
  4763. strerror(ERRNO));
  4764. }
  4765. }
  4766. #endif
  4767. }
  4768. int
  4769. mg_start_thread(mg_thread_func_t func, void *param)
  4770. {
  4771. pthread_t thread_id;
  4772. pthread_attr_t attr;
  4773. int result;
  4774. (void)pthread_attr_init(&attr);
  4775. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4776. #if defined(__ZEPHYR__)
  4777. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4778. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4779. /* Compile-time option to control stack size,
  4780. * e.g. -DUSE_STACK_SIZE=16384 */
  4781. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4782. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4783. result = pthread_create(&thread_id, &attr, func, param);
  4784. pthread_attr_destroy(&attr);
  4785. return result;
  4786. }
  4787. /* Start a thread storing the thread context. */
  4788. static int
  4789. mg_start_thread_with_id(mg_thread_func_t func,
  4790. void *param,
  4791. pthread_t *threadidptr)
  4792. {
  4793. pthread_t thread_id;
  4794. pthread_attr_t attr;
  4795. int result;
  4796. (void)pthread_attr_init(&attr);
  4797. #if defined(__ZEPHYR__)
  4798. pthread_attr_setstack(&attr,
  4799. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4800. ZEPHYR_STACK_SIZE);
  4801. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4802. /* Compile-time option to control stack size,
  4803. * e.g. -DUSE_STACK_SIZE=16384 */
  4804. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4805. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4806. result = pthread_create(&thread_id, &attr, func, param);
  4807. pthread_attr_destroy(&attr);
  4808. if ((result == 0) && (threadidptr != NULL)) {
  4809. *threadidptr = thread_id;
  4810. }
  4811. return result;
  4812. }
  4813. /* Wait for a thread to finish. */
  4814. static int
  4815. mg_join_thread(pthread_t threadid)
  4816. {
  4817. int result;
  4818. result = pthread_join(threadid, NULL);
  4819. return result;
  4820. }
  4821. #if !defined(NO_CGI)
  4822. static pid_t
  4823. spawn_process(struct mg_connection *conn,
  4824. const char *prog,
  4825. char *envblk,
  4826. char *envp[],
  4827. int fdin[2],
  4828. int fdout[2],
  4829. int fderr[2],
  4830. const char *dir,
  4831. unsigned char cgi_config_idx)
  4832. {
  4833. pid_t pid;
  4834. const char *interp;
  4835. (void)envblk;
  4836. if ((pid = fork()) == -1) {
  4837. /* Parent */
  4838. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4839. } else if (pid != 0) {
  4840. /* Make sure children close parent-side descriptors.
  4841. * The caller will close the child-side immediately. */
  4842. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4843. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4844. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4845. } else {
  4846. /* Child */
  4847. if (chdir(dir) != 0) {
  4848. mg_cry_internal(
  4849. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4850. } else if (dup2(fdin[0], 0) == -1) {
  4851. mg_cry_internal(conn,
  4852. "%s: dup2(%d, 0): %s",
  4853. __func__,
  4854. fdin[0],
  4855. strerror(ERRNO));
  4856. } else if (dup2(fdout[1], 1) == -1) {
  4857. mg_cry_internal(conn,
  4858. "%s: dup2(%d, 1): %s",
  4859. __func__,
  4860. fdout[1],
  4861. strerror(ERRNO));
  4862. } else if (dup2(fderr[1], 2) == -1) {
  4863. mg_cry_internal(conn,
  4864. "%s: dup2(%d, 2): %s",
  4865. __func__,
  4866. fderr[1],
  4867. strerror(ERRNO));
  4868. } else {
  4869. struct sigaction sa;
  4870. /* Keep stderr and stdout in two different pipes.
  4871. * Stdout will be sent back to the client,
  4872. * stderr should go into a server error log. */
  4873. (void)close(fdin[0]);
  4874. (void)close(fdout[1]);
  4875. (void)close(fderr[1]);
  4876. /* Close write end fdin and read end fdout and fderr */
  4877. (void)close(fdin[1]);
  4878. (void)close(fdout[0]);
  4879. (void)close(fderr[0]);
  4880. /* After exec, all signal handlers are restored to their default
  4881. * values, with one exception of SIGCHLD. According to
  4882. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4883. * will leave unchanged after exec if it was set to be ignored.
  4884. * Restore it to default action. */
  4885. memset(&sa, 0, sizeof(sa));
  4886. sa.sa_handler = SIG_DFL;
  4887. sigaction(SIGCHLD, &sa, NULL);
  4888. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4889. if (interp == NULL) {
  4890. /* no interpreter configured, call the programm directly */
  4891. (void)execle(prog, prog, NULL, envp);
  4892. mg_cry_internal(conn,
  4893. "%s: execle(%s): %s",
  4894. __func__,
  4895. prog,
  4896. strerror(ERRNO));
  4897. } else {
  4898. /* call the configured interpreter */
  4899. const char *interp_args =
  4900. conn->dom_ctx
  4901. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4902. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4903. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4904. } else {
  4905. (void)execle(interp, interp, prog, NULL, envp);
  4906. }
  4907. mg_cry_internal(conn,
  4908. "%s: execle(%s %s): %s",
  4909. __func__,
  4910. interp,
  4911. prog,
  4912. strerror(ERRNO));
  4913. }
  4914. }
  4915. exit(EXIT_FAILURE);
  4916. }
  4917. return pid;
  4918. }
  4919. #endif /* !NO_CGI */
  4920. static int
  4921. set_non_blocking_mode(SOCKET sock)
  4922. {
  4923. int flags = fcntl(sock, F_GETFL, 0);
  4924. if (flags < 0) {
  4925. return -1;
  4926. }
  4927. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4928. return -1;
  4929. }
  4930. return 0;
  4931. }
  4932. static int
  4933. set_blocking_mode(SOCKET sock)
  4934. {
  4935. int flags = fcntl(sock, F_GETFL, 0);
  4936. if (flags < 0) {
  4937. return -1;
  4938. }
  4939. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4940. return -1;
  4941. }
  4942. return 0;
  4943. }
  4944. #endif /* _WIN32 / else */
  4945. /* End of initial operating system specific define block. */
  4946. /* Get a random number (independent of C rand function) */
  4947. static uint64_t
  4948. get_random(void)
  4949. {
  4950. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4951. static uint64_t lcg = 0; /* Linear congruential generator */
  4952. uint64_t now = mg_get_current_time_ns();
  4953. if (lfsr == 0) {
  4954. /* lfsr will be only 0 if has not been initialized,
  4955. * so this code is called only once. */
  4956. lfsr = mg_get_current_time_ns();
  4957. lcg = mg_get_current_time_ns();
  4958. } else {
  4959. /* Get the next step of both random number generators. */
  4960. lfsr = (lfsr >> 1)
  4961. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4962. << 63);
  4963. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4964. }
  4965. /* Combining two pseudo-random number generators and a high resolution
  4966. * part
  4967. * of the current server time will make it hard (impossible?) to guess
  4968. * the
  4969. * next number. */
  4970. return (lfsr ^ lcg ^ now);
  4971. }
  4972. static int
  4973. mg_poll(struct mg_pollfd *pfd,
  4974. unsigned int n,
  4975. int milliseconds,
  4976. const stop_flag_t *stop_flag)
  4977. {
  4978. /* Call poll, but only for a maximum time of a few seconds.
  4979. * This will allow to stop the server after some seconds, instead
  4980. * of having to wait for a long socket timeout. */
  4981. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4982. int check_pollerr = 0;
  4983. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  4984. /* If we wait for only one file descriptor, wait on error as well */
  4985. pfd[0].events |= POLLERR;
  4986. check_pollerr = 1;
  4987. }
  4988. do {
  4989. int result;
  4990. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  4991. /* Shut down signal */
  4992. return -2;
  4993. }
  4994. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4995. ms_now = milliseconds;
  4996. }
  4997. result = poll(pfd, n, ms_now);
  4998. if (result != 0) {
  4999. /* Poll returned either success (1) or error (-1).
  5000. * Forward both to the caller. */
  5001. if ((check_pollerr)
  5002. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5003. == POLLERR)) {
  5004. /* One and only file descriptor returned error */
  5005. return -1;
  5006. }
  5007. return result;
  5008. }
  5009. /* Poll returned timeout (0). */
  5010. if (milliseconds > 0) {
  5011. milliseconds -= ms_now;
  5012. }
  5013. } while (milliseconds > 0);
  5014. /* timeout: return 0 */
  5015. return 0;
  5016. }
  5017. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5018. * descriptor.
  5019. * Return value:
  5020. * >=0 .. number of bytes successfully written
  5021. * -1 .. timeout
  5022. * -2 .. error
  5023. */
  5024. static int
  5025. push_inner(struct mg_context *ctx,
  5026. FILE *fp,
  5027. SOCKET sock,
  5028. SSL *ssl,
  5029. const char *buf,
  5030. int len,
  5031. double timeout)
  5032. {
  5033. uint64_t start = 0, now = 0, timeout_ns = 0;
  5034. int n, err;
  5035. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5036. #if defined(_WIN32)
  5037. typedef int len_t;
  5038. #else
  5039. typedef size_t len_t;
  5040. #endif
  5041. if (timeout > 0) {
  5042. now = mg_get_current_time_ns();
  5043. start = now;
  5044. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5045. }
  5046. if (ctx == NULL) {
  5047. return -2;
  5048. }
  5049. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5050. if (ssl) {
  5051. return -2;
  5052. }
  5053. #endif
  5054. /* Try to read until it succeeds, fails, times out, or the server
  5055. * shuts down. */
  5056. for (;;) {
  5057. #if defined(USE_MBEDTLS)
  5058. if (ssl != NULL) {
  5059. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5060. if (n <= 0) {
  5061. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5062. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5063. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5064. n = 0;
  5065. } else {
  5066. fprintf(stderr, "SSL write failed, error %d\n", n);
  5067. return -2;
  5068. }
  5069. } else {
  5070. err = 0;
  5071. }
  5072. } else
  5073. #elif !defined(NO_SSL)
  5074. if (ssl != NULL) {
  5075. ERR_clear_error();
  5076. n = SSL_write(ssl, buf, len);
  5077. if (n <= 0) {
  5078. err = SSL_get_error(ssl, n);
  5079. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5080. err = ERRNO;
  5081. } else if ((err == SSL_ERROR_WANT_READ)
  5082. || (err == SSL_ERROR_WANT_WRITE)) {
  5083. n = 0;
  5084. } else {
  5085. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5086. ERR_clear_error();
  5087. return -2;
  5088. }
  5089. ERR_clear_error();
  5090. } else {
  5091. err = 0;
  5092. }
  5093. } else
  5094. #endif
  5095. if (fp != NULL) {
  5096. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5097. if (ferror(fp)) {
  5098. n = -1;
  5099. err = ERRNO;
  5100. } else {
  5101. err = 0;
  5102. }
  5103. } else {
  5104. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5105. err = (n < 0) ? ERRNO : 0;
  5106. #if defined(_WIN32)
  5107. if (err == WSAEWOULDBLOCK) {
  5108. err = 0;
  5109. n = 0;
  5110. }
  5111. #else
  5112. if (ERROR_TRY_AGAIN(err)) {
  5113. err = 0;
  5114. n = 0;
  5115. }
  5116. #endif
  5117. if (n < 0) {
  5118. /* shutdown of the socket at client side */
  5119. return -2;
  5120. }
  5121. }
  5122. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5123. return -2;
  5124. }
  5125. if ((n > 0) || ((n == 0) && (len == 0))) {
  5126. /* some data has been read, or no data was requested */
  5127. return n;
  5128. }
  5129. if (n < 0) {
  5130. /* socket error - check errno */
  5131. DEBUG_TRACE("send() failed, error %d", err);
  5132. /* TODO (mid): error handling depending on the error code.
  5133. * These codes are different between Windows and Linux.
  5134. * Currently there is no problem with failing send calls,
  5135. * if there is a reproducible situation, it should be
  5136. * investigated in detail.
  5137. */
  5138. return -2;
  5139. }
  5140. /* Only in case n=0 (timeout), repeat calling the write function */
  5141. /* If send failed, wait before retry */
  5142. if (fp != NULL) {
  5143. /* For files, just wait a fixed time.
  5144. * Maybe it helps, maybe not. */
  5145. mg_sleep(5);
  5146. } else {
  5147. /* For sockets, wait for the socket using poll */
  5148. struct mg_pollfd pfd[1];
  5149. int pollres;
  5150. pfd[0].fd = sock;
  5151. pfd[0].events = POLLOUT;
  5152. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5153. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5154. return -2;
  5155. }
  5156. if (pollres > 0) {
  5157. continue;
  5158. }
  5159. }
  5160. if (timeout > 0) {
  5161. now = mg_get_current_time_ns();
  5162. if ((now - start) > timeout_ns) {
  5163. /* Timeout */
  5164. break;
  5165. }
  5166. }
  5167. }
  5168. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5169. used */
  5170. return -1;
  5171. }
  5172. static int
  5173. push_all(struct mg_context *ctx,
  5174. FILE *fp,
  5175. SOCKET sock,
  5176. SSL *ssl,
  5177. const char *buf,
  5178. int len)
  5179. {
  5180. double timeout = -1.0;
  5181. int n, nwritten = 0;
  5182. if (ctx == NULL) {
  5183. return -1;
  5184. }
  5185. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5186. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5187. }
  5188. if (timeout <= 0.0) {
  5189. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5190. / 1000.0;
  5191. }
  5192. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5193. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5194. if (n < 0) {
  5195. if (nwritten == 0) {
  5196. nwritten = -1; /* Propagate the error */
  5197. }
  5198. break;
  5199. } else if (n == 0) {
  5200. break; /* No more data to write */
  5201. } else {
  5202. nwritten += n;
  5203. len -= n;
  5204. }
  5205. }
  5206. return nwritten;
  5207. }
  5208. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5209. * Return value:
  5210. * >=0 .. number of bytes successfully read
  5211. * -1 .. timeout
  5212. * -2 .. error
  5213. */
  5214. static int
  5215. pull_inner(FILE *fp,
  5216. struct mg_connection *conn,
  5217. char *buf,
  5218. int len,
  5219. double timeout)
  5220. {
  5221. int nread, err = 0;
  5222. #if defined(_WIN32)
  5223. typedef int len_t;
  5224. #else
  5225. typedef size_t len_t;
  5226. #endif
  5227. /* We need an additional wait loop around this, because in some cases
  5228. * with TLSwe may get data from the socket but not from SSL_read.
  5229. * In this case we need to repeat at least once.
  5230. */
  5231. if (fp != NULL) {
  5232. /* Use read() instead of fread(), because if we're reading from the
  5233. * CGI pipe, fread() may block until IO buffer is filled up. We
  5234. * cannot afford to block and must pass all read bytes immediately
  5235. * to the client. */
  5236. nread = (int)read(fileno(fp), buf, (size_t)len);
  5237. err = (nread < 0) ? ERRNO : 0;
  5238. if ((nread == 0) && (len > 0)) {
  5239. /* Should get data, but got EOL */
  5240. return -2;
  5241. }
  5242. #if defined(USE_MBEDTLS)
  5243. } else if (conn->ssl != NULL) {
  5244. struct mg_pollfd pfd[1];
  5245. int to_read;
  5246. int pollres;
  5247. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5248. if (to_read > 0) {
  5249. /* We already know there is no more data buffered in conn->buf
  5250. * but there is more available in the SSL layer. So don't poll
  5251. * conn->client.sock yet. */
  5252. pollres = 1;
  5253. if (to_read > len)
  5254. to_read = len;
  5255. } else {
  5256. pfd[0].fd = conn->client.sock;
  5257. pfd[0].events = POLLIN;
  5258. to_read = len;
  5259. pollres = mg_poll(pfd,
  5260. 1,
  5261. (int)(timeout * 1000.0),
  5262. &(conn->phys_ctx->stop_flag));
  5263. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5264. return -2;
  5265. }
  5266. }
  5267. if (pollres > 0) {
  5268. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5269. if (nread <= 0) {
  5270. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5271. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5272. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5273. nread = 0;
  5274. } else {
  5275. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5276. return -2;
  5277. }
  5278. } else {
  5279. err = 0;
  5280. }
  5281. } else if (pollres < 0) {
  5282. /* Error */
  5283. return -2;
  5284. } else {
  5285. /* pollres = 0 means timeout */
  5286. nread = 0;
  5287. }
  5288. #elif !defined(NO_SSL)
  5289. } else if (conn->ssl != NULL) {
  5290. int ssl_pending;
  5291. struct mg_pollfd pfd[1];
  5292. int pollres;
  5293. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5294. /* We already know there is no more data buffered in conn->buf
  5295. * but there is more available in the SSL layer. So don't poll
  5296. * conn->client.sock yet. */
  5297. if (ssl_pending > len) {
  5298. ssl_pending = len;
  5299. }
  5300. pollres = 1;
  5301. } else {
  5302. pfd[0].fd = conn->client.sock;
  5303. pfd[0].events = POLLIN;
  5304. pollres = mg_poll(pfd,
  5305. 1,
  5306. (int)(timeout * 1000.0),
  5307. &(conn->phys_ctx->stop_flag));
  5308. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5309. return -2;
  5310. }
  5311. }
  5312. if (pollres > 0) {
  5313. ERR_clear_error();
  5314. nread =
  5315. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5316. if (nread <= 0) {
  5317. err = SSL_get_error(conn->ssl, nread);
  5318. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5319. err = ERRNO;
  5320. } else if ((err == SSL_ERROR_WANT_READ)
  5321. || (err == SSL_ERROR_WANT_WRITE)) {
  5322. nread = 0;
  5323. } else {
  5324. /* All errors should return -2 */
  5325. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5326. ERR_clear_error();
  5327. return -2;
  5328. }
  5329. ERR_clear_error();
  5330. } else {
  5331. err = 0;
  5332. }
  5333. } else if (pollres < 0) {
  5334. /* Error */
  5335. return -2;
  5336. } else {
  5337. /* pollres = 0 means timeout */
  5338. nread = 0;
  5339. }
  5340. #endif
  5341. } else {
  5342. struct mg_pollfd pfd[1];
  5343. int pollres;
  5344. pfd[0].fd = conn->client.sock;
  5345. pfd[0].events = POLLIN;
  5346. pollres = mg_poll(pfd,
  5347. 1,
  5348. (int)(timeout * 1000.0),
  5349. &(conn->phys_ctx->stop_flag));
  5350. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5351. return -2;
  5352. }
  5353. if (pollres > 0) {
  5354. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5355. err = (nread < 0) ? ERRNO : 0;
  5356. if (nread <= 0) {
  5357. /* shutdown of the socket at client side */
  5358. return -2;
  5359. }
  5360. } else if (pollres < 0) {
  5361. /* error callint poll */
  5362. return -2;
  5363. } else {
  5364. /* pollres = 0 means timeout */
  5365. nread = 0;
  5366. }
  5367. }
  5368. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5369. return -2;
  5370. }
  5371. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5372. /* some data has been read, or no data was requested */
  5373. return nread;
  5374. }
  5375. if (nread < 0) {
  5376. /* socket error - check errno */
  5377. #if defined(_WIN32)
  5378. if (err == WSAEWOULDBLOCK) {
  5379. /* TODO (low): check if this is still required */
  5380. /* standard case if called from close_socket_gracefully */
  5381. return -2;
  5382. } else if (err == WSAETIMEDOUT) {
  5383. /* TODO (low): check if this is still required */
  5384. /* timeout is handled by the while loop */
  5385. return 0;
  5386. } else if (err == WSAECONNABORTED) {
  5387. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5388. return -2;
  5389. } else {
  5390. DEBUG_TRACE("recv() failed, error %d", err);
  5391. return -2;
  5392. }
  5393. #else
  5394. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5395. * if the timeout is reached and if the socket was set to non-
  5396. * blocking in close_socket_gracefully, so we can not distinguish
  5397. * here. We have to wait for the timeout in both cases for now.
  5398. */
  5399. if (ERROR_TRY_AGAIN(err)) {
  5400. /* TODO (low): check if this is still required */
  5401. /* EAGAIN/EWOULDBLOCK:
  5402. * standard case if called from close_socket_gracefully
  5403. * => should return -1 */
  5404. /* or timeout occurred
  5405. * => the code must stay in the while loop */
  5406. /* EINTR can be generated on a socket with a timeout set even
  5407. * when SA_RESTART is effective for all relevant signals
  5408. * (see signal(7)).
  5409. * => stay in the while loop */
  5410. } else {
  5411. DEBUG_TRACE("recv() failed, error %d", err);
  5412. return -2;
  5413. }
  5414. #endif
  5415. }
  5416. /* Timeout occurred, but no data available. */
  5417. return -1;
  5418. }
  5419. static int
  5420. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5421. {
  5422. int n, nread = 0;
  5423. double timeout = -1.0;
  5424. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5425. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5426. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5427. }
  5428. if (timeout <= 0.0) {
  5429. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5430. / 1000.0;
  5431. }
  5432. start_time = mg_get_current_time_ns();
  5433. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5434. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5435. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5436. if (n == -2) {
  5437. if (nread == 0) {
  5438. nread = -1; /* Propagate the error */
  5439. }
  5440. break;
  5441. } else if (n == -1) {
  5442. /* timeout */
  5443. if (timeout >= 0.0) {
  5444. now = mg_get_current_time_ns();
  5445. if ((now - start_time) <= timeout_ns) {
  5446. continue;
  5447. }
  5448. }
  5449. break;
  5450. } else if (n == 0) {
  5451. break; /* No more data to read */
  5452. } else {
  5453. nread += n;
  5454. len -= n;
  5455. }
  5456. }
  5457. return nread;
  5458. }
  5459. static void
  5460. discard_unread_request_data(struct mg_connection *conn)
  5461. {
  5462. char buf[MG_BUF_LEN];
  5463. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5464. ;
  5465. }
  5466. static int
  5467. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5468. {
  5469. int64_t content_len, n, buffered_len, nread;
  5470. int64_t len64 =
  5471. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5472. * int, we may not read more
  5473. * bytes */
  5474. const char *body;
  5475. if (conn == NULL) {
  5476. return 0;
  5477. }
  5478. /* If Content-Length is not set for a response with body data,
  5479. * we do not know in advance how much data should be read. */
  5480. content_len = conn->content_len;
  5481. if (content_len < 0) {
  5482. /* The body data is completed when the connection is closed. */
  5483. content_len = INT64_MAX;
  5484. }
  5485. nread = 0;
  5486. if (conn->consumed_content < content_len) {
  5487. /* Adjust number of bytes to read. */
  5488. int64_t left_to_read = content_len - conn->consumed_content;
  5489. if (left_to_read < len64) {
  5490. /* Do not read more than the total content length of the
  5491. * request.
  5492. */
  5493. len64 = left_to_read;
  5494. }
  5495. /* Return buffered data */
  5496. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5497. - conn->consumed_content;
  5498. if (buffered_len > 0) {
  5499. if (len64 < buffered_len) {
  5500. buffered_len = len64;
  5501. }
  5502. body = conn->buf + conn->request_len + conn->consumed_content;
  5503. memcpy(buf, body, (size_t)buffered_len);
  5504. len64 -= buffered_len;
  5505. conn->consumed_content += buffered_len;
  5506. nread += buffered_len;
  5507. buf = (char *)buf + buffered_len;
  5508. }
  5509. /* We have returned all buffered data. Read new data from the remote
  5510. * socket.
  5511. */
  5512. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5513. conn->consumed_content += n;
  5514. nread += n;
  5515. } else {
  5516. nread = ((nread > 0) ? nread : n);
  5517. }
  5518. }
  5519. return (int)nread;
  5520. }
  5521. /* Forward declarations */
  5522. static void handle_request(struct mg_connection *);
  5523. static void log_access(const struct mg_connection *);
  5524. /* Handle request, update statistics and call access log */
  5525. static void
  5526. handle_request_stat_log(struct mg_connection *conn)
  5527. {
  5528. #if defined(USE_SERVER_STATS)
  5529. struct timespec tnow;
  5530. conn->conn_state = 4; /* processing */
  5531. #endif
  5532. handle_request(conn);
  5533. #if defined(USE_SERVER_STATS)
  5534. conn->conn_state = 5; /* processed */
  5535. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5536. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5537. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5538. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5539. conn->num_bytes_sent);
  5540. #endif
  5541. DEBUG_TRACE("%s", "handle_request done");
  5542. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5543. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5544. DEBUG_TRACE("%s", "end_request callback done");
  5545. }
  5546. log_access(conn);
  5547. }
  5548. #if defined(USE_HTTP2)
  5549. #if defined(NO_SSL)
  5550. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5551. #endif
  5552. #define USE_ALPN
  5553. #include "http2.inl"
  5554. /* Not supported with HTTP/2 */
  5555. #define HTTP1_only \
  5556. { \
  5557. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5558. http2_must_use_http1(conn); \
  5559. return; \
  5560. } \
  5561. }
  5562. #else
  5563. #define HTTP1_only
  5564. #endif
  5565. int
  5566. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5567. {
  5568. if (len > INT_MAX) {
  5569. len = INT_MAX;
  5570. }
  5571. if (conn == NULL) {
  5572. return 0;
  5573. }
  5574. if (conn->is_chunked) {
  5575. size_t all_read = 0;
  5576. while (len > 0) {
  5577. if (conn->is_chunked >= 3) {
  5578. /* No more data left to read */
  5579. return 0;
  5580. }
  5581. if (conn->is_chunked != 1) {
  5582. /* Has error */
  5583. return -1;
  5584. }
  5585. if (conn->consumed_content != conn->content_len) {
  5586. /* copy from the current chunk */
  5587. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5588. if (read_ret < 1) {
  5589. /* read error */
  5590. conn->is_chunked = 2;
  5591. return -1;
  5592. }
  5593. all_read += (size_t)read_ret;
  5594. len -= (size_t)read_ret;
  5595. if (conn->consumed_content == conn->content_len) {
  5596. /* Add data bytes in the current chunk have been read,
  5597. * so we are expecting \r\n now. */
  5598. char x[2];
  5599. conn->content_len += 2;
  5600. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5601. || (x[1] != '\n')) {
  5602. /* Protocol violation */
  5603. conn->is_chunked = 2;
  5604. return -1;
  5605. }
  5606. }
  5607. } else {
  5608. /* fetch a new chunk */
  5609. size_t i;
  5610. char lenbuf[64];
  5611. char *end = NULL;
  5612. unsigned long chunkSize = 0;
  5613. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5614. conn->content_len++;
  5615. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5616. lenbuf[i] = 0;
  5617. }
  5618. if ((i > 0) && (lenbuf[i] == '\r')
  5619. && (lenbuf[i - 1] != '\r')) {
  5620. continue;
  5621. }
  5622. if ((i > 1) && (lenbuf[i] == '\n')
  5623. && (lenbuf[i - 1] == '\r')) {
  5624. lenbuf[i + 1] = 0;
  5625. chunkSize = strtoul(lenbuf, &end, 16);
  5626. if (chunkSize == 0) {
  5627. /* regular end of content */
  5628. conn->is_chunked = 3;
  5629. }
  5630. break;
  5631. }
  5632. if (!isxdigit((unsigned char)lenbuf[i])) {
  5633. /* illegal character for chunk length */
  5634. conn->is_chunked = 2;
  5635. return -1;
  5636. }
  5637. }
  5638. if ((end == NULL) || (*end != '\r')) {
  5639. /* chunksize not set correctly */
  5640. conn->is_chunked = 2;
  5641. return -1;
  5642. }
  5643. if (chunkSize == 0) {
  5644. /* try discarding trailer for keep-alive */
  5645. conn->content_len += 2;
  5646. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5647. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5648. conn->is_chunked = 4;
  5649. }
  5650. break;
  5651. }
  5652. /* append a new chunk */
  5653. conn->content_len += (int64_t)chunkSize;
  5654. }
  5655. }
  5656. return (int)all_read;
  5657. }
  5658. return mg_read_inner(conn, buf, len);
  5659. }
  5660. int
  5661. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5662. {
  5663. time_t now;
  5664. int n, total, allowed;
  5665. if (conn == NULL) {
  5666. return 0;
  5667. }
  5668. if (len > INT_MAX) {
  5669. return -1;
  5670. }
  5671. /* Mark connection as "data sent" */
  5672. conn->request_state = 10;
  5673. #if defined(USE_HTTP2)
  5674. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5675. http2_data_frame_head(conn, len, 0);
  5676. }
  5677. #endif
  5678. if (conn->throttle > 0) {
  5679. if ((now = time(NULL)) != conn->last_throttle_time) {
  5680. conn->last_throttle_time = now;
  5681. conn->last_throttle_bytes = 0;
  5682. }
  5683. allowed = conn->throttle - conn->last_throttle_bytes;
  5684. if (allowed > (int)len) {
  5685. allowed = (int)len;
  5686. }
  5687. total = push_all(conn->phys_ctx,
  5688. NULL,
  5689. conn->client.sock,
  5690. conn->ssl,
  5691. (const char *)buf,
  5692. allowed);
  5693. if (total == allowed) {
  5694. buf = (const char *)buf + total;
  5695. conn->last_throttle_bytes += total;
  5696. while ((total < (int)len)
  5697. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5698. allowed = (conn->throttle > ((int)len - total))
  5699. ? (int)len - total
  5700. : conn->throttle;
  5701. n = push_all(conn->phys_ctx,
  5702. NULL,
  5703. conn->client.sock,
  5704. conn->ssl,
  5705. (const char *)buf,
  5706. allowed);
  5707. if (n != allowed) {
  5708. break;
  5709. }
  5710. sleep(1);
  5711. conn->last_throttle_bytes = allowed;
  5712. conn->last_throttle_time = time(NULL);
  5713. buf = (const char *)buf + n;
  5714. total += n;
  5715. }
  5716. }
  5717. } else {
  5718. total = push_all(conn->phys_ctx,
  5719. NULL,
  5720. conn->client.sock,
  5721. conn->ssl,
  5722. (const char *)buf,
  5723. (int)len);
  5724. }
  5725. if (total > 0) {
  5726. conn->num_bytes_sent += total;
  5727. }
  5728. return total;
  5729. }
  5730. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5731. int
  5732. mg_send_chunk(struct mg_connection *conn,
  5733. const char *chunk,
  5734. unsigned int chunk_len)
  5735. {
  5736. char lenbuf[16];
  5737. size_t lenbuf_len;
  5738. int ret;
  5739. int t;
  5740. /* First store the length information in a text buffer. */
  5741. sprintf(lenbuf, "%x\r\n", chunk_len);
  5742. lenbuf_len = strlen(lenbuf);
  5743. /* Then send length information, chunk and terminating \r\n. */
  5744. ret = mg_write(conn, lenbuf, lenbuf_len);
  5745. if (ret != (int)lenbuf_len) {
  5746. return -1;
  5747. }
  5748. t = ret;
  5749. ret = mg_write(conn, chunk, chunk_len);
  5750. if (ret != (int)chunk_len) {
  5751. return -1;
  5752. }
  5753. t += ret;
  5754. ret = mg_write(conn, "\r\n", 2);
  5755. if (ret != 2) {
  5756. return -1;
  5757. }
  5758. t += ret;
  5759. return t;
  5760. }
  5761. #if defined(GCC_DIAGNOSTIC)
  5762. /* This block forwards format strings to printf implementations,
  5763. * so we need to disable the format-nonliteral warning. */
  5764. #pragma GCC diagnostic push
  5765. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5766. #endif
  5767. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5768. static int
  5769. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5770. {
  5771. va_list ap_copy;
  5772. size_t size = MG_BUF_LEN / 4;
  5773. int len = -1;
  5774. *buf = NULL;
  5775. while (len < 0) {
  5776. if (*buf) {
  5777. mg_free(*buf);
  5778. }
  5779. size *= 4;
  5780. *buf = (char *)mg_malloc(size);
  5781. if (!*buf) {
  5782. break;
  5783. }
  5784. va_copy(ap_copy, ap);
  5785. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5786. va_end(ap_copy);
  5787. (*buf)[size - 1] = 0;
  5788. }
  5789. return len;
  5790. }
  5791. /* Print message to buffer. If buffer is large enough to hold the message,
  5792. * return buffer. If buffer is to small, allocate large enough buffer on
  5793. * heap,
  5794. * and return allocated buffer. */
  5795. static int
  5796. alloc_vprintf(char **out_buf,
  5797. char *prealloc_buf,
  5798. size_t prealloc_size,
  5799. const char *fmt,
  5800. va_list ap)
  5801. {
  5802. va_list ap_copy;
  5803. int len;
  5804. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5805. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5806. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5807. * Therefore, we make two passes: on first pass, get required message
  5808. * length.
  5809. * On second pass, actually print the message. */
  5810. va_copy(ap_copy, ap);
  5811. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5812. va_end(ap_copy);
  5813. if (len < 0) {
  5814. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5815. * Switch to alternative code path that uses incremental
  5816. * allocations.
  5817. */
  5818. va_copy(ap_copy, ap);
  5819. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5820. va_end(ap_copy);
  5821. } else if ((size_t)(len) >= prealloc_size) {
  5822. /* The pre-allocated buffer not large enough. */
  5823. /* Allocate a new buffer. */
  5824. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5825. if (!*out_buf) {
  5826. /* Allocation failed. Return -1 as "out of memory" error. */
  5827. return -1;
  5828. }
  5829. /* Buffer allocation successful. Store the string there. */
  5830. va_copy(ap_copy, ap);
  5831. IGNORE_UNUSED_RESULT(
  5832. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5833. va_end(ap_copy);
  5834. } else {
  5835. /* The pre-allocated buffer is large enough.
  5836. * Use it to store the string and return the address. */
  5837. va_copy(ap_copy, ap);
  5838. IGNORE_UNUSED_RESULT(
  5839. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5840. va_end(ap_copy);
  5841. *out_buf = prealloc_buf;
  5842. }
  5843. return len;
  5844. }
  5845. static int
  5846. alloc_printf(char **out_buf, const char *fmt, ...)
  5847. {
  5848. va_list ap;
  5849. int result;
  5850. va_start(ap, fmt);
  5851. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5852. va_end(ap);
  5853. return result;
  5854. }
  5855. #if defined(GCC_DIAGNOSTIC)
  5856. /* Enable format-nonliteral warning again. */
  5857. #pragma GCC diagnostic pop
  5858. #endif
  5859. static int
  5860. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5861. {
  5862. char mem[MG_BUF_LEN];
  5863. char *buf = NULL;
  5864. int len;
  5865. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5866. len = mg_write(conn, buf, (size_t)len);
  5867. }
  5868. if (buf != mem) {
  5869. mg_free(buf);
  5870. }
  5871. return len;
  5872. }
  5873. int
  5874. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5875. {
  5876. va_list ap;
  5877. int result;
  5878. va_start(ap, fmt);
  5879. result = mg_vprintf(conn, fmt, ap);
  5880. va_end(ap);
  5881. return result;
  5882. }
  5883. int
  5884. mg_url_decode(const char *src,
  5885. int src_len,
  5886. char *dst,
  5887. int dst_len,
  5888. int is_form_url_encoded)
  5889. {
  5890. int i, j, a, b;
  5891. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5892. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5893. if ((i < src_len - 2) && (src[i] == '%')
  5894. && isxdigit((unsigned char)src[i + 1])
  5895. && isxdigit((unsigned char)src[i + 2])) {
  5896. a = tolower((unsigned char)src[i + 1]);
  5897. b = tolower((unsigned char)src[i + 2]);
  5898. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5899. i += 2;
  5900. } else if (is_form_url_encoded && (src[i] == '+')) {
  5901. dst[j] = ' ';
  5902. } else {
  5903. dst[j] = src[i];
  5904. }
  5905. }
  5906. dst[j] = '\0'; /* Null-terminate the destination */
  5907. return (i >= src_len) ? j : -1;
  5908. }
  5909. /* form url decoding of an entire string */
  5910. static void
  5911. url_decode_in_place(char *buf)
  5912. {
  5913. int len = (int)strlen(buf);
  5914. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5915. }
  5916. int
  5917. mg_get_var(const char *data,
  5918. size_t data_len,
  5919. const char *name,
  5920. char *dst,
  5921. size_t dst_len)
  5922. {
  5923. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5924. }
  5925. int
  5926. mg_get_var2(const char *data,
  5927. size_t data_len,
  5928. const char *name,
  5929. char *dst,
  5930. size_t dst_len,
  5931. size_t occurrence)
  5932. {
  5933. const char *p, *e, *s;
  5934. size_t name_len;
  5935. int len;
  5936. if ((dst == NULL) || (dst_len == 0)) {
  5937. len = -2;
  5938. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5939. len = -1;
  5940. dst[0] = '\0';
  5941. } else {
  5942. name_len = strlen(name);
  5943. e = data + data_len;
  5944. len = -1;
  5945. dst[0] = '\0';
  5946. /* data is "var1=val1&var2=val2...". Find variable first */
  5947. for (p = data; p + name_len < e; p++) {
  5948. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5949. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5950. /* Point p to variable value */
  5951. p += name_len + 1;
  5952. /* Point s to the end of the value */
  5953. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5954. if (s == NULL) {
  5955. s = e;
  5956. }
  5957. DEBUG_ASSERT(s >= p);
  5958. if (s < p) {
  5959. return -3;
  5960. }
  5961. /* Decode variable into destination buffer */
  5962. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5963. /* Redirect error code from -1 to -2 (destination buffer too
  5964. * small). */
  5965. if (len == -1) {
  5966. len = -2;
  5967. }
  5968. break;
  5969. }
  5970. }
  5971. }
  5972. return len;
  5973. }
  5974. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5975. int
  5976. mg_split_form_urlencoded(char *data,
  5977. struct mg_header *form_fields,
  5978. unsigned num_form_fields)
  5979. {
  5980. char *b;
  5981. int i;
  5982. int num = 0;
  5983. if (data == NULL) {
  5984. /* parameter error */
  5985. return -1;
  5986. }
  5987. if ((form_fields == NULL) && (num_form_fields == 0)) {
  5988. /* determine the number of expected fields */
  5989. if (data[0] == 0) {
  5990. return 0;
  5991. }
  5992. /* count number of & to return the number of key-value-pairs */
  5993. num = 1;
  5994. while (*data) {
  5995. if (*data == '&') {
  5996. num++;
  5997. }
  5998. data++;
  5999. }
  6000. return num;
  6001. }
  6002. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6003. /* parameter error */
  6004. return -1;
  6005. }
  6006. for (i = 0; i < (int)num_form_fields; i++) {
  6007. /* extract key-value pairs from input data */
  6008. while ((*data == ' ') || (*data == '\t')) {
  6009. /* skip initial spaces */
  6010. data++;
  6011. }
  6012. if (*data == 0) {
  6013. /* end of string reached */
  6014. break;
  6015. }
  6016. form_fields[num].name = data;
  6017. /* find & or = */
  6018. b = data;
  6019. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6020. b++;
  6021. }
  6022. if (*b == 0) {
  6023. /* last key without value */
  6024. form_fields[num].value = NULL;
  6025. } else if (*b == '&') {
  6026. /* mid key without value */
  6027. form_fields[num].value = NULL;
  6028. } else {
  6029. /* terminate string */
  6030. *b = 0;
  6031. /* value starts after '=' */
  6032. data = b + 1;
  6033. form_fields[num].value = data;
  6034. }
  6035. /* new field is stored */
  6036. num++;
  6037. /* find a next key */
  6038. b = strchr(data, '&');
  6039. if (b == 0) {
  6040. /* no more data */
  6041. break;
  6042. } else {
  6043. /* terminate value of last field at '&' */
  6044. *b = 0;
  6045. /* next key-value-pairs starts after '&' */
  6046. data = b + 1;
  6047. }
  6048. }
  6049. /* Decode all values */
  6050. for (i = 0; i < num; i++) {
  6051. if (form_fields[i].name) {
  6052. url_decode_in_place((char *)form_fields[i].name);
  6053. }
  6054. if (form_fields[i].value) {
  6055. url_decode_in_place((char *)form_fields[i].value);
  6056. }
  6057. }
  6058. /* return number of fields found */
  6059. return num;
  6060. }
  6061. /* HCP24: some changes to compare whole var_name */
  6062. int
  6063. mg_get_cookie(const char *cookie_header,
  6064. const char *var_name,
  6065. char *dst,
  6066. size_t dst_size)
  6067. {
  6068. const char *s, *p, *end;
  6069. int name_len, len = -1;
  6070. if ((dst == NULL) || (dst_size == 0)) {
  6071. return -2;
  6072. }
  6073. dst[0] = '\0';
  6074. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6075. return -1;
  6076. }
  6077. name_len = (int)strlen(var_name);
  6078. end = s + strlen(s);
  6079. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6080. if (s[name_len] == '=') {
  6081. /* HCP24: now check is it a substring or a full cookie name */
  6082. if ((s == cookie_header) || (s[-1] == ' ')) {
  6083. s += name_len + 1;
  6084. if ((p = strchr(s, ' ')) == NULL) {
  6085. p = end;
  6086. }
  6087. if (p[-1] == ';') {
  6088. p--;
  6089. }
  6090. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6091. s++;
  6092. p--;
  6093. }
  6094. if ((size_t)(p - s) < dst_size) {
  6095. len = (int)(p - s);
  6096. mg_strlcpy(dst, s, (size_t)len + 1);
  6097. } else {
  6098. len = -3;
  6099. }
  6100. break;
  6101. }
  6102. }
  6103. }
  6104. return len;
  6105. }
  6106. int
  6107. mg_base64_encode(const unsigned char *src,
  6108. size_t src_len,
  6109. char *dst,
  6110. size_t *dst_len)
  6111. {
  6112. static const char *b64 =
  6113. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6114. size_t i, j;
  6115. int a, b, c;
  6116. if (dst_len != NULL) {
  6117. /* Expected length including 0 termination: */
  6118. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6119. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6120. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6121. if (*dst_len < expected_len) {
  6122. if (*dst_len > 0) {
  6123. dst[0] = '\0';
  6124. }
  6125. *dst_len = expected_len;
  6126. return 0;
  6127. }
  6128. }
  6129. for (i = j = 0; i < src_len; i += 3) {
  6130. a = src[i];
  6131. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6132. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6133. dst[j++] = b64[a >> 2];
  6134. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6135. if (i + 1 < src_len) {
  6136. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6137. }
  6138. if (i + 2 < src_len) {
  6139. dst[j++] = b64[c & 63];
  6140. }
  6141. }
  6142. while (j % 4 != 0) {
  6143. dst[j++] = '=';
  6144. }
  6145. dst[j++] = '\0';
  6146. if (dst_len != NULL) {
  6147. *dst_len = (size_t)j;
  6148. }
  6149. /* Return -1 for "OK" */
  6150. return -1;
  6151. }
  6152. static unsigned char
  6153. b64reverse(char letter)
  6154. {
  6155. if ((letter >= 'A') && (letter <= 'Z')) {
  6156. return letter - 'A';
  6157. }
  6158. if ((letter >= 'a') && (letter <= 'z')) {
  6159. return letter - 'a' + 26;
  6160. }
  6161. if ((letter >= '0') && (letter <= '9')) {
  6162. return letter - '0' + 52;
  6163. }
  6164. if (letter == '+') {
  6165. return 62;
  6166. }
  6167. if (letter == '/') {
  6168. return 63;
  6169. }
  6170. if (letter == '=') {
  6171. return 255; /* normal end */
  6172. }
  6173. return 254; /* error */
  6174. }
  6175. int
  6176. mg_base64_decode(const char *src,
  6177. size_t src_len,
  6178. unsigned char *dst,
  6179. size_t *dst_len)
  6180. {
  6181. size_t i;
  6182. unsigned char a, b, c, d;
  6183. size_t dst_len_limit = (size_t)-1;
  6184. size_t dst_len_used = 0;
  6185. if (dst_len != NULL) {
  6186. dst_len_limit = *dst_len;
  6187. *dst_len = 0;
  6188. }
  6189. for (i = 0; i < src_len; i += 4) {
  6190. /* Read 4 characters from BASE64 string */
  6191. a = b64reverse(src[i]);
  6192. if (a >= 254) {
  6193. return i;
  6194. }
  6195. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6196. if (b >= 254) {
  6197. return i + 1;
  6198. }
  6199. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6200. if (c == 254) {
  6201. return i + 2;
  6202. }
  6203. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6204. if (d == 254) {
  6205. return i + 3;
  6206. }
  6207. /* Add first (of 3) decoded character */
  6208. if (dst_len_used < dst_len_limit) {
  6209. dst[dst_len_used] = (a << 2) + (b >> 4);
  6210. }
  6211. dst_len_used++;
  6212. if (c != 255) {
  6213. if (dst_len_used < dst_len_limit) {
  6214. dst[dst_len_used] = (b << 4) + (c >> 2);
  6215. }
  6216. dst_len_used++;
  6217. if (d != 255) {
  6218. if (dst_len_used < dst_len_limit) {
  6219. dst[dst_len_used] = (c << 6) + d;
  6220. }
  6221. dst_len_used++;
  6222. }
  6223. }
  6224. }
  6225. /* Add terminating zero */
  6226. if (dst_len_used < dst_len_limit) {
  6227. dst[dst_len_used] = '\0';
  6228. }
  6229. dst_len_used++;
  6230. if (dst_len != NULL) {
  6231. *dst_len = dst_len_used;
  6232. }
  6233. if (dst_len_used > dst_len_limit) {
  6234. /* Out of memory */
  6235. return 0;
  6236. }
  6237. /* Return -1 for "OK" */
  6238. return -1;
  6239. }
  6240. static int
  6241. is_put_or_delete_method(const struct mg_connection *conn)
  6242. {
  6243. if (conn) {
  6244. const char *s = conn->request_info.request_method;
  6245. return (s != NULL)
  6246. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6247. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6248. }
  6249. return 0;
  6250. }
  6251. #if !defined(NO_FILES)
  6252. static int
  6253. extention_matches_script(
  6254. struct mg_connection *conn, /* in: request (must be valid) */
  6255. const char *filename /* in: filename (must be valid) */
  6256. )
  6257. {
  6258. #if !defined(NO_CGI)
  6259. unsigned char cgi_config_idx, inc, max;
  6260. #endif
  6261. #if defined(USE_LUA)
  6262. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6263. filename)
  6264. > 0) {
  6265. return 1;
  6266. }
  6267. #endif
  6268. #if defined(USE_DUKTAPE)
  6269. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6270. filename)
  6271. > 0) {
  6272. return 1;
  6273. }
  6274. #endif
  6275. #if !defined(NO_CGI)
  6276. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6277. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6278. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6279. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6280. && (match_prefix_strlen(
  6281. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6282. filename)
  6283. > 0)) {
  6284. return 1;
  6285. }
  6286. }
  6287. #endif
  6288. /* filename and conn could be unused, if all preocessor conditions
  6289. * are false (no script language supported). */
  6290. (void)filename;
  6291. (void)conn;
  6292. return 0;
  6293. }
  6294. static int
  6295. extention_matches_template_text(
  6296. struct mg_connection *conn, /* in: request (must be valid) */
  6297. const char *filename /* in: filename (must be valid) */
  6298. )
  6299. {
  6300. #if defined(USE_LUA)
  6301. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6302. filename)
  6303. > 0) {
  6304. return 1;
  6305. }
  6306. #endif
  6307. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6308. > 0) {
  6309. return 1;
  6310. }
  6311. return 0;
  6312. }
  6313. /* For given directory path, substitute it to valid index file.
  6314. * Return 1 if index file has been found, 0 if not found.
  6315. * If the file is found, it's stats is returned in stp. */
  6316. static int
  6317. substitute_index_file(struct mg_connection *conn,
  6318. char *path,
  6319. size_t path_len,
  6320. struct mg_file_stat *filestat)
  6321. {
  6322. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6323. struct vec filename_vec;
  6324. size_t n = strlen(path);
  6325. int found = 0;
  6326. /* The 'path' given to us points to the directory. Remove all trailing
  6327. * directory separator characters from the end of the path, and
  6328. * then append single directory separator character. */
  6329. while ((n > 0) && (path[n - 1] == '/')) {
  6330. n--;
  6331. }
  6332. path[n] = '/';
  6333. /* Traverse index files list. For each entry, append it to the given
  6334. * path and see if the file exists. If it exists, break the loop */
  6335. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6336. /* Ignore too long entries that may overflow path buffer */
  6337. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6338. continue;
  6339. }
  6340. /* Prepare full path to the index file */
  6341. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6342. /* Does it exist? */
  6343. if (mg_stat(conn, path, filestat)) {
  6344. /* Yes it does, break the loop */
  6345. found = 1;
  6346. break;
  6347. }
  6348. }
  6349. /* If no index file exists, restore directory path */
  6350. if (!found) {
  6351. path[n] = '\0';
  6352. }
  6353. return found;
  6354. }
  6355. #endif
  6356. static void
  6357. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6358. char *filename, /* out: filename */
  6359. size_t filename_buf_len, /* in: size of filename buffer */
  6360. struct mg_file_stat *filestat, /* out: file status structure */
  6361. int *is_found, /* out: file found (directly) */
  6362. int *is_script_resource, /* out: handled by a script? */
  6363. int *is_websocket_request, /* out: websocket connetion? */
  6364. int *is_put_or_delete_request, /* out: put/delete a file? */
  6365. int *is_template_text /* out: SSI file or LSP file? */
  6366. )
  6367. {
  6368. char const *accept_encoding;
  6369. #if !defined(NO_FILES)
  6370. const char *uri = conn->request_info.local_uri;
  6371. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6372. const char *rewrite;
  6373. struct vec a, b;
  6374. ptrdiff_t match_len;
  6375. char gz_path[UTF8_PATH_MAX];
  6376. int truncated;
  6377. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6378. char *tmp_str;
  6379. size_t tmp_str_len, sep_pos;
  6380. int allow_substitute_script_subresources;
  6381. #endif
  6382. #else
  6383. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6384. #endif
  6385. /* Step 1: Set all initially unknown outputs to zero */
  6386. memset(filestat, 0, sizeof(*filestat));
  6387. *filename = 0;
  6388. *is_found = 0;
  6389. *is_script_resource = 0;
  6390. *is_template_text = 0;
  6391. /* Step 2: Check if the request attempts to modify the file system */
  6392. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6393. /* Step 3: Check if it is a websocket request, and modify the document
  6394. * root if required */
  6395. #if defined(USE_WEBSOCKET)
  6396. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6397. #if !defined(NO_FILES)
  6398. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6399. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6400. }
  6401. #endif /* !NO_FILES */
  6402. #else /* USE_WEBSOCKET */
  6403. *is_websocket_request = 0;
  6404. #endif /* USE_WEBSOCKET */
  6405. /* Step 4: Check if gzip encoded response is allowed */
  6406. conn->accept_gzip = 0;
  6407. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6408. if (strstr(accept_encoding, "gzip") != NULL) {
  6409. conn->accept_gzip = 1;
  6410. }
  6411. }
  6412. #if !defined(NO_FILES)
  6413. /* Step 5: If there is no root directory, don't look for files. */
  6414. /* Note that root == NULL is a regular use case here. This occurs,
  6415. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6416. * config is not required. */
  6417. if (root == NULL) {
  6418. /* all file related outputs have already been set to 0, just return
  6419. */
  6420. return;
  6421. }
  6422. /* Step 6: Determine the local file path from the root path and the
  6423. * request uri. */
  6424. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6425. * part of the path one byte on the right. */
  6426. truncated = 0;
  6427. mg_snprintf(
  6428. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6429. if (truncated) {
  6430. goto interpret_cleanup;
  6431. }
  6432. /* Step 7: URI rewriting */
  6433. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6434. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6435. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6436. mg_snprintf(conn,
  6437. &truncated,
  6438. filename,
  6439. filename_buf_len - 1,
  6440. "%.*s%s",
  6441. (int)b.len,
  6442. b.ptr,
  6443. uri + match_len);
  6444. break;
  6445. }
  6446. }
  6447. if (truncated) {
  6448. goto interpret_cleanup;
  6449. }
  6450. /* Step 8: Check if the file exists at the server */
  6451. /* Local file path and name, corresponding to requested URI
  6452. * is now stored in "filename" variable. */
  6453. if (mg_stat(conn, filename, filestat)) {
  6454. int uri_len = (int)strlen(uri);
  6455. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6456. /* 8.1: File exists. */
  6457. *is_found = 1;
  6458. /* 8.2: Check if it is a script type. */
  6459. if (extention_matches_script(conn, filename)) {
  6460. /* The request addresses a CGI resource, Lua script or
  6461. * server-side javascript.
  6462. * The URI corresponds to the script itself (like
  6463. * /path/script.cgi), and there is no additional resource
  6464. * path (like /path/script.cgi/something).
  6465. * Requests that modify (replace or delete) a resource, like
  6466. * PUT and DELETE requests, should replace/delete the script
  6467. * file.
  6468. * Requests that read or write from/to a resource, like GET and
  6469. * POST requests, should call the script and return the
  6470. * generated response. */
  6471. *is_script_resource = (!*is_put_or_delete_request);
  6472. }
  6473. /* 8.3: Check for SSI and LSP files */
  6474. if (extention_matches_template_text(conn, filename)) {
  6475. /* Same as above, but for *.lsp and *.shtml files. */
  6476. /* A "template text" is a file delivered directly to the client,
  6477. * but with some text tags replaced by dynamic content.
  6478. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6479. * (LP, LSP) file. */
  6480. *is_template_text = (!*is_put_or_delete_request);
  6481. }
  6482. /* 8.4: If the request target is a directory, there could be
  6483. * a substitute file (index.html, index.cgi, ...). */
  6484. if (filestat->is_directory && is_uri_end_slash) {
  6485. /* Use a local copy here, since substitute_index_file will
  6486. * change the content of the file status */
  6487. struct mg_file_stat tmp_filestat;
  6488. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6489. if (substitute_index_file(
  6490. conn, filename, filename_buf_len, &tmp_filestat)) {
  6491. /* Substitute file found. Copy stat to the output, then
  6492. * check if the file is a script file */
  6493. *filestat = tmp_filestat;
  6494. if (extention_matches_script(conn, filename)) {
  6495. /* Substitute file is a script file */
  6496. *is_script_resource = 1;
  6497. } else if (extention_matches_template_text(conn, filename)) {
  6498. /* Substitute file is a LSP or SSI file */
  6499. *is_template_text = 1;
  6500. } else {
  6501. /* Substitute file is a regular file */
  6502. *is_script_resource = 0;
  6503. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6504. }
  6505. }
  6506. /* If there is no substitute file, the server could return
  6507. * a directory listing in a later step */
  6508. }
  6509. return;
  6510. }
  6511. /* Step 9: Check for zipped files: */
  6512. /* If we can't find the actual file, look for the file
  6513. * with the same name but a .gz extension. If we find it,
  6514. * use that and set the gzipped flag in the file struct
  6515. * to indicate that the response need to have the content-
  6516. * encoding: gzip header.
  6517. * We can only do this if the browser declares support. */
  6518. if (conn->accept_gzip) {
  6519. mg_snprintf(
  6520. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6521. if (truncated) {
  6522. goto interpret_cleanup;
  6523. }
  6524. if (mg_stat(conn, gz_path, filestat)) {
  6525. if (filestat) {
  6526. filestat->is_gzipped = 1;
  6527. *is_found = 1;
  6528. }
  6529. /* Currently gz files can not be scripts. */
  6530. return;
  6531. }
  6532. }
  6533. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6534. /* Step 10: Script resources may handle sub-resources */
  6535. /* Support PATH_INFO for CGI scripts. */
  6536. tmp_str_len = strlen(filename);
  6537. tmp_str =
  6538. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6539. if (!tmp_str) {
  6540. /* Out of memory */
  6541. goto interpret_cleanup;
  6542. }
  6543. memcpy(tmp_str, filename, tmp_str_len + 1);
  6544. /* Check config, if index scripts may have sub-resources */
  6545. allow_substitute_script_subresources =
  6546. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6547. "yes");
  6548. sep_pos = tmp_str_len;
  6549. while (sep_pos > 0) {
  6550. sep_pos--;
  6551. if (tmp_str[sep_pos] == '/') {
  6552. int is_script = 0, does_exist = 0;
  6553. tmp_str[sep_pos] = 0;
  6554. if (tmp_str[0]) {
  6555. is_script = extention_matches_script(conn, tmp_str);
  6556. does_exist = mg_stat(conn, tmp_str, filestat);
  6557. }
  6558. if (does_exist && is_script) {
  6559. filename[sep_pos] = 0;
  6560. memmove(filename + sep_pos + 2,
  6561. filename + sep_pos + 1,
  6562. strlen(filename + sep_pos + 1) + 1);
  6563. conn->path_info = filename + sep_pos + 1;
  6564. filename[sep_pos + 1] = '/';
  6565. *is_script_resource = 1;
  6566. *is_found = 1;
  6567. break;
  6568. }
  6569. if (allow_substitute_script_subresources) {
  6570. if (substitute_index_file(
  6571. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6572. /* some intermediate directory has an index file */
  6573. if (extention_matches_script(conn, tmp_str)) {
  6574. size_t script_name_len = strlen(tmp_str);
  6575. /* subres_name read before this memory locatio will be
  6576. overwritten */
  6577. char *subres_name = filename + sep_pos;
  6578. size_t subres_name_len = strlen(subres_name);
  6579. DEBUG_TRACE("Substitute script %s serving path %s",
  6580. tmp_str,
  6581. filename);
  6582. /* this index file is a script */
  6583. if ((script_name_len + subres_name_len + 2)
  6584. >= filename_buf_len) {
  6585. mg_free(tmp_str);
  6586. goto interpret_cleanup;
  6587. }
  6588. conn->path_info =
  6589. filename + script_name_len + 1; /* new target */
  6590. memmove(conn->path_info, subres_name, subres_name_len);
  6591. conn->path_info[subres_name_len] = 0;
  6592. memcpy(filename, tmp_str, script_name_len + 1);
  6593. *is_script_resource = 1;
  6594. *is_found = 1;
  6595. break;
  6596. } else {
  6597. DEBUG_TRACE("Substitute file %s serving path %s",
  6598. tmp_str,
  6599. filename);
  6600. /* non-script files will not have sub-resources */
  6601. filename[sep_pos] = 0;
  6602. conn->path_info = 0;
  6603. *is_script_resource = 0;
  6604. *is_found = 0;
  6605. break;
  6606. }
  6607. }
  6608. }
  6609. tmp_str[sep_pos] = '/';
  6610. }
  6611. }
  6612. mg_free(tmp_str);
  6613. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6614. #endif /* !defined(NO_FILES) */
  6615. return;
  6616. #if !defined(NO_FILES)
  6617. /* Reset all outputs */
  6618. interpret_cleanup:
  6619. memset(filestat, 0, sizeof(*filestat));
  6620. *filename = 0;
  6621. *is_found = 0;
  6622. *is_script_resource = 0;
  6623. *is_websocket_request = 0;
  6624. *is_put_or_delete_request = 0;
  6625. #endif /* !defined(NO_FILES) */
  6626. }
  6627. /* Check whether full request is buffered. Return:
  6628. * -1 if request or response is malformed
  6629. * 0 if request or response is not yet fully buffered
  6630. * >0 actual request length, including last \r\n\r\n */
  6631. static int
  6632. get_http_header_len(const char *buf, int buflen)
  6633. {
  6634. int i;
  6635. for (i = 0; i < buflen; i++) {
  6636. /* Do an unsigned comparison in some conditions below */
  6637. const unsigned char c = (unsigned char)buf[i];
  6638. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6639. && !isprint(c)) {
  6640. /* abort scan as soon as one malformed character is found */
  6641. return -1;
  6642. }
  6643. if (i < buflen - 1) {
  6644. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6645. /* Two newline, no carriage return - not standard compliant,
  6646. * but it should be accepted */
  6647. return i + 2;
  6648. }
  6649. }
  6650. if (i < buflen - 3) {
  6651. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6652. && (buf[i + 3] == '\n')) {
  6653. /* Two \r\n - standard compliant */
  6654. return i + 4;
  6655. }
  6656. }
  6657. }
  6658. return 0;
  6659. }
  6660. #if !defined(NO_CACHING)
  6661. /* Convert month to the month number. Return -1 on error, or month number */
  6662. static int
  6663. get_month_index(const char *s)
  6664. {
  6665. size_t i;
  6666. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6667. if (!strcmp(s, month_names[i])) {
  6668. return (int)i;
  6669. }
  6670. }
  6671. return -1;
  6672. }
  6673. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6674. static time_t
  6675. parse_date_string(const char *datetime)
  6676. {
  6677. char month_str[32] = {0};
  6678. int second, minute, hour, day, month, year;
  6679. time_t result = (time_t)0;
  6680. struct tm tm;
  6681. if ((sscanf(datetime,
  6682. "%d/%3s/%d %d:%d:%d",
  6683. &day,
  6684. month_str,
  6685. &year,
  6686. &hour,
  6687. &minute,
  6688. &second)
  6689. == 6)
  6690. || (sscanf(datetime,
  6691. "%d %3s %d %d:%d:%d",
  6692. &day,
  6693. month_str,
  6694. &year,
  6695. &hour,
  6696. &minute,
  6697. &second)
  6698. == 6)
  6699. || (sscanf(datetime,
  6700. "%*3s, %d %3s %d %d:%d:%d",
  6701. &day,
  6702. month_str,
  6703. &year,
  6704. &hour,
  6705. &minute,
  6706. &second)
  6707. == 6)
  6708. || (sscanf(datetime,
  6709. "%d-%3s-%d %d:%d:%d",
  6710. &day,
  6711. month_str,
  6712. &year,
  6713. &hour,
  6714. &minute,
  6715. &second)
  6716. == 6)) {
  6717. month = get_month_index(month_str);
  6718. if ((month >= 0) && (year >= 1970)) {
  6719. memset(&tm, 0, sizeof(tm));
  6720. tm.tm_year = year - 1900;
  6721. tm.tm_mon = month;
  6722. tm.tm_mday = day;
  6723. tm.tm_hour = hour;
  6724. tm.tm_min = minute;
  6725. tm.tm_sec = second;
  6726. result = timegm(&tm);
  6727. }
  6728. }
  6729. return result;
  6730. }
  6731. #endif /* !NO_CACHING */
  6732. /* Pre-process URIs according to RFC + protect against directory disclosure
  6733. * attacks by removing '..', excessive '/' and '\' characters */
  6734. static void
  6735. remove_dot_segments(char *inout)
  6736. {
  6737. /* Windows backend protection
  6738. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6739. * in URI by slash */
  6740. char *out_end = inout;
  6741. char *in = inout;
  6742. if (!in) {
  6743. /* Param error. */
  6744. return;
  6745. }
  6746. while (*in) {
  6747. if (*in == '\\') {
  6748. *in = '/';
  6749. }
  6750. in++;
  6751. }
  6752. /* Algorithm "remove_dot_segments" from
  6753. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6754. /* Step 1:
  6755. * The input buffer is initialized.
  6756. * The output buffer is initialized to the empty string.
  6757. */
  6758. in = inout;
  6759. /* Step 2:
  6760. * While the input buffer is not empty, loop as follows:
  6761. */
  6762. /* Less than out_end of the inout buffer is used as output, so keep
  6763. * condition: out_end <= in */
  6764. while (*in) {
  6765. /* Step 2a:
  6766. * If the input buffer begins with a prefix of "../" or "./",
  6767. * then remove that prefix from the input buffer;
  6768. */
  6769. if (!strncmp(in, "../", 3)) {
  6770. in += 3;
  6771. } else if (!strncmp(in, "./", 2)) {
  6772. in += 2;
  6773. }
  6774. /* otherwise */
  6775. /* Step 2b:
  6776. * if the input buffer begins with a prefix of "/./" or "/.",
  6777. * where "." is a complete path segment, then replace that
  6778. * prefix with "/" in the input buffer;
  6779. */
  6780. else if (!strncmp(in, "/./", 3)) {
  6781. in += 2;
  6782. } else if (!strcmp(in, "/.")) {
  6783. in[1] = 0;
  6784. }
  6785. /* otherwise */
  6786. /* Step 2c:
  6787. * if the input buffer begins with a prefix of "/../" or "/..",
  6788. * where ".." is a complete path segment, then replace that
  6789. * prefix with "/" in the input buffer and remove the last
  6790. * segment and its preceding "/" (if any) from the output
  6791. * buffer;
  6792. */
  6793. else if (!strncmp(in, "/../", 4)) {
  6794. in += 3;
  6795. if (inout != out_end) {
  6796. /* remove last segment */
  6797. do {
  6798. out_end--;
  6799. } while ((inout != out_end) && (*out_end != '/'));
  6800. }
  6801. } else if (!strcmp(in, "/..")) {
  6802. in[1] = 0;
  6803. if (inout != out_end) {
  6804. /* remove last segment */
  6805. do {
  6806. out_end--;
  6807. } while ((inout != out_end) && (*out_end != '/'));
  6808. }
  6809. }
  6810. /* otherwise */
  6811. /* Step 2d:
  6812. * if the input buffer consists only of "." or "..", then remove
  6813. * that from the input buffer;
  6814. */
  6815. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6816. *in = 0;
  6817. }
  6818. /* otherwise */
  6819. /* Step 2e:
  6820. * move the first path segment in the input buffer to the end of
  6821. * the output buffer, including the initial "/" character (if
  6822. * any) and any subsequent characters up to, but not including,
  6823. * the next "/" character or the end of the input buffer.
  6824. */
  6825. else {
  6826. do {
  6827. *out_end = *in;
  6828. out_end++;
  6829. in++;
  6830. } while ((*in != 0) && (*in != '/'));
  6831. }
  6832. }
  6833. /* Step 3:
  6834. * Finally, the output buffer is returned as the result of
  6835. * remove_dot_segments.
  6836. */
  6837. /* Terminate output */
  6838. *out_end = 0;
  6839. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6840. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6841. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6842. * or "//" anymore.
  6843. */
  6844. out_end = in = inout;
  6845. while (*in) {
  6846. if (*in == '.') {
  6847. /* remove . at the end or preceding of / */
  6848. char *in_ahead = in;
  6849. do {
  6850. in_ahead++;
  6851. } while (*in_ahead == '.');
  6852. if (*in_ahead == '/') {
  6853. in = in_ahead;
  6854. if ((out_end != inout) && (out_end[-1] == '/')) {
  6855. /* remove generated // */
  6856. out_end--;
  6857. }
  6858. } else if (*in_ahead == 0) {
  6859. in = in_ahead;
  6860. } else {
  6861. do {
  6862. *out_end++ = '.';
  6863. in++;
  6864. } while (in != in_ahead);
  6865. }
  6866. } else if (*in == '/') {
  6867. /* replace // by / */
  6868. *out_end++ = '/';
  6869. do {
  6870. in++;
  6871. } while (*in == '/');
  6872. } else {
  6873. *out_end++ = *in;
  6874. in++;
  6875. }
  6876. }
  6877. *out_end = 0;
  6878. }
  6879. static const struct {
  6880. const char *extension;
  6881. size_t ext_len;
  6882. const char *mime_type;
  6883. } builtin_mime_types[] = {
  6884. /* IANA registered MIME types
  6885. * (http://www.iana.org/assignments/media-types)
  6886. * application types */
  6887. {".bin", 4, "application/octet-stream"},
  6888. {".deb", 4, "application/octet-stream"},
  6889. {".dmg", 4, "application/octet-stream"},
  6890. {".dll", 4, "application/octet-stream"},
  6891. {".doc", 4, "application/msword"},
  6892. {".eps", 4, "application/postscript"},
  6893. {".exe", 4, "application/octet-stream"},
  6894. {".iso", 4, "application/octet-stream"},
  6895. {".js", 3, "application/javascript"},
  6896. {".json", 5, "application/json"},
  6897. {".msi", 4, "application/octet-stream"},
  6898. {".pdf", 4, "application/pdf"},
  6899. {".ps", 3, "application/postscript"},
  6900. {".rtf", 4, "application/rtf"},
  6901. {".xhtml", 6, "application/xhtml+xml"},
  6902. {".xsl", 4, "application/xml"},
  6903. {".xslt", 5, "application/xml"},
  6904. /* fonts */
  6905. {".ttf", 4, "application/font-sfnt"},
  6906. {".cff", 4, "application/font-sfnt"},
  6907. {".otf", 4, "application/font-sfnt"},
  6908. {".aat", 4, "application/font-sfnt"},
  6909. {".sil", 4, "application/font-sfnt"},
  6910. {".pfr", 4, "application/font-tdpfr"},
  6911. {".woff", 5, "application/font-woff"},
  6912. {".woff2", 6, "application/font-woff2"},
  6913. /* audio */
  6914. {".mp3", 4, "audio/mpeg"},
  6915. {".oga", 4, "audio/ogg"},
  6916. {".ogg", 4, "audio/ogg"},
  6917. /* image */
  6918. {".gif", 4, "image/gif"},
  6919. {".ief", 4, "image/ief"},
  6920. {".jpeg", 5, "image/jpeg"},
  6921. {".jpg", 4, "image/jpeg"},
  6922. {".jpm", 4, "image/jpm"},
  6923. {".jpx", 4, "image/jpx"},
  6924. {".png", 4, "image/png"},
  6925. {".svg", 4, "image/svg+xml"},
  6926. {".tif", 4, "image/tiff"},
  6927. {".tiff", 5, "image/tiff"},
  6928. /* model */
  6929. {".wrl", 4, "model/vrml"},
  6930. /* text */
  6931. {".css", 4, "text/css"},
  6932. {".csv", 4, "text/csv"},
  6933. {".htm", 4, "text/html"},
  6934. {".html", 5, "text/html"},
  6935. {".sgm", 4, "text/sgml"},
  6936. {".shtm", 5, "text/html"},
  6937. {".shtml", 6, "text/html"},
  6938. {".txt", 4, "text/plain"},
  6939. {".xml", 4, "text/xml"},
  6940. /* video */
  6941. {".mov", 4, "video/quicktime"},
  6942. {".mp4", 4, "video/mp4"},
  6943. {".mpeg", 5, "video/mpeg"},
  6944. {".mpg", 4, "video/mpeg"},
  6945. {".ogv", 4, "video/ogg"},
  6946. {".qt", 3, "video/quicktime"},
  6947. /* not registered types
  6948. * (http://reference.sitepoint.com/html/mime-types-full,
  6949. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6950. {".arj", 4, "application/x-arj-compressed"},
  6951. {".gz", 3, "application/x-gunzip"},
  6952. {".rar", 4, "application/x-arj-compressed"},
  6953. {".swf", 4, "application/x-shockwave-flash"},
  6954. {".tar", 4, "application/x-tar"},
  6955. {".tgz", 4, "application/x-tar-gz"},
  6956. {".torrent", 8, "application/x-bittorrent"},
  6957. {".ppt", 4, "application/x-mspowerpoint"},
  6958. {".xls", 4, "application/x-msexcel"},
  6959. {".zip", 4, "application/x-zip-compressed"},
  6960. {".aac",
  6961. 4,
  6962. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6963. {".flac", 5, "audio/flac"},
  6964. {".aif", 4, "audio/x-aif"},
  6965. {".m3u", 4, "audio/x-mpegurl"},
  6966. {".mid", 4, "audio/x-midi"},
  6967. {".ra", 3, "audio/x-pn-realaudio"},
  6968. {".ram", 4, "audio/x-pn-realaudio"},
  6969. {".wav", 4, "audio/x-wav"},
  6970. {".bmp", 4, "image/bmp"},
  6971. {".ico", 4, "image/x-icon"},
  6972. {".pct", 4, "image/x-pct"},
  6973. {".pict", 5, "image/pict"},
  6974. {".rgb", 4, "image/x-rgb"},
  6975. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6976. {".asf", 4, "video/x-ms-asf"},
  6977. {".avi", 4, "video/x-msvideo"},
  6978. {".m4v", 4, "video/x-m4v"},
  6979. {NULL, 0, NULL}};
  6980. const char *
  6981. mg_get_builtin_mime_type(const char *path)
  6982. {
  6983. const char *ext;
  6984. size_t i, path_len;
  6985. path_len = strlen(path);
  6986. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6987. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6988. if ((path_len > builtin_mime_types[i].ext_len)
  6989. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6990. return builtin_mime_types[i].mime_type;
  6991. }
  6992. }
  6993. return "text/plain";
  6994. }
  6995. /* Look at the "path" extension and figure what mime type it has.
  6996. * Store mime type in the vector. */
  6997. static void
  6998. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6999. {
  7000. struct vec ext_vec, mime_vec;
  7001. const char *list, *ext;
  7002. size_t path_len;
  7003. path_len = strlen(path);
  7004. if ((conn == NULL) || (vec == NULL)) {
  7005. if (vec != NULL) {
  7006. memset(vec, '\0', sizeof(struct vec));
  7007. }
  7008. return;
  7009. }
  7010. /* Scan user-defined mime types first, in case user wants to
  7011. * override default mime types. */
  7012. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7013. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7014. /* ext now points to the path suffix */
  7015. ext = path + path_len - ext_vec.len;
  7016. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7017. *vec = mime_vec;
  7018. return;
  7019. }
  7020. }
  7021. vec->ptr = mg_get_builtin_mime_type(path);
  7022. vec->len = strlen(vec->ptr);
  7023. }
  7024. /* Stringify binary data. Output buffer must be twice as big as input,
  7025. * because each byte takes 2 bytes in string representation */
  7026. static void
  7027. bin2str(char *to, const unsigned char *p, size_t len)
  7028. {
  7029. static const char *hex = "0123456789abcdef";
  7030. for (; len--; p++) {
  7031. *to++ = hex[p[0] >> 4];
  7032. *to++ = hex[p[0] & 0x0f];
  7033. }
  7034. *to = '\0';
  7035. }
  7036. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7037. */
  7038. char *
  7039. mg_md5(char buf[33], ...)
  7040. {
  7041. md5_byte_t hash[16];
  7042. const char *p;
  7043. va_list ap;
  7044. md5_state_t ctx;
  7045. md5_init(&ctx);
  7046. va_start(ap, buf);
  7047. while ((p = va_arg(ap, const char *)) != NULL) {
  7048. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7049. }
  7050. va_end(ap);
  7051. md5_finish(&ctx, hash);
  7052. bin2str(buf, hash, sizeof(hash));
  7053. return buf;
  7054. }
  7055. /* Check the user's password, return 1 if OK */
  7056. static int
  7057. check_password(const char *method,
  7058. const char *ha1,
  7059. const char *uri,
  7060. const char *nonce,
  7061. const char *nc,
  7062. const char *cnonce,
  7063. const char *qop,
  7064. const char *response)
  7065. {
  7066. char ha2[32 + 1], expected_response[32 + 1];
  7067. /* Some of the parameters may be NULL */
  7068. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7069. || (qop == NULL) || (response == NULL)) {
  7070. return 0;
  7071. }
  7072. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7073. if (strlen(response) != 32) {
  7074. return 0;
  7075. }
  7076. mg_md5(ha2, method, ":", uri, NULL);
  7077. mg_md5(expected_response,
  7078. ha1,
  7079. ":",
  7080. nonce,
  7081. ":",
  7082. nc,
  7083. ":",
  7084. cnonce,
  7085. ":",
  7086. qop,
  7087. ":",
  7088. ha2,
  7089. NULL);
  7090. return mg_strcasecmp(response, expected_response) == 0;
  7091. }
  7092. #if !defined(NO_FILESYSTEMS)
  7093. /* Use the global passwords file, if specified by auth_gpass option,
  7094. * or search for .htpasswd in the requested directory. */
  7095. static void
  7096. open_auth_file(struct mg_connection *conn,
  7097. const char *path,
  7098. struct mg_file *filep)
  7099. {
  7100. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7101. char name[UTF8_PATH_MAX];
  7102. const char *p, *e,
  7103. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7104. int truncated;
  7105. if (gpass != NULL) {
  7106. /* Use global passwords file */
  7107. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7108. #if defined(DEBUG)
  7109. /* Use mg_cry_internal here, since gpass has been
  7110. * configured. */
  7111. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7112. #endif
  7113. }
  7114. /* Important: using local struct mg_file to test path for
  7115. * is_directory flag. If filep is used, mg_stat() makes it
  7116. * appear as if auth file was opened.
  7117. * TODO(mid): Check if this is still required after rewriting
  7118. * mg_stat */
  7119. } else if (mg_stat(conn, path, &filep->stat)
  7120. && filep->stat.is_directory) {
  7121. mg_snprintf(conn,
  7122. &truncated,
  7123. name,
  7124. sizeof(name),
  7125. "%s/%s",
  7126. path,
  7127. PASSWORDS_FILE_NAME);
  7128. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7129. #if defined(DEBUG)
  7130. /* Don't use mg_cry_internal here, but only a trace, since
  7131. * this is a typical case. It will occur for every directory
  7132. * without a password file. */
  7133. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7134. #endif
  7135. }
  7136. } else {
  7137. /* Try to find .htpasswd in requested directory. */
  7138. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7139. if (e[0] == '/') {
  7140. break;
  7141. }
  7142. }
  7143. mg_snprintf(conn,
  7144. &truncated,
  7145. name,
  7146. sizeof(name),
  7147. "%.*s/%s",
  7148. (int)(e - p),
  7149. p,
  7150. PASSWORDS_FILE_NAME);
  7151. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7152. #if defined(DEBUG)
  7153. /* Don't use mg_cry_internal here, but only a trace, since
  7154. * this is a typical case. It will occur for every directory
  7155. * without a password file. */
  7156. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7157. #endif
  7158. }
  7159. }
  7160. }
  7161. }
  7162. #endif /* NO_FILESYSTEMS */
  7163. /* Parsed Authorization header */
  7164. struct ah {
  7165. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7166. };
  7167. /* Return 1 on success. Always initializes the ah structure. */
  7168. static int
  7169. parse_auth_header(struct mg_connection *conn,
  7170. char *buf,
  7171. size_t buf_size,
  7172. struct ah *ah)
  7173. {
  7174. char *name, *value, *s;
  7175. const char *auth_header;
  7176. uint64_t nonce;
  7177. if (!ah || !conn) {
  7178. return 0;
  7179. }
  7180. (void)memset(ah, 0, sizeof(*ah));
  7181. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7182. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7183. return 0;
  7184. }
  7185. /* Make modifiable copy of the auth header */
  7186. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7187. s = buf;
  7188. /* Parse authorization header */
  7189. for (;;) {
  7190. /* Gobble initial spaces */
  7191. while (isspace((unsigned char)*s)) {
  7192. s++;
  7193. }
  7194. name = skip_quoted(&s, "=", " ", 0);
  7195. /* Value is either quote-delimited, or ends at first comma or space.
  7196. */
  7197. if (s[0] == '\"') {
  7198. s++;
  7199. value = skip_quoted(&s, "\"", " ", '\\');
  7200. if (s[0] == ',') {
  7201. s++;
  7202. }
  7203. } else {
  7204. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7205. * uses spaces */
  7206. }
  7207. if (*name == '\0') {
  7208. break;
  7209. }
  7210. if (!strcmp(name, "username")) {
  7211. ah->user = value;
  7212. } else if (!strcmp(name, "cnonce")) {
  7213. ah->cnonce = value;
  7214. } else if (!strcmp(name, "response")) {
  7215. ah->response = value;
  7216. } else if (!strcmp(name, "uri")) {
  7217. ah->uri = value;
  7218. } else if (!strcmp(name, "qop")) {
  7219. ah->qop = value;
  7220. } else if (!strcmp(name, "nc")) {
  7221. ah->nc = value;
  7222. } else if (!strcmp(name, "nonce")) {
  7223. ah->nonce = value;
  7224. }
  7225. }
  7226. #if !defined(NO_NONCE_CHECK)
  7227. /* Read the nonce from the response. */
  7228. if (ah->nonce == NULL) {
  7229. return 0;
  7230. }
  7231. s = NULL;
  7232. nonce = strtoull(ah->nonce, &s, 10);
  7233. if ((s == NULL) || (*s != 0)) {
  7234. return 0;
  7235. }
  7236. /* Convert the nonce from the client to a number. */
  7237. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7238. /* The converted number corresponds to the time the nounce has been
  7239. * created. This should not be earlier than the server start. */
  7240. /* Server side nonce check is valuable in all situations but one:
  7241. * if the server restarts frequently, but the client should not see
  7242. * that, so the server should accept nonces from previous starts. */
  7243. /* However, the reasonable default is to not accept a nonce from a
  7244. * previous start, so if anyone changed the access rights between
  7245. * two restarts, a new login is required. */
  7246. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7247. /* nonce is from a previous start of the server and no longer valid
  7248. * (replay attack?) */
  7249. return 0;
  7250. }
  7251. /* Check if the nonce is too high, so it has not (yet) been used by the
  7252. * server. */
  7253. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7254. + conn->dom_ctx->nonce_count)) {
  7255. return 0;
  7256. }
  7257. #else
  7258. (void)nonce;
  7259. #endif
  7260. /* CGI needs it as REMOTE_USER */
  7261. if (ah->user != NULL) {
  7262. conn->request_info.remote_user =
  7263. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7264. } else {
  7265. return 0;
  7266. }
  7267. return 1;
  7268. }
  7269. static const char *
  7270. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7271. {
  7272. if (!filep) {
  7273. return NULL;
  7274. }
  7275. if (filep->access.fp != NULL) {
  7276. return fgets(buf, (int)size, filep->access.fp);
  7277. } else {
  7278. return NULL;
  7279. }
  7280. }
  7281. /* Define the initial recursion depth for procesesing htpasswd files that
  7282. * include other htpasswd
  7283. * (or even the same) files. It is not difficult to provide a file or files
  7284. * s.t. they force civetweb
  7285. * to infinitely recurse and then crash.
  7286. */
  7287. #define INITIAL_DEPTH 9
  7288. #if INITIAL_DEPTH <= 0
  7289. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7290. #endif
  7291. #if !defined(NO_FILESYSTEMS)
  7292. struct read_auth_file_struct {
  7293. struct mg_connection *conn;
  7294. struct ah ah;
  7295. const char *domain;
  7296. char buf[256 + 256 + 40];
  7297. const char *f_user;
  7298. const char *f_domain;
  7299. const char *f_ha1;
  7300. };
  7301. static int
  7302. read_auth_file(struct mg_file *filep,
  7303. struct read_auth_file_struct *workdata,
  7304. int depth)
  7305. {
  7306. int is_authorized = 0;
  7307. struct mg_file fp;
  7308. size_t l;
  7309. if (!filep || !workdata || (0 == depth)) {
  7310. return 0;
  7311. }
  7312. /* Loop over passwords file */
  7313. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7314. l = strlen(workdata->buf);
  7315. while (l > 0) {
  7316. if (isspace((unsigned char)workdata->buf[l - 1])
  7317. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7318. l--;
  7319. workdata->buf[l] = 0;
  7320. } else
  7321. break;
  7322. }
  7323. if (l < 1) {
  7324. continue;
  7325. }
  7326. workdata->f_user = workdata->buf;
  7327. if (workdata->f_user[0] == ':') {
  7328. /* user names may not contain a ':' and may not be empty,
  7329. * so lines starting with ':' may be used for a special purpose
  7330. */
  7331. if (workdata->f_user[1] == '#') {
  7332. /* :# is a comment */
  7333. continue;
  7334. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7335. if (mg_fopen(workdata->conn,
  7336. workdata->f_user + 9,
  7337. MG_FOPEN_MODE_READ,
  7338. &fp)) {
  7339. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7340. (void)mg_fclose(
  7341. &fp.access); /* ignore error on read only file */
  7342. /* No need to continue processing files once we have a
  7343. * match, since nothing will reset it back
  7344. * to 0.
  7345. */
  7346. if (is_authorized) {
  7347. return is_authorized;
  7348. }
  7349. } else {
  7350. mg_cry_internal(workdata->conn,
  7351. "%s: cannot open authorization file: %s",
  7352. __func__,
  7353. workdata->buf);
  7354. }
  7355. continue;
  7356. }
  7357. /* everything is invalid for the moment (might change in the
  7358. * future) */
  7359. mg_cry_internal(workdata->conn,
  7360. "%s: syntax error in authorization file: %s",
  7361. __func__,
  7362. workdata->buf);
  7363. continue;
  7364. }
  7365. workdata->f_domain = strchr(workdata->f_user, ':');
  7366. if (workdata->f_domain == NULL) {
  7367. mg_cry_internal(workdata->conn,
  7368. "%s: syntax error in authorization file: %s",
  7369. __func__,
  7370. workdata->buf);
  7371. continue;
  7372. }
  7373. *(char *)(workdata->f_domain) = 0;
  7374. (workdata->f_domain)++;
  7375. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7376. if (workdata->f_ha1 == NULL) {
  7377. mg_cry_internal(workdata->conn,
  7378. "%s: syntax error in authorization file: %s",
  7379. __func__,
  7380. workdata->buf);
  7381. continue;
  7382. }
  7383. *(char *)(workdata->f_ha1) = 0;
  7384. (workdata->f_ha1)++;
  7385. if (!strcmp(workdata->ah.user, workdata->f_user)
  7386. && !strcmp(workdata->domain, workdata->f_domain)) {
  7387. return check_password(workdata->conn->request_info.request_method,
  7388. workdata->f_ha1,
  7389. workdata->ah.uri,
  7390. workdata->ah.nonce,
  7391. workdata->ah.nc,
  7392. workdata->ah.cnonce,
  7393. workdata->ah.qop,
  7394. workdata->ah.response);
  7395. }
  7396. }
  7397. return is_authorized;
  7398. }
  7399. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7400. static int
  7401. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7402. {
  7403. struct read_auth_file_struct workdata;
  7404. char buf[MG_BUF_LEN];
  7405. if (!conn || !conn->dom_ctx) {
  7406. return 0;
  7407. }
  7408. memset(&workdata, 0, sizeof(workdata));
  7409. workdata.conn = conn;
  7410. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7411. return 0;
  7412. }
  7413. if (realm) {
  7414. workdata.domain = realm;
  7415. } else {
  7416. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7417. }
  7418. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7419. }
  7420. /* Public function to check http digest authentication header */
  7421. int
  7422. mg_check_digest_access_authentication(struct mg_connection *conn,
  7423. const char *realm,
  7424. const char *filename)
  7425. {
  7426. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7427. int auth;
  7428. if (!conn || !filename) {
  7429. return -1;
  7430. }
  7431. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7432. return -2;
  7433. }
  7434. auth = authorize(conn, &file, realm);
  7435. mg_fclose(&file.access);
  7436. return auth;
  7437. }
  7438. #endif /* NO_FILESYSTEMS */
  7439. /* Return 1 if request is authorised, 0 otherwise. */
  7440. static int
  7441. check_authorization(struct mg_connection *conn, const char *path)
  7442. {
  7443. #if !defined(NO_FILESYSTEMS)
  7444. char fname[UTF8_PATH_MAX];
  7445. struct vec uri_vec, filename_vec;
  7446. const char *list;
  7447. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7448. int authorized = 1, truncated;
  7449. if (!conn || !conn->dom_ctx) {
  7450. return 0;
  7451. }
  7452. list = conn->dom_ctx->config[PROTECT_URI];
  7453. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7454. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7455. mg_snprintf(conn,
  7456. &truncated,
  7457. fname,
  7458. sizeof(fname),
  7459. "%.*s",
  7460. (int)filename_vec.len,
  7461. filename_vec.ptr);
  7462. if (truncated
  7463. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7464. mg_cry_internal(conn,
  7465. "%s: cannot open %s: %s",
  7466. __func__,
  7467. fname,
  7468. strerror(errno));
  7469. }
  7470. break;
  7471. }
  7472. }
  7473. if (!is_file_opened(&file.access)) {
  7474. open_auth_file(conn, path, &file);
  7475. }
  7476. if (is_file_opened(&file.access)) {
  7477. authorized = authorize(conn, &file, NULL);
  7478. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7479. }
  7480. return authorized;
  7481. #else
  7482. (void)conn;
  7483. (void)path;
  7484. return 1;
  7485. #endif /* NO_FILESYSTEMS */
  7486. }
  7487. /* Internal function. Assumes conn is valid */
  7488. static void
  7489. send_authorization_request(struct mg_connection *conn, const char *realm)
  7490. {
  7491. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7492. int trunc = 0;
  7493. char buf[128];
  7494. if (!realm) {
  7495. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7496. }
  7497. mg_lock_context(conn->phys_ctx);
  7498. nonce += conn->dom_ctx->nonce_count;
  7499. ++conn->dom_ctx->nonce_count;
  7500. mg_unlock_context(conn->phys_ctx);
  7501. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7502. conn->must_close = 1;
  7503. /* Create 401 response */
  7504. mg_response_header_start(conn, 401);
  7505. send_no_cache_header(conn);
  7506. send_additional_header(conn);
  7507. mg_response_header_add(conn, "Content-Length", "0", -1);
  7508. /* Content for "WWW-Authenticate" header */
  7509. mg_snprintf(conn,
  7510. &trunc,
  7511. buf,
  7512. sizeof(buf),
  7513. "Digest qop=\"auth\", realm=\"%s\", "
  7514. "nonce=\"%" UINT64_FMT "\"",
  7515. realm,
  7516. nonce);
  7517. if (!trunc) {
  7518. /* !trunc should always be true */
  7519. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7520. }
  7521. /* Send all headers */
  7522. mg_response_header_send(conn);
  7523. }
  7524. /* Interface function. Parameters are provided by the user, so do
  7525. * at least some basic checks.
  7526. */
  7527. int
  7528. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7529. const char *realm)
  7530. {
  7531. if (conn && conn->dom_ctx) {
  7532. send_authorization_request(conn, realm);
  7533. return 0;
  7534. }
  7535. return -1;
  7536. }
  7537. #if !defined(NO_FILES)
  7538. static int
  7539. is_authorized_for_put(struct mg_connection *conn)
  7540. {
  7541. if (conn) {
  7542. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7543. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7544. int ret = 0;
  7545. if (passfile != NULL
  7546. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7547. ret = authorize(conn, &file, NULL);
  7548. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7549. }
  7550. return ret;
  7551. }
  7552. return 0;
  7553. }
  7554. #endif
  7555. int
  7556. mg_modify_passwords_file_ha1(const char *fname,
  7557. const char *domain,
  7558. const char *user,
  7559. const char *ha1)
  7560. {
  7561. int found = 0, i, result = 1;
  7562. char line[512], u[256], d[256], h[256];
  7563. struct stat st = {0};
  7564. FILE *fp = NULL;
  7565. char *temp_file = NULL;
  7566. int temp_file_offs = 0;
  7567. /* Regard empty password as no password - remove user record. */
  7568. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7569. ha1 = NULL;
  7570. }
  7571. /* Other arguments must not be empty */
  7572. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7573. return 0;
  7574. }
  7575. /* Using the given file format, user name and domain must not contain
  7576. * the ':' character */
  7577. if (strchr(user, ':') != NULL) {
  7578. return 0;
  7579. }
  7580. if (strchr(domain, ':') != NULL) {
  7581. return 0;
  7582. }
  7583. /* Do not allow control characters like newline in user name and domain.
  7584. * Do not allow excessively long names either. */
  7585. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7586. if (iscntrl((unsigned char)user[i])) {
  7587. return 0;
  7588. }
  7589. }
  7590. if (user[i]) {
  7591. return 0; /* user name too long */
  7592. }
  7593. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7594. if (iscntrl((unsigned char)domain[i])) {
  7595. return 0;
  7596. }
  7597. }
  7598. if (domain[i]) {
  7599. return 0; /* domain name too long */
  7600. }
  7601. /* The maximum length of the path to the password file is limited */
  7602. if (strlen(fname) >= UTF8_PATH_MAX) {
  7603. return 0;
  7604. }
  7605. /* Check if the file exists, and get file size */
  7606. if (0 == stat(fname, &st)) {
  7607. int temp_buf_len = (int)st.st_size + 1024;
  7608. /* Allocate memory (instead of using a temporary file) */
  7609. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7610. if (!temp_file) {
  7611. /* Out of memory */
  7612. return 0;
  7613. }
  7614. /* File exists. Read it into a memory buffer. */
  7615. fp = fopen(fname, "r");
  7616. if (fp == NULL) {
  7617. /* Cannot read file. No permission? */
  7618. mg_free(temp_file);
  7619. return 0;
  7620. }
  7621. /* Read content and store in memory */
  7622. while ((fgets(line, sizeof(line), fp) != NULL)
  7623. && ((temp_file_offs + 600) < temp_buf_len)) {
  7624. /* file format is "user:domain:hash\n" */
  7625. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7626. continue;
  7627. }
  7628. u[255] = 0;
  7629. d[255] = 0;
  7630. h[255] = 0;
  7631. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7632. /* Found the user: change the password hash or drop the user
  7633. */
  7634. if ((ha1 != NULL) && (!found)) {
  7635. i = sprintf(temp_file + temp_file_offs,
  7636. "%s:%s:%s\n",
  7637. user,
  7638. domain,
  7639. ha1);
  7640. if (i < 1) {
  7641. fclose(fp);
  7642. mg_free(temp_file);
  7643. return 0;
  7644. }
  7645. temp_file_offs += i;
  7646. }
  7647. found = 1;
  7648. } else {
  7649. /* Copy existing user, including password hash */
  7650. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7651. if (i < 1) {
  7652. fclose(fp);
  7653. mg_free(temp_file);
  7654. return 0;
  7655. }
  7656. temp_file_offs += i;
  7657. }
  7658. }
  7659. fclose(fp);
  7660. }
  7661. /* Create new file */
  7662. fp = fopen(fname, "w");
  7663. if (!fp) {
  7664. mg_free(temp_file);
  7665. return 0;
  7666. }
  7667. #if !defined(_WIN32)
  7668. /* On Linux & co., restrict file read/write permissions to the owner */
  7669. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7670. result = 0;
  7671. }
  7672. #endif
  7673. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7674. /* Store buffered content of old file */
  7675. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7676. != (size_t)temp_file_offs) {
  7677. result = 0;
  7678. }
  7679. }
  7680. /* If new user, just add it */
  7681. if ((ha1 != NULL) && (!found)) {
  7682. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7683. result = 0;
  7684. }
  7685. }
  7686. /* All data written */
  7687. if (fclose(fp) != 0) {
  7688. result = 0;
  7689. }
  7690. mg_free(temp_file);
  7691. return result;
  7692. }
  7693. int
  7694. mg_modify_passwords_file(const char *fname,
  7695. const char *domain,
  7696. const char *user,
  7697. const char *pass)
  7698. {
  7699. char ha1buf[33];
  7700. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7701. return 0;
  7702. }
  7703. if ((pass == NULL) || (pass[0] == 0)) {
  7704. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7705. }
  7706. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7707. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7708. }
  7709. static int
  7710. is_valid_port(unsigned long port)
  7711. {
  7712. return (port <= 0xffff);
  7713. }
  7714. static int
  7715. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7716. {
  7717. struct addrinfo hints, *res, *ressave;
  7718. int func_ret = 0;
  7719. int gai_ret;
  7720. memset(&hints, 0, sizeof(struct addrinfo));
  7721. hints.ai_family = af;
  7722. if (!resolve_src) {
  7723. hints.ai_flags = AI_NUMERICHOST;
  7724. }
  7725. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7726. if (gai_ret != 0) {
  7727. /* gai_strerror could be used to convert gai_ret to a string */
  7728. /* POSIX return values: see
  7729. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7730. */
  7731. /* Windows return values: see
  7732. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7733. */
  7734. return 0;
  7735. }
  7736. ressave = res;
  7737. while (res) {
  7738. if ((dstlen >= (size_t)res->ai_addrlen)
  7739. && (res->ai_addr->sa_family == af)) {
  7740. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7741. func_ret = 1;
  7742. }
  7743. res = res->ai_next;
  7744. }
  7745. freeaddrinfo(ressave);
  7746. return func_ret;
  7747. }
  7748. static int
  7749. connect_socket(
  7750. struct mg_context *ctx /* may be NULL */,
  7751. const char *host,
  7752. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7753. int use_ssl, /* 0 or 1 */
  7754. char *ebuf,
  7755. size_t ebuf_len,
  7756. SOCKET *sock /* output: socket, must not be NULL */,
  7757. union usa *sa /* output: socket address, must not be NULL */
  7758. )
  7759. {
  7760. int ip_ver = 0;
  7761. int conn_ret = -1;
  7762. int sockerr = 0;
  7763. *sock = INVALID_SOCKET;
  7764. memset(sa, 0, sizeof(*sa));
  7765. if (ebuf_len > 0) {
  7766. *ebuf = 0;
  7767. }
  7768. if (host == NULL) {
  7769. mg_snprintf(NULL,
  7770. NULL, /* No truncation check for ebuf */
  7771. ebuf,
  7772. ebuf_len,
  7773. "%s",
  7774. "NULL host");
  7775. return 0;
  7776. }
  7777. #if defined(USE_X_DOM_SOCKET)
  7778. if (port == -99) {
  7779. /* Unix domain socket */
  7780. size_t hostlen = strlen(host);
  7781. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7782. mg_snprintf(NULL,
  7783. NULL, /* No truncation check for ebuf */
  7784. ebuf,
  7785. ebuf_len,
  7786. "%s",
  7787. "host length exceeds limit");
  7788. return 0;
  7789. }
  7790. } else
  7791. #endif
  7792. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7793. mg_snprintf(NULL,
  7794. NULL, /* No truncation check for ebuf */
  7795. ebuf,
  7796. ebuf_len,
  7797. "%s",
  7798. "invalid port");
  7799. return 0;
  7800. }
  7801. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7802. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7803. if (use_ssl && (TLS_client_method == NULL)) {
  7804. mg_snprintf(NULL,
  7805. NULL, /* No truncation check for ebuf */
  7806. ebuf,
  7807. ebuf_len,
  7808. "%s",
  7809. "SSL is not initialized");
  7810. return 0;
  7811. }
  7812. #else
  7813. if (use_ssl && (SSLv23_client_method == NULL)) {
  7814. mg_snprintf(NULL,
  7815. NULL, /* No truncation check for ebuf */
  7816. ebuf,
  7817. ebuf_len,
  7818. "%s",
  7819. "SSL is not initialized");
  7820. return 0;
  7821. }
  7822. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7823. #else
  7824. (void)use_ssl;
  7825. #endif /* NO SSL */
  7826. #if defined(USE_X_DOM_SOCKET)
  7827. if (port == -99) {
  7828. size_t hostlen = strlen(host);
  7829. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7830. ip_ver = -99;
  7831. sa->sun.sun_family = AF_UNIX;
  7832. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7833. memcpy(sa->sun.sun_path, host, hostlen);
  7834. } else
  7835. #endif
  7836. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7837. sa->sin.sin_port = htons((uint16_t)port);
  7838. ip_ver = 4;
  7839. #if defined(USE_IPV6)
  7840. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7841. sa->sin6.sin6_port = htons((uint16_t)port);
  7842. ip_ver = 6;
  7843. } else if (host[0] == '[') {
  7844. /* While getaddrinfo on Windows will work with [::1],
  7845. * getaddrinfo on Linux only works with ::1 (without []). */
  7846. size_t l = strlen(host + 1);
  7847. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7848. if (h) {
  7849. h[l - 1] = 0;
  7850. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7851. sa->sin6.sin6_port = htons((uint16_t)port);
  7852. ip_ver = 6;
  7853. }
  7854. mg_free(h);
  7855. }
  7856. #endif
  7857. }
  7858. if (ip_ver == 0) {
  7859. mg_snprintf(NULL,
  7860. NULL, /* No truncation check for ebuf */
  7861. ebuf,
  7862. ebuf_len,
  7863. "%s",
  7864. "host not found");
  7865. return 0;
  7866. }
  7867. if (ip_ver == 4) {
  7868. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7869. }
  7870. #if defined(USE_IPV6)
  7871. else if (ip_ver == 6) {
  7872. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7873. }
  7874. #endif
  7875. #if defined(USE_X_DOM_SOCKET)
  7876. else if (ip_ver == -99) {
  7877. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7878. }
  7879. #endif
  7880. if (*sock == INVALID_SOCKET) {
  7881. mg_snprintf(NULL,
  7882. NULL, /* No truncation check for ebuf */
  7883. ebuf,
  7884. ebuf_len,
  7885. "socket(): %s",
  7886. strerror(ERRNO));
  7887. return 0;
  7888. }
  7889. if (0 != set_non_blocking_mode(*sock)) {
  7890. mg_snprintf(NULL,
  7891. NULL, /* No truncation check for ebuf */
  7892. ebuf,
  7893. ebuf_len,
  7894. "Cannot set socket to non-blocking: %s",
  7895. strerror(ERRNO));
  7896. closesocket(*sock);
  7897. *sock = INVALID_SOCKET;
  7898. return 0;
  7899. }
  7900. set_close_on_exec(*sock, NULL, ctx);
  7901. if (ip_ver == 4) {
  7902. /* connected with IPv4 */
  7903. conn_ret = connect(*sock,
  7904. (struct sockaddr *)((void *)&sa->sin),
  7905. sizeof(sa->sin));
  7906. }
  7907. #if defined(USE_IPV6)
  7908. else if (ip_ver == 6) {
  7909. /* connected with IPv6 */
  7910. conn_ret = connect(*sock,
  7911. (struct sockaddr *)((void *)&sa->sin6),
  7912. sizeof(sa->sin6));
  7913. }
  7914. #endif
  7915. #if defined(USE_X_DOM_SOCKET)
  7916. else if (ip_ver == -99) {
  7917. /* connected to domain socket */
  7918. conn_ret = connect(*sock,
  7919. (struct sockaddr *)((void *)&sa->sun),
  7920. sizeof(sa->sun));
  7921. }
  7922. #endif
  7923. if (conn_ret != 0) {
  7924. sockerr = ERRNO;
  7925. }
  7926. #if defined(_WIN32)
  7927. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7928. #else
  7929. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7930. #endif
  7931. /* Data for getsockopt */
  7932. void *psockerr = &sockerr;
  7933. int ret;
  7934. #if defined(_WIN32)
  7935. int len = (int)sizeof(sockerr);
  7936. #else
  7937. socklen_t len = (socklen_t)sizeof(sockerr);
  7938. #endif
  7939. /* Data for poll */
  7940. struct mg_pollfd pfd[1];
  7941. int pollres;
  7942. int ms_wait = 10000; /* 10 second timeout */
  7943. stop_flag_t nonstop;
  7944. STOP_FLAG_ASSIGN(&nonstop, 0);
  7945. /* For a non-blocking socket, the connect sequence is:
  7946. * 1) call connect (will not block)
  7947. * 2) wait until the socket is ready for writing (select or poll)
  7948. * 3) check connection state with getsockopt
  7949. */
  7950. pfd[0].fd = *sock;
  7951. pfd[0].events = POLLOUT;
  7952. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7953. if (pollres != 1) {
  7954. /* Not connected */
  7955. mg_snprintf(NULL,
  7956. NULL, /* No truncation check for ebuf */
  7957. ebuf,
  7958. ebuf_len,
  7959. "connect(%s:%d): timeout",
  7960. host,
  7961. port);
  7962. closesocket(*sock);
  7963. *sock = INVALID_SOCKET;
  7964. return 0;
  7965. }
  7966. #if defined(_WIN32)
  7967. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7968. #else
  7969. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7970. #endif
  7971. if ((ret == 0) && (sockerr == 0)) {
  7972. conn_ret = 0;
  7973. }
  7974. }
  7975. if (conn_ret != 0) {
  7976. /* Not connected */
  7977. mg_snprintf(NULL,
  7978. NULL, /* No truncation check for ebuf */
  7979. ebuf,
  7980. ebuf_len,
  7981. "connect(%s:%d): error %s",
  7982. host,
  7983. port,
  7984. strerror(sockerr));
  7985. closesocket(*sock);
  7986. *sock = INVALID_SOCKET;
  7987. return 0;
  7988. }
  7989. return 1;
  7990. }
  7991. int
  7992. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7993. {
  7994. static const char *dont_escape = "._-$,;~()";
  7995. static const char *hex = "0123456789abcdef";
  7996. char *pos = dst;
  7997. const char *end = dst + dst_len - 1;
  7998. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7999. if (isalnum((unsigned char)*src)
  8000. || (strchr(dont_escape, *src) != NULL)) {
  8001. *pos = *src;
  8002. } else if (pos + 2 < end) {
  8003. pos[0] = '%';
  8004. pos[1] = hex[(unsigned char)*src >> 4];
  8005. pos[2] = hex[(unsigned char)*src & 0xf];
  8006. pos += 2;
  8007. } else {
  8008. break;
  8009. }
  8010. }
  8011. *pos = '\0';
  8012. return (*src == '\0') ? (int)(pos - dst) : -1;
  8013. }
  8014. /* Return 0 on success, non-zero if an error occurs. */
  8015. static int
  8016. print_dir_entry(struct de *de)
  8017. {
  8018. size_t namesize, escsize, i;
  8019. char *href, *esc, *p;
  8020. char size[64], mod[64];
  8021. #if defined(REENTRANT_TIME)
  8022. struct tm _tm;
  8023. struct tm *tm = &_tm;
  8024. #else
  8025. struct tm *tm;
  8026. #endif
  8027. /* Estimate worst case size for encoding and escaping */
  8028. namesize = strlen(de->file_name) + 1;
  8029. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8030. href = (char *)mg_malloc(namesize * 3 + escsize);
  8031. if (href == NULL) {
  8032. return -1;
  8033. }
  8034. mg_url_encode(de->file_name, href, namesize * 3);
  8035. esc = NULL;
  8036. if (escsize > 0) {
  8037. /* HTML escaping needed */
  8038. esc = href + namesize * 3;
  8039. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8040. mg_strlcpy(p, de->file_name + i, 2);
  8041. if (*p == '&') {
  8042. strcpy(p, "&amp;");
  8043. } else if (*p == '<') {
  8044. strcpy(p, "&lt;");
  8045. } else if (*p == '>') {
  8046. strcpy(p, "&gt;");
  8047. }
  8048. }
  8049. }
  8050. if (de->file.is_directory) {
  8051. mg_snprintf(de->conn,
  8052. NULL, /* Buffer is big enough */
  8053. size,
  8054. sizeof(size),
  8055. "%s",
  8056. "[DIRECTORY]");
  8057. } else {
  8058. /* We use (signed) cast below because MSVC 6 compiler cannot
  8059. * convert unsigned __int64 to double. Sigh. */
  8060. if (de->file.size < 1024) {
  8061. mg_snprintf(de->conn,
  8062. NULL, /* Buffer is big enough */
  8063. size,
  8064. sizeof(size),
  8065. "%d",
  8066. (int)de->file.size);
  8067. } else if (de->file.size < 0x100000) {
  8068. mg_snprintf(de->conn,
  8069. NULL, /* Buffer is big enough */
  8070. size,
  8071. sizeof(size),
  8072. "%.1fk",
  8073. (double)de->file.size / 1024.0);
  8074. } else if (de->file.size < 0x40000000) {
  8075. mg_snprintf(de->conn,
  8076. NULL, /* Buffer is big enough */
  8077. size,
  8078. sizeof(size),
  8079. "%.1fM",
  8080. (double)de->file.size / 1048576);
  8081. } else {
  8082. mg_snprintf(de->conn,
  8083. NULL, /* Buffer is big enough */
  8084. size,
  8085. sizeof(size),
  8086. "%.1fG",
  8087. (double)de->file.size / 1073741824);
  8088. }
  8089. }
  8090. /* Note: mg_snprintf will not cause a buffer overflow above.
  8091. * So, string truncation checks are not required here. */
  8092. #if defined(REENTRANT_TIME)
  8093. localtime_r(&de->file.last_modified, tm);
  8094. #else
  8095. tm = localtime(&de->file.last_modified);
  8096. #endif
  8097. if (tm != NULL) {
  8098. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8099. } else {
  8100. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8101. mod[sizeof(mod) - 1] = '\0';
  8102. }
  8103. mg_printf(de->conn,
  8104. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8105. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8106. href,
  8107. de->file.is_directory ? "/" : "",
  8108. esc ? esc : de->file_name,
  8109. de->file.is_directory ? "/" : "",
  8110. mod,
  8111. size);
  8112. mg_free(href);
  8113. return 0;
  8114. }
  8115. /* This function is called from send_directory() and used for
  8116. * sorting directory entries by size, or name, or modification time.
  8117. * On windows, __cdecl specification is needed in case if project is built
  8118. * with __stdcall convention. qsort always requires __cdels callback. */
  8119. static int WINCDECL
  8120. compare_dir_entries(const void *p1, const void *p2)
  8121. {
  8122. if (p1 && p2) {
  8123. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8124. const char *query_string = a->conn->request_info.query_string;
  8125. int cmp_result = 0;
  8126. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8127. query_string = "n";
  8128. }
  8129. if (a->file.is_directory && !b->file.is_directory) {
  8130. return -1; /* Always put directories on top */
  8131. } else if (!a->file.is_directory && b->file.is_directory) {
  8132. return 1; /* Always put directories on top */
  8133. } else if (*query_string == 'n') {
  8134. cmp_result = strcmp(a->file_name, b->file_name);
  8135. } else if (*query_string == 's') {
  8136. cmp_result = (a->file.size == b->file.size)
  8137. ? 0
  8138. : ((a->file.size > b->file.size) ? 1 : -1);
  8139. } else if (*query_string == 'd') {
  8140. cmp_result =
  8141. (a->file.last_modified == b->file.last_modified)
  8142. ? 0
  8143. : ((a->file.last_modified > b->file.last_modified) ? 1
  8144. : -1);
  8145. }
  8146. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8147. }
  8148. return 0;
  8149. }
  8150. static int
  8151. must_hide_file(struct mg_connection *conn, const char *path)
  8152. {
  8153. if (conn && conn->dom_ctx) {
  8154. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8155. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8156. return (match_prefix_strlen(pw_pattern, path) > 0)
  8157. || (match_prefix_strlen(pattern, path) > 0);
  8158. }
  8159. return 0;
  8160. }
  8161. #if !defined(NO_FILESYSTEMS)
  8162. static int
  8163. scan_directory(struct mg_connection *conn,
  8164. const char *dir,
  8165. void *data,
  8166. int (*cb)(struct de *, void *))
  8167. {
  8168. char path[UTF8_PATH_MAX];
  8169. struct dirent *dp;
  8170. DIR *dirp;
  8171. struct de de;
  8172. int truncated;
  8173. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8174. return 0;
  8175. } else {
  8176. de.conn = conn;
  8177. while ((dp = mg_readdir(dirp)) != NULL) {
  8178. /* Do not show current dir and hidden files */
  8179. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8180. || must_hide_file(conn, dp->d_name)) {
  8181. continue;
  8182. }
  8183. mg_snprintf(
  8184. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8185. /* If we don't memset stat structure to zero, mtime will have
  8186. * garbage and strftime() will segfault later on in
  8187. * print_dir_entry(). memset is required only if mg_stat()
  8188. * fails. For more details, see
  8189. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8190. memset(&de.file, 0, sizeof(de.file));
  8191. if (truncated) {
  8192. /* If the path is not complete, skip processing. */
  8193. continue;
  8194. }
  8195. if (!mg_stat(conn, path, &de.file)) {
  8196. mg_cry_internal(conn,
  8197. "%s: mg_stat(%s) failed: %s",
  8198. __func__,
  8199. path,
  8200. strerror(ERRNO));
  8201. }
  8202. de.file_name = dp->d_name;
  8203. if (cb(&de, data)) {
  8204. /* stopped */
  8205. break;
  8206. }
  8207. }
  8208. (void)mg_closedir(dirp);
  8209. }
  8210. return 1;
  8211. }
  8212. #endif /* NO_FILESYSTEMS */
  8213. #if !defined(NO_FILES)
  8214. static int
  8215. remove_directory(struct mg_connection *conn, const char *dir)
  8216. {
  8217. char path[UTF8_PATH_MAX];
  8218. struct dirent *dp;
  8219. DIR *dirp;
  8220. struct de de;
  8221. int truncated;
  8222. int ok = 1;
  8223. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8224. return 0;
  8225. } else {
  8226. de.conn = conn;
  8227. while ((dp = mg_readdir(dirp)) != NULL) {
  8228. /* Do not show current dir (but show hidden files as they will
  8229. * also be removed) */
  8230. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8231. continue;
  8232. }
  8233. mg_snprintf(
  8234. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8235. /* If we don't memset stat structure to zero, mtime will have
  8236. * garbage and strftime() will segfault later on in
  8237. * print_dir_entry(). memset is required only if mg_stat()
  8238. * fails. For more details, see
  8239. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8240. memset(&de.file, 0, sizeof(de.file));
  8241. if (truncated) {
  8242. /* Do not delete anything shorter */
  8243. ok = 0;
  8244. continue;
  8245. }
  8246. if (!mg_stat(conn, path, &de.file)) {
  8247. mg_cry_internal(conn,
  8248. "%s: mg_stat(%s) failed: %s",
  8249. __func__,
  8250. path,
  8251. strerror(ERRNO));
  8252. ok = 0;
  8253. }
  8254. if (de.file.is_directory) {
  8255. if (remove_directory(conn, path) == 0) {
  8256. ok = 0;
  8257. }
  8258. } else {
  8259. /* This will fail file is the file is in memory */
  8260. if (mg_remove(conn, path) == 0) {
  8261. ok = 0;
  8262. }
  8263. }
  8264. }
  8265. (void)mg_closedir(dirp);
  8266. IGNORE_UNUSED_RESULT(rmdir(dir));
  8267. }
  8268. return ok;
  8269. }
  8270. #endif
  8271. struct dir_scan_data {
  8272. struct de *entries;
  8273. size_t num_entries;
  8274. size_t arr_size;
  8275. };
  8276. #if !defined(NO_FILESYSTEMS)
  8277. static int
  8278. dir_scan_callback(struct de *de, void *data)
  8279. {
  8280. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8281. struct de *entries = dsd->entries;
  8282. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8283. /* Here "entries" is a temporary pointer and can be replaced,
  8284. * "dsd->entries" is the original pointer */
  8285. entries =
  8286. (struct de *)mg_realloc(entries,
  8287. dsd->arr_size * 2 * sizeof(entries[0]));
  8288. if (entries == NULL) {
  8289. /* stop scan */
  8290. return 1;
  8291. }
  8292. dsd->entries = entries;
  8293. dsd->arr_size *= 2;
  8294. }
  8295. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8296. if (entries[dsd->num_entries].file_name == NULL) {
  8297. /* stop scan */
  8298. return 1;
  8299. }
  8300. entries[dsd->num_entries].file = de->file;
  8301. entries[dsd->num_entries].conn = de->conn;
  8302. dsd->num_entries++;
  8303. return 0;
  8304. }
  8305. static void
  8306. handle_directory_request(struct mg_connection *conn, const char *dir)
  8307. {
  8308. size_t i;
  8309. int sort_direction;
  8310. struct dir_scan_data data = {NULL, 0, 128};
  8311. char date[64], *esc, *p;
  8312. const char *title;
  8313. time_t curtime = time(NULL);
  8314. if (!conn) {
  8315. return;
  8316. }
  8317. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8318. mg_send_http_error(conn,
  8319. 500,
  8320. "Error: Cannot open directory\nopendir(%s): %s",
  8321. dir,
  8322. strerror(ERRNO));
  8323. return;
  8324. }
  8325. gmt_time_string(date, sizeof(date), &curtime);
  8326. esc = NULL;
  8327. title = conn->request_info.local_uri;
  8328. if (title[strcspn(title, "&<>")]) {
  8329. /* HTML escaping needed */
  8330. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8331. if (esc) {
  8332. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8333. mg_strlcpy(p, title + i, 2);
  8334. if (*p == '&') {
  8335. strcpy(p, "&amp;");
  8336. } else if (*p == '<') {
  8337. strcpy(p, "&lt;");
  8338. } else if (*p == '>') {
  8339. strcpy(p, "&gt;");
  8340. }
  8341. }
  8342. } else {
  8343. title = "";
  8344. }
  8345. }
  8346. sort_direction = ((conn->request_info.query_string != NULL)
  8347. && (conn->request_info.query_string[0] != '\0')
  8348. && (conn->request_info.query_string[1] == 'd'))
  8349. ? 'a'
  8350. : 'd';
  8351. conn->must_close = 1;
  8352. /* Create 200 OK response */
  8353. mg_response_header_start(conn, 200);
  8354. send_static_cache_header(conn);
  8355. send_additional_header(conn);
  8356. mg_response_header_add(conn,
  8357. "Content-Type",
  8358. "text/html; charset=utf-8",
  8359. -1);
  8360. /* Send all headers */
  8361. mg_response_header_send(conn);
  8362. /* Body */
  8363. mg_printf(conn,
  8364. "<html><head><title>Index of %s</title>"
  8365. "<style>th {text-align: left;}</style></head>"
  8366. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8367. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8368. "<th><a href=\"?d%c\">Modified</a></th>"
  8369. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8370. "<tr><td colspan=\"3\"><hr></td></tr>",
  8371. esc ? esc : title,
  8372. esc ? esc : title,
  8373. sort_direction,
  8374. sort_direction,
  8375. sort_direction);
  8376. mg_free(esc);
  8377. /* Print first entry - link to a parent directory */
  8378. mg_printf(conn,
  8379. "<tr><td><a href=\"%s\">%s</a></td>"
  8380. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8381. "..",
  8382. "Parent directory",
  8383. "-",
  8384. "-");
  8385. /* Sort and print directory entries */
  8386. if (data.entries != NULL) {
  8387. qsort(data.entries,
  8388. data.num_entries,
  8389. sizeof(data.entries[0]),
  8390. compare_dir_entries);
  8391. for (i = 0; i < data.num_entries; i++) {
  8392. print_dir_entry(&data.entries[i]);
  8393. mg_free(data.entries[i].file_name);
  8394. }
  8395. mg_free(data.entries);
  8396. }
  8397. mg_printf(conn, "%s", "</table></pre></body></html>");
  8398. conn->status_code = 200;
  8399. }
  8400. #endif /* NO_FILESYSTEMS */
  8401. /* Send len bytes from the opened file to the client. */
  8402. static void
  8403. send_file_data(struct mg_connection *conn,
  8404. struct mg_file *filep,
  8405. int64_t offset,
  8406. int64_t len)
  8407. {
  8408. char buf[MG_BUF_LEN];
  8409. int to_read, num_read, num_written;
  8410. int64_t size;
  8411. if (!filep || !conn) {
  8412. return;
  8413. }
  8414. /* Sanity check the offset */
  8415. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8416. : (int64_t)(filep->stat.size);
  8417. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8418. if (len > 0 && filep->access.fp != NULL) {
  8419. /* file stored on disk */
  8420. #if defined(__linux__)
  8421. /* sendfile is only available for Linux */
  8422. if ((conn->ssl == 0) && (conn->throttle == 0)
  8423. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8424. "yes"))) {
  8425. off_t sf_offs = (off_t)offset;
  8426. ssize_t sf_sent;
  8427. int sf_file = fileno(filep->access.fp);
  8428. int loop_cnt = 0;
  8429. do {
  8430. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8431. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8432. size_t sf_tosend =
  8433. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8434. sf_sent =
  8435. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8436. if (sf_sent > 0) {
  8437. len -= sf_sent;
  8438. offset += sf_sent;
  8439. } else if (loop_cnt == 0) {
  8440. /* This file can not be sent using sendfile.
  8441. * This might be the case for pseudo-files in the
  8442. * /sys/ and /proc/ file system.
  8443. * Use the regular user mode copy code instead. */
  8444. break;
  8445. } else if (sf_sent == 0) {
  8446. /* No error, but 0 bytes sent. May be EOF? */
  8447. return;
  8448. }
  8449. loop_cnt++;
  8450. } while ((len > 0) && (sf_sent >= 0));
  8451. if (sf_sent > 0) {
  8452. return; /* OK */
  8453. }
  8454. /* sf_sent<0 means error, thus fall back to the classic way */
  8455. /* This is always the case, if sf_file is not a "normal" file,
  8456. * e.g., for sending data from the output of a CGI process. */
  8457. offset = (int64_t)sf_offs;
  8458. }
  8459. #endif
  8460. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8461. mg_cry_internal(conn,
  8462. "%s: fseeko() failed: %s",
  8463. __func__,
  8464. strerror(ERRNO));
  8465. mg_send_http_error(
  8466. conn,
  8467. 500,
  8468. "%s",
  8469. "Error: Unable to access file at requested position.");
  8470. } else {
  8471. while (len > 0) {
  8472. /* Calculate how much to read from the file in the buffer */
  8473. to_read = sizeof(buf);
  8474. if ((int64_t)to_read > len) {
  8475. to_read = (int)len;
  8476. }
  8477. /* Read from file, exit the loop on error */
  8478. if ((num_read =
  8479. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8480. <= 0) {
  8481. break;
  8482. }
  8483. /* Send read bytes to the client, exit the loop on error */
  8484. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8485. != num_read) {
  8486. break;
  8487. }
  8488. /* Both read and were successful, adjust counters */
  8489. len -= num_written;
  8490. }
  8491. }
  8492. }
  8493. }
  8494. static int
  8495. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8496. {
  8497. return sscanf(header,
  8498. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8499. a,
  8500. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8501. // to an integer value, but function will not report
  8502. // conversion errors; consider using 'strtol' instead
  8503. }
  8504. static void
  8505. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8506. {
  8507. if ((filestat != NULL) && (buf != NULL)) {
  8508. mg_snprintf(NULL,
  8509. NULL, /* All calls to construct_etag use 64 byte buffer */
  8510. buf,
  8511. buf_len,
  8512. "\"%lx.%" INT64_FMT "\"",
  8513. (unsigned long)filestat->last_modified,
  8514. filestat->size);
  8515. }
  8516. }
  8517. static void
  8518. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8519. {
  8520. if (filep != NULL && filep->fp != NULL) {
  8521. #if defined(_WIN32)
  8522. (void)conn; /* Unused. */
  8523. #else
  8524. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8525. mg_cry_internal(conn,
  8526. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8527. __func__,
  8528. strerror(ERRNO));
  8529. }
  8530. #endif
  8531. }
  8532. }
  8533. #if defined(USE_ZLIB)
  8534. #include "mod_zlib.inl"
  8535. #endif
  8536. #if !defined(NO_FILESYSTEMS)
  8537. static void
  8538. handle_static_file_request(struct mg_connection *conn,
  8539. const char *path,
  8540. struct mg_file *filep,
  8541. const char *mime_type,
  8542. const char *additional_headers)
  8543. {
  8544. char lm[64], etag[64];
  8545. char range[128]; /* large enough, so there will be no overflow */
  8546. const char *range_hdr;
  8547. int64_t cl, r1, r2;
  8548. struct vec mime_vec;
  8549. int n, truncated;
  8550. char gz_path[UTF8_PATH_MAX];
  8551. const char *encoding = 0;
  8552. const char *origin_hdr;
  8553. const char *cors_orig_cfg;
  8554. const char *cors1, *cors2;
  8555. int is_head_request;
  8556. #if defined(USE_ZLIB)
  8557. /* Compression is allowed, unless there is a reason not to use
  8558. * compression. If the file is already compressed, too small or a
  8559. * "range" request was made, on the fly compression is not possible. */
  8560. int allow_on_the_fly_compression = 1;
  8561. #endif
  8562. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8563. return;
  8564. }
  8565. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8566. if (mime_type == NULL) {
  8567. get_mime_type(conn, path, &mime_vec);
  8568. } else {
  8569. mime_vec.ptr = mime_type;
  8570. mime_vec.len = strlen(mime_type);
  8571. }
  8572. if (filep->stat.size > INT64_MAX) {
  8573. mg_send_http_error(conn,
  8574. 500,
  8575. "Error: File size is too large to send\n%" INT64_FMT,
  8576. filep->stat.size);
  8577. return;
  8578. }
  8579. cl = (int64_t)filep->stat.size;
  8580. conn->status_code = 200;
  8581. range[0] = '\0';
  8582. #if defined(USE_ZLIB)
  8583. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8584. * it's important to rewrite the filename after resolving
  8585. * the mime type from it, to preserve the actual file's type */
  8586. if (!conn->accept_gzip) {
  8587. allow_on_the_fly_compression = 0;
  8588. }
  8589. #endif
  8590. /* Check if there is a range header */
  8591. range_hdr = mg_get_header(conn, "Range");
  8592. /* For gzipped files, add *.gz */
  8593. if (filep->stat.is_gzipped) {
  8594. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8595. if (truncated) {
  8596. mg_send_http_error(conn,
  8597. 500,
  8598. "Error: Path of zipped file too long (%s)",
  8599. path);
  8600. return;
  8601. }
  8602. path = gz_path;
  8603. encoding = "gzip";
  8604. #if defined(USE_ZLIB)
  8605. /* File is already compressed. No "on the fly" compression. */
  8606. allow_on_the_fly_compression = 0;
  8607. #endif
  8608. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8609. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8610. struct mg_file_stat file_stat;
  8611. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8612. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8613. && !file_stat.is_directory) {
  8614. file_stat.is_gzipped = 1;
  8615. filep->stat = file_stat;
  8616. cl = (int64_t)filep->stat.size;
  8617. path = gz_path;
  8618. encoding = "gzip";
  8619. #if defined(USE_ZLIB)
  8620. /* File is already compressed. No "on the fly" compression. */
  8621. allow_on_the_fly_compression = 0;
  8622. #endif
  8623. }
  8624. }
  8625. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8626. mg_send_http_error(conn,
  8627. 500,
  8628. "Error: Cannot open file\nfopen(%s): %s",
  8629. path,
  8630. strerror(ERRNO));
  8631. return;
  8632. }
  8633. fclose_on_exec(&filep->access, conn);
  8634. /* If "Range" request was made: parse header, send only selected part
  8635. * of the file. */
  8636. r1 = r2 = 0;
  8637. if ((range_hdr != NULL)
  8638. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8639. && (r2 >= 0)) {
  8640. /* actually, range requests don't play well with a pre-gzipped
  8641. * file (since the range is specified in the uncompressed space) */
  8642. if (filep->stat.is_gzipped) {
  8643. mg_send_http_error(
  8644. conn,
  8645. 416, /* 416 = Range Not Satisfiable */
  8646. "%s",
  8647. "Error: Range requests in gzipped files are not supported");
  8648. (void)mg_fclose(
  8649. &filep->access); /* ignore error on read only file */
  8650. return;
  8651. }
  8652. conn->status_code = 206;
  8653. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8654. mg_snprintf(conn,
  8655. NULL, /* range buffer is big enough */
  8656. range,
  8657. sizeof(range),
  8658. "bytes "
  8659. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8660. r1,
  8661. r1 + cl - 1,
  8662. filep->stat.size);
  8663. #if defined(USE_ZLIB)
  8664. /* Do not compress ranges. */
  8665. allow_on_the_fly_compression = 0;
  8666. #endif
  8667. }
  8668. /* Do not compress small files. Small files do not benefit from file
  8669. * compression, but there is still some overhead. */
  8670. #if defined(USE_ZLIB)
  8671. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8672. /* File is below the size limit. */
  8673. allow_on_the_fly_compression = 0;
  8674. }
  8675. #endif
  8676. /* Standard CORS header */
  8677. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8678. origin_hdr = mg_get_header(conn, "Origin");
  8679. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8680. /* Cross-origin resource sharing (CORS), see
  8681. * http://www.html5rocks.com/en/tutorials/cors/,
  8682. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8683. * -
  8684. * preflight is not supported for files. */
  8685. cors1 = "Access-Control-Allow-Origin";
  8686. cors2 = cors_orig_cfg;
  8687. } else {
  8688. cors1 = cors2 = "";
  8689. }
  8690. /* Prepare Etag, and Last-Modified headers. */
  8691. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8692. construct_etag(etag, sizeof(etag), &filep->stat);
  8693. /* Create 2xx (200, 206) response */
  8694. mg_response_header_start(conn, conn->status_code);
  8695. send_static_cache_header(conn);
  8696. send_additional_header(conn);
  8697. mg_response_header_add(conn,
  8698. "Content-Type",
  8699. mime_vec.ptr,
  8700. (int)mime_vec.len);
  8701. if (cors1[0] != 0) {
  8702. mg_response_header_add(conn, cors1, cors2, -1);
  8703. }
  8704. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8705. mg_response_header_add(conn, "Etag", etag, -1);
  8706. #if defined(USE_ZLIB)
  8707. /* On the fly compression allowed */
  8708. if (allow_on_the_fly_compression) {
  8709. /* For on the fly compression, we don't know the content size in
  8710. * advance, so we have to use chunked encoding */
  8711. encoding = "gzip";
  8712. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8713. /* HTTP/2 is always using "chunks" (frames) */
  8714. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8715. }
  8716. } else
  8717. #endif
  8718. {
  8719. /* Without on-the-fly compression, we know the content-length
  8720. * and we can use ranges (with on-the-fly compression we cannot).
  8721. * So we send these response headers only in this case. */
  8722. char len[32];
  8723. int trunc = 0;
  8724. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8725. if (!trunc) {
  8726. mg_response_header_add(conn, "Content-Length", len, -1);
  8727. }
  8728. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8729. }
  8730. if (encoding) {
  8731. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8732. }
  8733. if (range[0] != 0) {
  8734. mg_response_header_add(conn, "Content-Range", range, -1);
  8735. }
  8736. /* The code above does not add any header starting with X- to make
  8737. * sure no one of the additional_headers is included twice */
  8738. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8739. mg_response_header_add_lines(conn, additional_headers);
  8740. }
  8741. /* Send all headers */
  8742. mg_response_header_send(conn);
  8743. if (!is_head_request) {
  8744. #if defined(USE_ZLIB)
  8745. if (allow_on_the_fly_compression) {
  8746. /* Compress and send */
  8747. send_compressed_data(conn, filep);
  8748. } else
  8749. #endif
  8750. {
  8751. /* Send file directly */
  8752. send_file_data(conn, filep, r1, cl);
  8753. }
  8754. }
  8755. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8756. }
  8757. int
  8758. mg_send_file_body(struct mg_connection *conn, const char *path)
  8759. {
  8760. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8761. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8762. return -1;
  8763. }
  8764. fclose_on_exec(&file.access, conn);
  8765. send_file_data(conn, &file, 0, INT64_MAX);
  8766. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8767. return 0; /* >= 0 for OK */
  8768. }
  8769. #endif /* NO_FILESYSTEMS */
  8770. #if !defined(NO_CACHING)
  8771. /* Return True if we should reply 304 Not Modified. */
  8772. static int
  8773. is_not_modified(const struct mg_connection *conn,
  8774. const struct mg_file_stat *filestat)
  8775. {
  8776. char etag[64];
  8777. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8778. const char *inm = mg_get_header(conn, "If-None-Match");
  8779. construct_etag(etag, sizeof(etag), filestat);
  8780. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8781. || ((ims != NULL)
  8782. && (filestat->last_modified <= parse_date_string(ims)));
  8783. }
  8784. static void
  8785. handle_not_modified_static_file_request(struct mg_connection *conn,
  8786. struct mg_file *filep)
  8787. {
  8788. char lm[64], etag[64];
  8789. if ((conn == NULL) || (filep == NULL)) {
  8790. return;
  8791. }
  8792. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8793. construct_etag(etag, sizeof(etag), &filep->stat);
  8794. /* Create 304 "not modified" response */
  8795. mg_response_header_start(conn, 304);
  8796. send_static_cache_header(conn);
  8797. send_additional_header(conn);
  8798. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8799. mg_response_header_add(conn, "Etag", etag, -1);
  8800. /* Send all headers */
  8801. mg_response_header_send(conn);
  8802. }
  8803. #endif
  8804. #if !defined(NO_FILESYSTEMS)
  8805. void
  8806. mg_send_file(struct mg_connection *conn, const char *path)
  8807. {
  8808. mg_send_mime_file2(conn, path, NULL, NULL);
  8809. }
  8810. void
  8811. mg_send_mime_file(struct mg_connection *conn,
  8812. const char *path,
  8813. const char *mime_type)
  8814. {
  8815. mg_send_mime_file2(conn, path, mime_type, NULL);
  8816. }
  8817. void
  8818. mg_send_mime_file2(struct mg_connection *conn,
  8819. const char *path,
  8820. const char *mime_type,
  8821. const char *additional_headers)
  8822. {
  8823. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8824. if (!conn) {
  8825. /* No conn */
  8826. return;
  8827. }
  8828. if (mg_stat(conn, path, &file.stat)) {
  8829. #if !defined(NO_CACHING)
  8830. if (is_not_modified(conn, &file.stat)) {
  8831. /* Send 304 "Not Modified" - this must not send any body data */
  8832. handle_not_modified_static_file_request(conn, &file);
  8833. } else
  8834. #endif /* NO_CACHING */
  8835. if (file.stat.is_directory) {
  8836. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8837. "yes")) {
  8838. handle_directory_request(conn, path);
  8839. } else {
  8840. mg_send_http_error(conn,
  8841. 403,
  8842. "%s",
  8843. "Error: Directory listing denied");
  8844. }
  8845. } else {
  8846. handle_static_file_request(
  8847. conn, path, &file, mime_type, additional_headers);
  8848. }
  8849. } else {
  8850. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8851. }
  8852. }
  8853. /* For a given PUT path, create all intermediate subdirectories.
  8854. * Return 0 if the path itself is a directory.
  8855. * Return 1 if the path leads to a file.
  8856. * Return -1 for if the path is too long.
  8857. * Return -2 if path can not be created.
  8858. */
  8859. static int
  8860. put_dir(struct mg_connection *conn, const char *path)
  8861. {
  8862. char buf[UTF8_PATH_MAX];
  8863. const char *s, *p;
  8864. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8865. size_t len;
  8866. int res = 1;
  8867. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8868. len = (size_t)(p - path);
  8869. if (len >= sizeof(buf)) {
  8870. /* path too long */
  8871. res = -1;
  8872. break;
  8873. }
  8874. memcpy(buf, path, len);
  8875. buf[len] = '\0';
  8876. /* Try to create intermediate directory */
  8877. DEBUG_TRACE("mkdir(%s)", buf);
  8878. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8879. /* path does not exixt and can not be created */
  8880. res = -2;
  8881. break;
  8882. }
  8883. /* Is path itself a directory? */
  8884. if (p[1] == '\0') {
  8885. res = 0;
  8886. }
  8887. }
  8888. return res;
  8889. }
  8890. static void
  8891. remove_bad_file(const struct mg_connection *conn, const char *path)
  8892. {
  8893. int r = mg_remove(conn, path);
  8894. if (r != 0) {
  8895. mg_cry_internal(conn,
  8896. "%s: Cannot remove invalid file %s",
  8897. __func__,
  8898. path);
  8899. }
  8900. }
  8901. long long
  8902. mg_store_body(struct mg_connection *conn, const char *path)
  8903. {
  8904. char buf[MG_BUF_LEN];
  8905. long long len = 0;
  8906. int ret, n;
  8907. struct mg_file fi;
  8908. if (conn->consumed_content != 0) {
  8909. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8910. return -11;
  8911. }
  8912. ret = put_dir(conn, path);
  8913. if (ret < 0) {
  8914. /* -1 for path too long,
  8915. * -2 for path can not be created. */
  8916. return ret;
  8917. }
  8918. if (ret != 1) {
  8919. /* Return 0 means, path itself is a directory. */
  8920. return 0;
  8921. }
  8922. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8923. return -12;
  8924. }
  8925. ret = mg_read(conn, buf, sizeof(buf));
  8926. while (ret > 0) {
  8927. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8928. if (n != ret) {
  8929. (void)mg_fclose(
  8930. &fi.access); /* File is bad and will be removed anyway. */
  8931. remove_bad_file(conn, path);
  8932. return -13;
  8933. }
  8934. len += ret;
  8935. ret = mg_read(conn, buf, sizeof(buf));
  8936. }
  8937. /* File is open for writing. If fclose fails, there was probably an
  8938. * error flushing the buffer to disk, so the file on disk might be
  8939. * broken. Delete it and return an error to the caller. */
  8940. if (mg_fclose(&fi.access) != 0) {
  8941. remove_bad_file(conn, path);
  8942. return -14;
  8943. }
  8944. return len;
  8945. }
  8946. #endif /* NO_FILESYSTEMS */
  8947. /* Parse a buffer:
  8948. * Forward the string pointer till the end of a word, then
  8949. * terminate it and forward till the begin of the next word.
  8950. */
  8951. static int
  8952. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8953. {
  8954. /* Forward until a space is found - use isgraph here */
  8955. /* See http://www.cplusplus.com/reference/cctype/ */
  8956. while (isgraph((unsigned char)**ppw)) {
  8957. (*ppw)++;
  8958. }
  8959. /* Check end of word */
  8960. if (eol) {
  8961. /* must be a end of line */
  8962. if ((**ppw != '\r') && (**ppw != '\n')) {
  8963. return -1;
  8964. }
  8965. } else {
  8966. /* must be a end of a word, but not a line */
  8967. if (**ppw != ' ') {
  8968. return -1;
  8969. }
  8970. }
  8971. /* Terminate and forward to the next word */
  8972. do {
  8973. **ppw = 0;
  8974. (*ppw)++;
  8975. } while (isspace((unsigned char)**ppw));
  8976. /* Check after term */
  8977. if (!eol) {
  8978. /* if it's not the end of line, there must be a next word */
  8979. if (!isgraph((unsigned char)**ppw)) {
  8980. return -1;
  8981. }
  8982. }
  8983. /* ok */
  8984. return 1;
  8985. }
  8986. /* Parse HTTP headers from the given buffer, advance buf pointer
  8987. * to the point where parsing stopped.
  8988. * All parameters must be valid pointers (not NULL).
  8989. * Return <0 on error. */
  8990. static int
  8991. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8992. {
  8993. int i;
  8994. int num_headers = 0;
  8995. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8996. char *dp = *buf;
  8997. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8998. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8999. dp++;
  9000. }
  9001. if (dp == *buf) {
  9002. /* End of headers reached. */
  9003. break;
  9004. }
  9005. /* Drop all spaces after header name before : */
  9006. while (*dp == ' ') {
  9007. *dp = 0;
  9008. dp++;
  9009. }
  9010. if (*dp != ':') {
  9011. /* This is not a valid field. */
  9012. return -1;
  9013. }
  9014. /* End of header key (*dp == ':') */
  9015. /* Truncate here and set the key name */
  9016. *dp = 0;
  9017. hdr[i].name = *buf;
  9018. /* Skip all spaces */
  9019. do {
  9020. dp++;
  9021. } while ((*dp == ' ') || (*dp == '\t'));
  9022. /* The rest of the line is the value */
  9023. hdr[i].value = dp;
  9024. /* Find end of line */
  9025. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9026. dp++;
  9027. };
  9028. /* eliminate \r */
  9029. if (*dp == '\r') {
  9030. *dp = 0;
  9031. dp++;
  9032. if (*dp != '\n') {
  9033. /* This is not a valid line. */
  9034. return -1;
  9035. }
  9036. }
  9037. /* here *dp is either 0 or '\n' */
  9038. /* in any case, we have a new header */
  9039. num_headers = i + 1;
  9040. if (*dp) {
  9041. *dp = 0;
  9042. dp++;
  9043. *buf = dp;
  9044. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9045. /* This is the end of the header */
  9046. break;
  9047. }
  9048. } else {
  9049. *buf = dp;
  9050. break;
  9051. }
  9052. }
  9053. return num_headers;
  9054. }
  9055. struct mg_http_method_info {
  9056. const char *name;
  9057. int request_has_body;
  9058. int response_has_body;
  9059. int is_safe;
  9060. int is_idempotent;
  9061. int is_cacheable;
  9062. };
  9063. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9064. static const struct mg_http_method_info http_methods[] = {
  9065. /* HTTP (RFC 2616) */
  9066. {"GET", 0, 1, 1, 1, 1},
  9067. {"POST", 1, 1, 0, 0, 0},
  9068. {"PUT", 1, 0, 0, 1, 0},
  9069. {"DELETE", 0, 0, 0, 1, 0},
  9070. {"HEAD", 0, 0, 1, 1, 1},
  9071. {"OPTIONS", 0, 0, 1, 1, 0},
  9072. {"CONNECT", 1, 1, 0, 0, 0},
  9073. /* TRACE method (RFC 2616) is not supported for security reasons */
  9074. /* PATCH method (RFC 5789) */
  9075. {"PATCH", 1, 0, 0, 0, 0},
  9076. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9077. /* WEBDAV (RFC 2518) */
  9078. {"PROPFIND", 0, 1, 1, 1, 0},
  9079. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9080. * Some PROPFIND results MAY be cached, with care,
  9081. * as there is no cache validation mechanism for
  9082. * most properties. This method is both safe and
  9083. * idempotent (see Section 9.1 of [RFC2616]). */
  9084. {"MKCOL", 0, 0, 0, 1, 0},
  9085. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9086. * When MKCOL is invoked without a request body,
  9087. * the newly created collection SHOULD have no
  9088. * members. A MKCOL request message may contain
  9089. * a message body. The precise behavior of a MKCOL
  9090. * request when the body is present is undefined,
  9091. * ... ==> We do not support MKCOL with body data.
  9092. * This method is idempotent, but not safe (see
  9093. * Section 9.1 of [RFC2616]). Responses to this
  9094. * method MUST NOT be cached. */
  9095. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9096. {"LOCK", 1, 1, 0, 0, 0},
  9097. {"UNLOCK", 1, 0, 0, 0, 0},
  9098. {"PROPPATCH", 1, 1, 0, 0, 0},
  9099. /* Unsupported WEBDAV Methods: */
  9100. /* COPY, MOVE (RFC 2518) */
  9101. /* + 11 methods from RFC 3253 */
  9102. /* ORDERPATCH (RFC 3648) */
  9103. /* ACL (RFC 3744) */
  9104. /* SEARCH (RFC 5323) */
  9105. /* + MicroSoft extensions
  9106. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9107. /* REPORT method (RFC 3253) */
  9108. {"REPORT", 1, 1, 1, 1, 1},
  9109. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9110. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9111. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9112. * to be useful for REST in case a "GET request with body" is
  9113. * required. */
  9114. {NULL, 0, 0, 0, 0, 0}
  9115. /* end of list */
  9116. };
  9117. static const struct mg_http_method_info *
  9118. get_http_method_info(const char *method)
  9119. {
  9120. /* Check if the method is known to the server. The list of all known
  9121. * HTTP methods can be found here at
  9122. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9123. */
  9124. const struct mg_http_method_info *m = http_methods;
  9125. while (m->name) {
  9126. if (!strcmp(m->name, method)) {
  9127. return m;
  9128. }
  9129. m++;
  9130. }
  9131. return NULL;
  9132. }
  9133. static int
  9134. is_valid_http_method(const char *method)
  9135. {
  9136. return (get_http_method_info(method) != NULL);
  9137. }
  9138. /* Parse HTTP request, fill in mg_request_info structure.
  9139. * This function modifies the buffer by NUL-terminating
  9140. * HTTP request components, header names and header values.
  9141. * Parameters:
  9142. * buf (in/out): pointer to the HTTP header to parse and split
  9143. * len (in): length of HTTP header buffer
  9144. * re (out): parsed header as mg_request_info
  9145. * buf and ri must be valid pointers (not NULL), len>0.
  9146. * Returns <0 on error. */
  9147. static int
  9148. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9149. {
  9150. int request_length;
  9151. int init_skip = 0;
  9152. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9153. * remote_port */
  9154. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9155. NULL;
  9156. ri->num_headers = 0;
  9157. /* RFC says that all initial whitespaces should be ignored */
  9158. /* This included all leading \r and \n (isspace) */
  9159. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9160. while ((len > 0) && isspace((unsigned char)*buf)) {
  9161. buf++;
  9162. len--;
  9163. init_skip++;
  9164. }
  9165. if (len == 0) {
  9166. /* Incomplete request */
  9167. return 0;
  9168. }
  9169. /* Control characters are not allowed, including zero */
  9170. if (iscntrl((unsigned char)*buf)) {
  9171. return -1;
  9172. }
  9173. /* Find end of HTTP header */
  9174. request_length = get_http_header_len(buf, len);
  9175. if (request_length <= 0) {
  9176. return request_length;
  9177. }
  9178. buf[request_length - 1] = '\0';
  9179. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9180. return -1;
  9181. }
  9182. /* The first word has to be the HTTP method */
  9183. ri->request_method = buf;
  9184. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9185. return -1;
  9186. }
  9187. /* The second word is the URI */
  9188. ri->request_uri = buf;
  9189. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9190. return -1;
  9191. }
  9192. /* Next would be the HTTP version */
  9193. ri->http_version = buf;
  9194. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9195. return -1;
  9196. }
  9197. /* Check for a valid HTTP version key */
  9198. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9199. /* Invalid request */
  9200. return -1;
  9201. }
  9202. ri->http_version += 5;
  9203. /* Check for a valid http method */
  9204. if (!is_valid_http_method(ri->request_method)) {
  9205. return -1;
  9206. }
  9207. /* Parse all HTTP headers */
  9208. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9209. if (ri->num_headers < 0) {
  9210. /* Error while parsing headers */
  9211. return -1;
  9212. }
  9213. return request_length + init_skip;
  9214. }
  9215. static int
  9216. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9217. {
  9218. int response_length;
  9219. int init_skip = 0;
  9220. char *tmp, *tmp2;
  9221. long l;
  9222. /* Initialize elements. */
  9223. ri->http_version = ri->status_text = NULL;
  9224. ri->num_headers = ri->status_code = 0;
  9225. /* RFC says that all initial whitespaces should be ingored */
  9226. /* This included all leading \r and \n (isspace) */
  9227. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9228. while ((len > 0) && isspace((unsigned char)*buf)) {
  9229. buf++;
  9230. len--;
  9231. init_skip++;
  9232. }
  9233. if (len == 0) {
  9234. /* Incomplete request */
  9235. return 0;
  9236. }
  9237. /* Control characters are not allowed, including zero */
  9238. if (iscntrl((unsigned char)*buf)) {
  9239. return -1;
  9240. }
  9241. /* Find end of HTTP header */
  9242. response_length = get_http_header_len(buf, len);
  9243. if (response_length <= 0) {
  9244. return response_length;
  9245. }
  9246. buf[response_length - 1] = '\0';
  9247. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9248. return -1;
  9249. }
  9250. /* The first word is the HTTP version */
  9251. /* Check for a valid HTTP version key */
  9252. if (strncmp(buf, "HTTP/", 5) != 0) {
  9253. /* Invalid request */
  9254. return -1;
  9255. }
  9256. buf += 5;
  9257. if (!isgraph((unsigned char)buf[0])) {
  9258. /* Invalid request */
  9259. return -1;
  9260. }
  9261. ri->http_version = buf;
  9262. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9263. return -1;
  9264. }
  9265. /* The second word is the status as a number */
  9266. tmp = buf;
  9267. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9268. return -1;
  9269. }
  9270. l = strtol(tmp, &tmp2, 10);
  9271. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9272. /* Everything else but a 3 digit code is invalid */
  9273. return -1;
  9274. }
  9275. ri->status_code = (int)l;
  9276. /* The rest of the line is the status text */
  9277. ri->status_text = buf;
  9278. /* Find end of status text */
  9279. /* isgraph or isspace = isprint */
  9280. while (isprint((unsigned char)*buf)) {
  9281. buf++;
  9282. }
  9283. if ((*buf != '\r') && (*buf != '\n')) {
  9284. return -1;
  9285. }
  9286. /* Terminate string and forward buf to next line */
  9287. do {
  9288. *buf = 0;
  9289. buf++;
  9290. } while (isspace((unsigned char)*buf));
  9291. /* Parse all HTTP headers */
  9292. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9293. if (ri->num_headers < 0) {
  9294. /* Error while parsing headers */
  9295. return -1;
  9296. }
  9297. return response_length + init_skip;
  9298. }
  9299. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9300. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9301. * buffer (which marks the end of HTTP request). Buffer buf may already
  9302. * have some data. The length of the data is stored in nread.
  9303. * Upon every read operation, increase nread by the number of bytes read. */
  9304. static int
  9305. read_message(FILE *fp,
  9306. struct mg_connection *conn,
  9307. char *buf,
  9308. int bufsiz,
  9309. int *nread)
  9310. {
  9311. int request_len, n = 0;
  9312. struct timespec last_action_time;
  9313. double request_timeout;
  9314. if (!conn) {
  9315. return 0;
  9316. }
  9317. memset(&last_action_time, 0, sizeof(last_action_time));
  9318. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9319. /* value of request_timeout is in seconds, config in milliseconds */
  9320. request_timeout =
  9321. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9322. } else {
  9323. request_timeout =
  9324. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9325. / 1000.0;
  9326. }
  9327. if (conn->handled_requests > 0) {
  9328. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9329. request_timeout =
  9330. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9331. / 1000.0;
  9332. }
  9333. }
  9334. request_len = get_http_header_len(buf, *nread);
  9335. while (request_len == 0) {
  9336. /* Full request not yet received */
  9337. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9338. /* Server is to be stopped. */
  9339. return -1;
  9340. }
  9341. if (*nread >= bufsiz) {
  9342. /* Request too long */
  9343. return -2;
  9344. }
  9345. n = pull_inner(
  9346. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9347. if (n == -2) {
  9348. /* Receive error */
  9349. return -1;
  9350. }
  9351. /* update clock after every read request */
  9352. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9353. if (n > 0) {
  9354. *nread += n;
  9355. request_len = get_http_header_len(buf, *nread);
  9356. }
  9357. if ((request_len == 0) && (request_timeout >= 0)) {
  9358. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9359. > request_timeout) {
  9360. /* Timeout */
  9361. return -1;
  9362. }
  9363. }
  9364. }
  9365. return request_len;
  9366. }
  9367. #if !defined(NO_CGI) || !defined(NO_FILES)
  9368. static int
  9369. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9370. {
  9371. const char *expect;
  9372. char buf[MG_BUF_LEN];
  9373. int success = 0;
  9374. if (!conn) {
  9375. return 0;
  9376. }
  9377. expect = mg_get_header(conn, "Expect");
  9378. DEBUG_ASSERT(fp != NULL);
  9379. if (!fp) {
  9380. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9381. return 0;
  9382. }
  9383. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9384. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9385. */
  9386. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9387. } else {
  9388. if (expect != NULL) {
  9389. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9390. conn->status_code = 100;
  9391. } else {
  9392. conn->status_code = 200;
  9393. }
  9394. DEBUG_ASSERT(conn->consumed_content == 0);
  9395. if (conn->consumed_content != 0) {
  9396. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9397. return 0;
  9398. }
  9399. for (;;) {
  9400. int nread = mg_read(conn, buf, sizeof(buf));
  9401. if (nread <= 0) {
  9402. success = (nread == 0);
  9403. break;
  9404. }
  9405. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9406. break;
  9407. }
  9408. }
  9409. /* Each error code path in this function must send an error */
  9410. if (!success) {
  9411. /* NOTE: Maybe some data has already been sent. */
  9412. /* TODO (low): If some data has been sent, a correct error
  9413. * reply can no longer be sent, so just close the connection */
  9414. mg_send_http_error(conn, 500, "%s", "");
  9415. }
  9416. }
  9417. return success;
  9418. }
  9419. #endif
  9420. #if defined(USE_TIMERS)
  9421. #define TIMER_API static
  9422. #include "timer.inl"
  9423. #endif /* USE_TIMERS */
  9424. #if !defined(NO_CGI)
  9425. /* This structure helps to create an environment for the spawned CGI
  9426. * program.
  9427. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9428. * last element must be NULL.
  9429. * However, on Windows there is a requirement that all these
  9430. * VARIABLE=VALUE\0
  9431. * strings must reside in a contiguous buffer. The end of the buffer is
  9432. * marked by two '\0' characters.
  9433. * We satisfy both worlds: we create an envp array (which is vars), all
  9434. * entries are actually pointers inside buf. */
  9435. struct cgi_environment {
  9436. struct mg_connection *conn;
  9437. /* Data block */
  9438. char *buf; /* Environment buffer */
  9439. size_t buflen; /* Space available in buf */
  9440. size_t bufused; /* Space taken in buf */
  9441. /* Index block */
  9442. char **var; /* char **envp */
  9443. size_t varlen; /* Number of variables available in var */
  9444. size_t varused; /* Number of variables stored in var */
  9445. };
  9446. static void addenv(struct cgi_environment *env,
  9447. PRINTF_FORMAT_STRING(const char *fmt),
  9448. ...) PRINTF_ARGS(2, 3);
  9449. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9450. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9451. static void
  9452. addenv(struct cgi_environment *env, const char *fmt, ...)
  9453. {
  9454. size_t i, n, space;
  9455. int truncated = 0;
  9456. char *added;
  9457. va_list ap;
  9458. if ((env->varlen - env->varused) < 2) {
  9459. mg_cry_internal(env->conn,
  9460. "%s: Cannot register CGI variable [%s]",
  9461. __func__,
  9462. fmt);
  9463. return;
  9464. }
  9465. /* Calculate how much space is left in the buffer */
  9466. space = (env->buflen - env->bufused);
  9467. do {
  9468. /* Space for "\0\0" is always needed. */
  9469. if (space <= 2) {
  9470. /* Allocate new buffer */
  9471. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9472. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9473. if (!added) {
  9474. /* Out of memory */
  9475. mg_cry_internal(
  9476. env->conn,
  9477. "%s: Cannot allocate memory for CGI variable [%s]",
  9478. __func__,
  9479. fmt);
  9480. return;
  9481. }
  9482. /* Retarget pointers */
  9483. env->buf = added;
  9484. env->buflen = n;
  9485. for (i = 0, n = 0; i < env->varused; i++) {
  9486. env->var[i] = added + n;
  9487. n += strlen(added + n) + 1;
  9488. }
  9489. space = (env->buflen - env->bufused);
  9490. }
  9491. /* Make a pointer to the free space int the buffer */
  9492. added = env->buf + env->bufused;
  9493. /* Copy VARIABLE=VALUE\0 string into the free space */
  9494. va_start(ap, fmt);
  9495. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9496. va_end(ap);
  9497. /* Do not add truncated strings to the environment */
  9498. if (truncated) {
  9499. /* Reallocate the buffer */
  9500. space = 0;
  9501. }
  9502. } while (truncated);
  9503. /* Calculate number of bytes added to the environment */
  9504. n = strlen(added) + 1;
  9505. env->bufused += n;
  9506. /* Append a pointer to the added string into the envp array */
  9507. env->var[env->varused] = added;
  9508. env->varused++;
  9509. }
  9510. /* Return 0 on success, non-zero if an error occurs. */
  9511. static int
  9512. prepare_cgi_environment(struct mg_connection *conn,
  9513. const char *prog,
  9514. struct cgi_environment *env,
  9515. unsigned char cgi_config_idx)
  9516. {
  9517. const char *s;
  9518. struct vec var_vec;
  9519. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9520. int i, truncated, uri_len;
  9521. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9522. return -1;
  9523. }
  9524. env->conn = conn;
  9525. env->buflen = CGI_ENVIRONMENT_SIZE;
  9526. env->bufused = 0;
  9527. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9528. if (env->buf == NULL) {
  9529. mg_cry_internal(conn,
  9530. "%s: Not enough memory for environmental buffer",
  9531. __func__);
  9532. return -1;
  9533. }
  9534. env->varlen = MAX_CGI_ENVIR_VARS;
  9535. env->varused = 0;
  9536. env->var =
  9537. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9538. if (env->var == NULL) {
  9539. mg_cry_internal(conn,
  9540. "%s: Not enough memory for environmental variables",
  9541. __func__);
  9542. mg_free(env->buf);
  9543. return -1;
  9544. }
  9545. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9546. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9547. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9548. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9549. /* Prepare the environment block */
  9550. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9551. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9552. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9553. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9554. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9555. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9556. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9557. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9558. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9559. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9560. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9561. /* SCRIPT_NAME */
  9562. uri_len = (int)strlen(conn->request_info.local_uri);
  9563. if (conn->path_info == NULL) {
  9564. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9565. /* URI: /path_to_script/script.cgi */
  9566. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9567. } else {
  9568. /* URI: /path_to_script/ ... using index.cgi */
  9569. const char *index_file = strrchr(prog, '/');
  9570. if (index_file) {
  9571. addenv(env,
  9572. "SCRIPT_NAME=%s%s",
  9573. conn->request_info.local_uri,
  9574. index_file + 1);
  9575. }
  9576. }
  9577. } else {
  9578. /* URI: /path_to_script/script.cgi/path_info */
  9579. addenv(env,
  9580. "SCRIPT_NAME=%.*s",
  9581. uri_len - (int)strlen(conn->path_info),
  9582. conn->request_info.local_uri);
  9583. }
  9584. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9585. if (conn->path_info == NULL) {
  9586. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9587. } else {
  9588. addenv(env,
  9589. "PATH_TRANSLATED=%s%s",
  9590. conn->dom_ctx->config[DOCUMENT_ROOT],
  9591. conn->path_info);
  9592. }
  9593. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9594. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9595. addenv(env, "CONTENT_TYPE=%s", s);
  9596. }
  9597. if (conn->request_info.query_string != NULL) {
  9598. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9599. }
  9600. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9601. addenv(env, "CONTENT_LENGTH=%s", s);
  9602. }
  9603. if ((s = getenv("PATH")) != NULL) {
  9604. addenv(env, "PATH=%s", s);
  9605. }
  9606. if (conn->path_info != NULL) {
  9607. addenv(env, "PATH_INFO=%s", conn->path_info);
  9608. }
  9609. if (conn->status_code > 0) {
  9610. /* CGI error handler should show the status code */
  9611. addenv(env, "STATUS=%d", conn->status_code);
  9612. }
  9613. #if defined(_WIN32)
  9614. if ((s = getenv("COMSPEC")) != NULL) {
  9615. addenv(env, "COMSPEC=%s", s);
  9616. }
  9617. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9618. addenv(env, "SYSTEMROOT=%s", s);
  9619. }
  9620. if ((s = getenv("SystemDrive")) != NULL) {
  9621. addenv(env, "SystemDrive=%s", s);
  9622. }
  9623. if ((s = getenv("ProgramFiles")) != NULL) {
  9624. addenv(env, "ProgramFiles=%s", s);
  9625. }
  9626. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9627. addenv(env, "ProgramFiles(x86)=%s", s);
  9628. }
  9629. #else
  9630. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9631. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9632. }
  9633. #endif /* _WIN32 */
  9634. if ((s = getenv("PERLLIB")) != NULL) {
  9635. addenv(env, "PERLLIB=%s", s);
  9636. }
  9637. if (conn->request_info.remote_user != NULL) {
  9638. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9639. addenv(env, "%s", "AUTH_TYPE=Digest");
  9640. }
  9641. /* Add all headers as HTTP_* variables */
  9642. for (i = 0; i < conn->request_info.num_headers; i++) {
  9643. (void)mg_snprintf(conn,
  9644. &truncated,
  9645. http_var_name,
  9646. sizeof(http_var_name),
  9647. "HTTP_%s",
  9648. conn->request_info.http_headers[i].name);
  9649. if (truncated) {
  9650. mg_cry_internal(conn,
  9651. "%s: HTTP header variable too long [%s]",
  9652. __func__,
  9653. conn->request_info.http_headers[i].name);
  9654. continue;
  9655. }
  9656. /* Convert variable name into uppercase, and change - to _ */
  9657. for (p = http_var_name; *p != '\0'; p++) {
  9658. if (*p == '-') {
  9659. *p = '_';
  9660. }
  9661. *p = (char)toupper((unsigned char)*p);
  9662. }
  9663. addenv(env,
  9664. "%s=%s",
  9665. http_var_name,
  9666. conn->request_info.http_headers[i].value);
  9667. }
  9668. /* Add user-specified variables */
  9669. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9670. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9671. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9672. }
  9673. env->var[env->varused] = NULL;
  9674. env->buf[env->bufused] = '\0';
  9675. return 0;
  9676. }
  9677. /* Data for CGI process control: PID and number of references */
  9678. struct process_control_data {
  9679. pid_t pid;
  9680. ptrdiff_t references;
  9681. };
  9682. static int
  9683. abort_cgi_process(void *data)
  9684. {
  9685. /* Waitpid checks for child status and won't work for a pid that does
  9686. * not identify a child of the current process. Thus, if the pid is
  9687. * reused, we will not affect a different process. */
  9688. struct process_control_data *proc = (struct process_control_data *)data;
  9689. int status = 0;
  9690. ptrdiff_t refs;
  9691. pid_t ret_pid;
  9692. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9693. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9694. /* Stop child process */
  9695. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9696. kill(proc->pid, SIGABRT);
  9697. /* Wait until process is terminated (don't leave zombies) */
  9698. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9699. ;
  9700. } else {
  9701. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9702. }
  9703. /* Dec reference counter */
  9704. refs = mg_atomic_dec(&proc->references);
  9705. if (refs == 0) {
  9706. /* no more references - free data */
  9707. mg_free(data);
  9708. }
  9709. return 0;
  9710. }
  9711. /* Local (static) function assumes all arguments are valid. */
  9712. static void
  9713. handle_cgi_request(struct mg_connection *conn,
  9714. const char *prog,
  9715. unsigned char cgi_config_idx)
  9716. {
  9717. char *buf;
  9718. size_t buflen;
  9719. int headers_len, data_len, i, truncated;
  9720. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9721. const char *status, *status_text, *connection_state;
  9722. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9723. struct mg_request_info ri;
  9724. struct cgi_environment blk;
  9725. FILE *in = NULL, *out = NULL, *err = NULL;
  9726. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9727. pid_t pid = (pid_t)-1;
  9728. struct process_control_data *proc = NULL;
  9729. #if defined(USE_TIMERS)
  9730. double cgi_timeout;
  9731. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9732. /* Get timeout in seconds */
  9733. cgi_timeout =
  9734. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9735. } else {
  9736. cgi_timeout =
  9737. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9738. }
  9739. #endif
  9740. buf = NULL;
  9741. buflen = conn->phys_ctx->max_request_size;
  9742. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9743. if (i != 0) {
  9744. blk.buf = NULL;
  9745. blk.var = NULL;
  9746. goto done;
  9747. }
  9748. /* CGI must be executed in its own directory. 'dir' must point to the
  9749. * directory containing executable program, 'p' must point to the
  9750. * executable program name relative to 'dir'. */
  9751. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9752. if (truncated) {
  9753. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9754. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9755. goto done;
  9756. }
  9757. if ((p = strrchr(dir, '/')) != NULL) {
  9758. *p++ = '\0';
  9759. } else {
  9760. dir[0] = '.';
  9761. dir[1] = '\0';
  9762. p = (char *)prog;
  9763. }
  9764. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9765. status = strerror(ERRNO);
  9766. mg_cry_internal(
  9767. conn,
  9768. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9769. prog,
  9770. status);
  9771. mg_send_http_error(conn,
  9772. 500,
  9773. "Error: Cannot create CGI pipe: %s",
  9774. status);
  9775. goto done;
  9776. }
  9777. proc = (struct process_control_data *)
  9778. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9779. if (proc == NULL) {
  9780. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9781. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9782. goto done;
  9783. }
  9784. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9785. pid = spawn_process(
  9786. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9787. if (pid == (pid_t)-1) {
  9788. status = strerror(ERRNO);
  9789. mg_cry_internal(
  9790. conn,
  9791. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9792. prog,
  9793. status);
  9794. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9795. mg_free(proc);
  9796. proc = NULL;
  9797. goto done;
  9798. }
  9799. /* Store data in shared process_control_data */
  9800. proc->pid = pid;
  9801. proc->references = 1;
  9802. #if defined(USE_TIMERS)
  9803. if (cgi_timeout > 0.0) {
  9804. proc->references = 2;
  9805. // Start a timer for CGI
  9806. timer_add(conn->phys_ctx,
  9807. cgi_timeout /* in seconds */,
  9808. 0.0,
  9809. 1,
  9810. abort_cgi_process,
  9811. (void *)proc,
  9812. NULL);
  9813. }
  9814. #endif
  9815. /* Parent closes only one side of the pipes.
  9816. * If we don't mark them as closed, close() attempt before
  9817. * return from this function throws an exception on Windows.
  9818. * Windows does not like when closed descriptor is closed again. */
  9819. (void)close(fdin[0]);
  9820. (void)close(fdout[1]);
  9821. (void)close(fderr[1]);
  9822. fdin[0] = fdout[1] = fderr[1] = -1;
  9823. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9824. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9825. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9826. status = strerror(ERRNO);
  9827. mg_cry_internal(conn,
  9828. "Error: CGI program \"%s\": Can not open fd: %s",
  9829. prog,
  9830. status);
  9831. mg_send_http_error(conn,
  9832. 500,
  9833. "Error: CGI can not open fd\nfdopen: %s",
  9834. status);
  9835. goto done;
  9836. }
  9837. setbuf(in, NULL);
  9838. setbuf(out, NULL);
  9839. setbuf(err, NULL);
  9840. fout.access.fp = out;
  9841. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9842. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9843. conn->content_len);
  9844. /* This is a POST/PUT request, or another request with body data. */
  9845. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9846. /* Error sending the body data */
  9847. mg_cry_internal(
  9848. conn,
  9849. "Error: CGI program \"%s\": Forward body data failed",
  9850. prog);
  9851. goto done;
  9852. }
  9853. }
  9854. /* Close so child gets an EOF. */
  9855. fclose(in);
  9856. in = NULL;
  9857. fdin[1] = -1;
  9858. /* Now read CGI reply into a buffer. We need to set correct
  9859. * status code, thus we need to see all HTTP headers first.
  9860. * Do not send anything back to client, until we buffer in all
  9861. * HTTP headers. */
  9862. data_len = 0;
  9863. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9864. if (buf == NULL) {
  9865. mg_send_http_error(conn,
  9866. 500,
  9867. "Error: Not enough memory for CGI buffer (%u bytes)",
  9868. (unsigned int)buflen);
  9869. mg_cry_internal(
  9870. conn,
  9871. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9872. "bytes)",
  9873. prog,
  9874. (unsigned int)buflen);
  9875. goto done;
  9876. }
  9877. DEBUG_TRACE("CGI: %s", "wait for response");
  9878. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9879. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9880. if (headers_len <= 0) {
  9881. /* Could not parse the CGI response. Check if some error message on
  9882. * stderr. */
  9883. i = pull_all(err, conn, buf, (int)buflen);
  9884. if (i > 0) {
  9885. /* CGI program explicitly sent an error */
  9886. /* Write the error message to the internal log */
  9887. mg_cry_internal(conn,
  9888. "Error: CGI program \"%s\" sent error "
  9889. "message: [%.*s]",
  9890. prog,
  9891. i,
  9892. buf);
  9893. /* Don't send the error message back to the client */
  9894. mg_send_http_error(conn,
  9895. 500,
  9896. "Error: CGI program \"%s\" failed.",
  9897. prog);
  9898. } else {
  9899. /* CGI program did not explicitly send an error, but a broken
  9900. * respon header */
  9901. mg_cry_internal(conn,
  9902. "Error: CGI program sent malformed or too big "
  9903. "(>%u bytes) HTTP headers: [%.*s]",
  9904. (unsigned)buflen,
  9905. data_len,
  9906. buf);
  9907. mg_send_http_error(conn,
  9908. 500,
  9909. "Error: CGI program sent malformed or too big "
  9910. "(>%u bytes) HTTP headers: [%.*s]",
  9911. (unsigned)buflen,
  9912. data_len,
  9913. buf);
  9914. }
  9915. /* in both cases, abort processing CGI */
  9916. goto done;
  9917. }
  9918. pbuf = buf;
  9919. buf[headers_len - 1] = '\0';
  9920. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9921. /* Make up and send the status line */
  9922. status_text = "OK";
  9923. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9924. != NULL) {
  9925. conn->status_code = atoi(status);
  9926. status_text = status;
  9927. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9928. status_text++;
  9929. }
  9930. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9931. != NULL) {
  9932. conn->status_code = 307;
  9933. } else {
  9934. conn->status_code = 200;
  9935. }
  9936. connection_state =
  9937. get_header(ri.http_headers, ri.num_headers, "Connection");
  9938. if (!header_has_option(connection_state, "keep-alive")) {
  9939. conn->must_close = 1;
  9940. }
  9941. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9942. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9943. /* Send headers */
  9944. for (i = 0; i < ri.num_headers; i++) {
  9945. DEBUG_TRACE("CGI header: %s: %s",
  9946. ri.http_headers[i].name,
  9947. ri.http_headers[i].value);
  9948. mg_printf(conn,
  9949. "%s: %s\r\n",
  9950. ri.http_headers[i].name,
  9951. ri.http_headers[i].value);
  9952. }
  9953. mg_write(conn, "\r\n", 2);
  9954. /* Send chunk of data that may have been read after the headers */
  9955. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9956. /* Read the rest of CGI output and send to the client */
  9957. DEBUG_TRACE("CGI: %s", "forward all data");
  9958. send_file_data(conn, &fout, 0, INT64_MAX);
  9959. DEBUG_TRACE("CGI: %s", "all data sent");
  9960. done:
  9961. mg_free(blk.var);
  9962. mg_free(blk.buf);
  9963. if (pid != (pid_t)-1) {
  9964. abort_cgi_process((void *)proc);
  9965. }
  9966. if (fdin[0] != -1) {
  9967. close(fdin[0]);
  9968. }
  9969. if (fdout[1] != -1) {
  9970. close(fdout[1]);
  9971. }
  9972. if (fderr[1] != -1) {
  9973. close(fderr[1]);
  9974. }
  9975. if (in != NULL) {
  9976. fclose(in);
  9977. } else if (fdin[1] != -1) {
  9978. close(fdin[1]);
  9979. }
  9980. if (out != NULL) {
  9981. fclose(out);
  9982. } else if (fdout[0] != -1) {
  9983. close(fdout[0]);
  9984. }
  9985. if (err != NULL) {
  9986. fclose(err);
  9987. } else if (fderr[0] != -1) {
  9988. close(fderr[0]);
  9989. }
  9990. mg_free(buf);
  9991. }
  9992. #endif /* !NO_CGI */
  9993. #if !defined(NO_FILES)
  9994. static void
  9995. mkcol(struct mg_connection *conn, const char *path)
  9996. {
  9997. int rc, body_len;
  9998. struct de de;
  9999. if (conn == NULL) {
  10000. return;
  10001. }
  10002. /* TODO (mid): Check the mg_send_http_error situations in this function
  10003. */
  10004. memset(&de.file, 0, sizeof(de.file));
  10005. if (!mg_stat(conn, path, &de.file)) {
  10006. mg_cry_internal(conn,
  10007. "%s: mg_stat(%s) failed: %s",
  10008. __func__,
  10009. path,
  10010. strerror(ERRNO));
  10011. }
  10012. if (de.file.last_modified) {
  10013. /* TODO (mid): This check does not seem to make any sense ! */
  10014. /* TODO (mid): Add a webdav unit test first, before changing
  10015. * anything here. */
  10016. mg_send_http_error(
  10017. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10018. return;
  10019. }
  10020. body_len = conn->data_len - conn->request_len;
  10021. if (body_len > 0) {
  10022. mg_send_http_error(
  10023. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10024. return;
  10025. }
  10026. rc = mg_mkdir(conn, path, 0755);
  10027. if (rc == 0) {
  10028. /* Create 201 "Created" response */
  10029. mg_response_header_start(conn, 201);
  10030. send_static_cache_header(conn);
  10031. send_additional_header(conn);
  10032. mg_response_header_add(conn, "Content-Length", "0", -1);
  10033. /* Send all headers - there is no body */
  10034. mg_response_header_send(conn);
  10035. } else {
  10036. if (errno == EEXIST) {
  10037. mg_send_http_error(
  10038. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10039. } else if (errno == EACCES) {
  10040. mg_send_http_error(
  10041. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10042. } else if (errno == ENOENT) {
  10043. mg_send_http_error(
  10044. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10045. } else {
  10046. mg_send_http_error(
  10047. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  10048. }
  10049. }
  10050. }
  10051. static void
  10052. put_file(struct mg_connection *conn, const char *path)
  10053. {
  10054. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10055. const char *range;
  10056. int64_t r1, r2;
  10057. int rc;
  10058. if (conn == NULL) {
  10059. return;
  10060. }
  10061. if (mg_stat(conn, path, &file.stat)) {
  10062. /* File already exists */
  10063. conn->status_code = 200;
  10064. if (file.stat.is_directory) {
  10065. /* This is an already existing directory,
  10066. * so there is nothing to do for the server. */
  10067. rc = 0;
  10068. } else {
  10069. /* File exists and is not a directory. */
  10070. /* Can it be replaced? */
  10071. /* Check if the server may write this file */
  10072. if (access(path, W_OK) == 0) {
  10073. /* Access granted */
  10074. rc = 1;
  10075. } else {
  10076. mg_send_http_error(
  10077. conn,
  10078. 403,
  10079. "Error: Put not possible\nReplacing %s is not allowed",
  10080. path);
  10081. return;
  10082. }
  10083. }
  10084. } else {
  10085. /* File should be created */
  10086. conn->status_code = 201;
  10087. rc = put_dir(conn, path);
  10088. }
  10089. if (rc == 0) {
  10090. /* put_dir returns 0 if path is a directory */
  10091. /* Create response */
  10092. mg_response_header_start(conn, conn->status_code);
  10093. send_no_cache_header(conn);
  10094. send_additional_header(conn);
  10095. mg_response_header_add(conn, "Content-Length", "0", -1);
  10096. /* Send all headers - there is no body */
  10097. mg_response_header_send(conn);
  10098. /* Request to create a directory has been fulfilled successfully.
  10099. * No need to put a file. */
  10100. return;
  10101. }
  10102. if (rc == -1) {
  10103. /* put_dir returns -1 if the path is too long */
  10104. mg_send_http_error(conn,
  10105. 414,
  10106. "Error: Path too long\nput_dir(%s): %s",
  10107. path,
  10108. strerror(ERRNO));
  10109. return;
  10110. }
  10111. if (rc == -2) {
  10112. /* put_dir returns -2 if the directory can not be created */
  10113. mg_send_http_error(conn,
  10114. 500,
  10115. "Error: Can not create directory\nput_dir(%s): %s",
  10116. path,
  10117. strerror(ERRNO));
  10118. return;
  10119. }
  10120. /* A file should be created or overwritten. */
  10121. /* Currently CivetWeb does not nead read+write access. */
  10122. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10123. || file.access.fp == NULL) {
  10124. (void)mg_fclose(&file.access);
  10125. mg_send_http_error(conn,
  10126. 500,
  10127. "Error: Can not create file\nfopen(%s): %s",
  10128. path,
  10129. strerror(ERRNO));
  10130. return;
  10131. }
  10132. fclose_on_exec(&file.access, conn);
  10133. range = mg_get_header(conn, "Content-Range");
  10134. r1 = r2 = 0;
  10135. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10136. conn->status_code = 206; /* Partial content */
  10137. fseeko(file.access.fp, r1, SEEK_SET);
  10138. }
  10139. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10140. /* forward_body_data failed.
  10141. * The error code has already been sent to the client,
  10142. * and conn->status_code is already set. */
  10143. (void)mg_fclose(&file.access);
  10144. return;
  10145. }
  10146. if (mg_fclose(&file.access) != 0) {
  10147. /* fclose failed. This might have different reasons, but a likely
  10148. * one is "no space on disk", http 507. */
  10149. conn->status_code = 507;
  10150. }
  10151. /* Create response (status_code has been set before) */
  10152. mg_response_header_start(conn, conn->status_code);
  10153. send_no_cache_header(conn);
  10154. send_additional_header(conn);
  10155. mg_response_header_add(conn, "Content-Length", "0", -1);
  10156. /* Send all headers - there is no body */
  10157. mg_response_header_send(conn);
  10158. }
  10159. static void
  10160. delete_file(struct mg_connection *conn, const char *path)
  10161. {
  10162. struct de de;
  10163. memset(&de.file, 0, sizeof(de.file));
  10164. if (!mg_stat(conn, path, &de.file)) {
  10165. /* mg_stat returns 0 if the file does not exist */
  10166. mg_send_http_error(conn,
  10167. 404,
  10168. "Error: Cannot delete file\nFile %s not found",
  10169. path);
  10170. return;
  10171. }
  10172. if (de.file.is_directory) {
  10173. if (remove_directory(conn, path)) {
  10174. /* Delete is successful: Return 204 without content. */
  10175. mg_send_http_error(conn, 204, "%s", "");
  10176. } else {
  10177. /* Delete is not successful: Return 500 (Server error). */
  10178. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10179. }
  10180. return;
  10181. }
  10182. /* This is an existing file (not a directory).
  10183. * Check if write permission is granted. */
  10184. if (access(path, W_OK) != 0) {
  10185. /* File is read only */
  10186. mg_send_http_error(
  10187. conn,
  10188. 403,
  10189. "Error: Delete not possible\nDeleting %s is not allowed",
  10190. path);
  10191. return;
  10192. }
  10193. /* Try to delete it. */
  10194. if (mg_remove(conn, path) == 0) {
  10195. /* Delete was successful: Return 204 without content. */
  10196. mg_response_header_start(conn, 204);
  10197. send_no_cache_header(conn);
  10198. send_additional_header(conn);
  10199. mg_response_header_add(conn, "Content-Length", "0", -1);
  10200. mg_response_header_send(conn);
  10201. } else {
  10202. /* Delete not successful (file locked). */
  10203. mg_send_http_error(conn,
  10204. 423,
  10205. "Error: Cannot delete file\nremove(%s): %s",
  10206. path,
  10207. strerror(ERRNO));
  10208. }
  10209. }
  10210. #endif /* !NO_FILES */
  10211. #if !defined(NO_FILESYSTEMS)
  10212. static void
  10213. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10214. static void
  10215. do_ssi_include(struct mg_connection *conn,
  10216. const char *ssi,
  10217. char *tag,
  10218. int include_level)
  10219. {
  10220. char file_name[MG_BUF_LEN], path[512], *p;
  10221. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10222. size_t len;
  10223. int truncated = 0;
  10224. if (conn == NULL) {
  10225. return;
  10226. }
  10227. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10228. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10229. * always < MG_BUF_LEN. */
  10230. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10231. /* File name is relative to the webserver root */
  10232. file_name[511] = 0;
  10233. (void)mg_snprintf(conn,
  10234. &truncated,
  10235. path,
  10236. sizeof(path),
  10237. "%s/%s",
  10238. conn->dom_ctx->config[DOCUMENT_ROOT],
  10239. file_name);
  10240. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10241. /* File name is relative to the webserver working directory
  10242. * or it is absolute system path */
  10243. file_name[511] = 0;
  10244. (void)
  10245. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10246. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10247. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10248. /* File name is relative to the currect document */
  10249. file_name[511] = 0;
  10250. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10251. if (!truncated) {
  10252. if ((p = strrchr(path, '/')) != NULL) {
  10253. p[1] = '\0';
  10254. }
  10255. len = strlen(path);
  10256. (void)mg_snprintf(conn,
  10257. &truncated,
  10258. path + len,
  10259. sizeof(path) - len,
  10260. "%s",
  10261. file_name);
  10262. }
  10263. } else {
  10264. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10265. return;
  10266. }
  10267. if (truncated) {
  10268. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10269. return;
  10270. }
  10271. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10272. mg_cry_internal(conn,
  10273. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10274. tag,
  10275. path,
  10276. strerror(ERRNO));
  10277. } else {
  10278. fclose_on_exec(&file.access, conn);
  10279. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10280. > 0) {
  10281. send_ssi_file(conn, path, &file, include_level + 1);
  10282. } else {
  10283. send_file_data(conn, &file, 0, INT64_MAX);
  10284. }
  10285. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10286. }
  10287. }
  10288. #if !defined(NO_POPEN)
  10289. static void
  10290. do_ssi_exec(struct mg_connection *conn, char *tag)
  10291. {
  10292. char cmd[1024] = "";
  10293. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10294. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10295. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10296. } else {
  10297. cmd[1023] = 0;
  10298. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10299. mg_cry_internal(conn,
  10300. "Cannot SSI #exec: [%s]: %s",
  10301. cmd,
  10302. strerror(ERRNO));
  10303. } else {
  10304. send_file_data(conn, &file, 0, INT64_MAX);
  10305. pclose(file.access.fp);
  10306. }
  10307. }
  10308. }
  10309. #endif /* !NO_POPEN */
  10310. static int
  10311. mg_fgetc(struct mg_file *filep)
  10312. {
  10313. if (filep == NULL) {
  10314. return EOF;
  10315. }
  10316. if (filep->access.fp != NULL) {
  10317. return fgetc(filep->access.fp);
  10318. } else {
  10319. return EOF;
  10320. }
  10321. }
  10322. static void
  10323. send_ssi_file(struct mg_connection *conn,
  10324. const char *path,
  10325. struct mg_file *filep,
  10326. int include_level)
  10327. {
  10328. char buf[MG_BUF_LEN];
  10329. int ch, len, in_tag, in_ssi_tag;
  10330. if (include_level > 10) {
  10331. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10332. return;
  10333. }
  10334. in_tag = in_ssi_tag = len = 0;
  10335. /* Read file, byte by byte, and look for SSI include tags */
  10336. while ((ch = mg_fgetc(filep)) != EOF) {
  10337. if (in_tag) {
  10338. /* We are in a tag, either SSI tag or html tag */
  10339. if (ch == '>') {
  10340. /* Tag is closing */
  10341. buf[len++] = '>';
  10342. if (in_ssi_tag) {
  10343. /* Handle SSI tag */
  10344. buf[len] = 0;
  10345. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10346. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10347. #if !defined(NO_POPEN)
  10348. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10349. do_ssi_exec(conn, buf + 9);
  10350. #endif /* !NO_POPEN */
  10351. } else {
  10352. mg_cry_internal(conn,
  10353. "%s: unknown SSI "
  10354. "command: \"%s\"",
  10355. path,
  10356. buf);
  10357. }
  10358. len = 0;
  10359. in_ssi_tag = in_tag = 0;
  10360. } else {
  10361. /* Not an SSI tag */
  10362. /* Flush buffer */
  10363. (void)mg_write(conn, buf, (size_t)len);
  10364. len = 0;
  10365. in_tag = 0;
  10366. }
  10367. } else {
  10368. /* Tag is still open */
  10369. buf[len++] = (char)(ch & 0xff);
  10370. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10371. /* All SSI tags start with <!--# */
  10372. in_ssi_tag = 1;
  10373. }
  10374. if ((len + 2) > (int)sizeof(buf)) {
  10375. /* Tag to long for buffer */
  10376. mg_cry_internal(conn, "%s: tag is too large", path);
  10377. return;
  10378. }
  10379. }
  10380. } else {
  10381. /* We are not in a tag yet. */
  10382. if (ch == '<') {
  10383. /* Tag is opening */
  10384. in_tag = 1;
  10385. if (len > 0) {
  10386. /* Flush current buffer.
  10387. * Buffer is filled with "len" bytes. */
  10388. (void)mg_write(conn, buf, (size_t)len);
  10389. }
  10390. /* Store the < */
  10391. len = 1;
  10392. buf[0] = '<';
  10393. } else {
  10394. /* No Tag */
  10395. /* Add data to buffer */
  10396. buf[len++] = (char)(ch & 0xff);
  10397. /* Flush if buffer is full */
  10398. if (len == (int)sizeof(buf)) {
  10399. mg_write(conn, buf, (size_t)len);
  10400. len = 0;
  10401. }
  10402. }
  10403. }
  10404. }
  10405. /* Send the rest of buffered data */
  10406. if (len > 0) {
  10407. mg_write(conn, buf, (size_t)len);
  10408. }
  10409. }
  10410. static void
  10411. handle_ssi_file_request(struct mg_connection *conn,
  10412. const char *path,
  10413. struct mg_file *filep)
  10414. {
  10415. char date[64];
  10416. time_t curtime = time(NULL);
  10417. const char *cors_orig_cfg;
  10418. const char *cors1, *cors2;
  10419. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10420. return;
  10421. }
  10422. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10423. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10424. /* Cross-origin resource sharing (CORS). */
  10425. cors1 = "Access-Control-Allow-Origin";
  10426. cors2 = cors_orig_cfg;
  10427. } else {
  10428. cors1 = cors2 = "";
  10429. }
  10430. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10431. /* File exists (precondition for calling this function),
  10432. * but can not be opened by the server. */
  10433. mg_send_http_error(conn,
  10434. 500,
  10435. "Error: Cannot read file\nfopen(%s): %s",
  10436. path,
  10437. strerror(ERRNO));
  10438. } else {
  10439. /* Set "must_close" for HTTP/1.x, since we do not know the
  10440. * content length */
  10441. conn->must_close = 1;
  10442. gmt_time_string(date, sizeof(date), &curtime);
  10443. fclose_on_exec(&filep->access, conn);
  10444. /* 200 OK response */
  10445. mg_response_header_start(conn, 200);
  10446. send_no_cache_header(conn);
  10447. send_additional_header(conn);
  10448. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10449. if (cors1[0]) {
  10450. mg_response_header_add(conn, cors1, cors2, -1);
  10451. }
  10452. mg_response_header_send(conn);
  10453. /* Header sent, now send body */
  10454. send_ssi_file(conn, path, filep, 0);
  10455. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10456. }
  10457. }
  10458. #endif /* NO_FILESYSTEMS */
  10459. #if !defined(NO_FILES)
  10460. static void
  10461. send_options(struct mg_connection *conn)
  10462. {
  10463. if (!conn) {
  10464. return;
  10465. }
  10466. /* We do not set a "Cache-Control" header here, but leave the default.
  10467. * Since browsers do not send an OPTIONS request, we can not test the
  10468. * effect anyway. */
  10469. mg_response_header_start(conn, 200);
  10470. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10471. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10472. /* Use the same as before */
  10473. mg_response_header_add(
  10474. conn,
  10475. "Allow",
  10476. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10477. -1);
  10478. mg_response_header_add(conn, "DAV", "1", -1);
  10479. } else {
  10480. /* TODO: Check this later for HTTP/2 */
  10481. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10482. }
  10483. send_additional_header(conn);
  10484. mg_response_header_send(conn);
  10485. }
  10486. /* Writes PROPFIND properties for a collection element */
  10487. static int
  10488. print_props(struct mg_connection *conn,
  10489. const char *uri,
  10490. const char *name,
  10491. struct mg_file_stat *filep)
  10492. {
  10493. size_t href_size, i, j;
  10494. int len;
  10495. char *href, mtime[64];
  10496. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10497. return 0;
  10498. }
  10499. /* Estimate worst case size for encoding */
  10500. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10501. href = (char *)mg_malloc(href_size);
  10502. if (href == NULL) {
  10503. return 0;
  10504. }
  10505. len = mg_url_encode(uri, href, href_size);
  10506. if (len >= 0) {
  10507. /* Append an extra string */
  10508. mg_url_encode(name, href + len, href_size - (size_t)len);
  10509. }
  10510. /* Directory separator should be preserved. */
  10511. for (i = j = 0; href[i]; j++) {
  10512. if (!strncmp(href + i, "%2f", 3)) {
  10513. href[j] = '/';
  10514. i += 3;
  10515. } else {
  10516. href[j] = href[i++];
  10517. }
  10518. }
  10519. href[j] = '\0';
  10520. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10521. mg_printf(conn,
  10522. "<d:response>"
  10523. "<d:href>%s</d:href>"
  10524. "<d:propstat>"
  10525. "<d:prop>"
  10526. "<d:resourcetype>%s</d:resourcetype>"
  10527. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10528. "<d:getlastmodified>%s</d:getlastmodified>"
  10529. "</d:prop>"
  10530. "<d:status>HTTP/1.1 200 OK</d:status>"
  10531. "</d:propstat>"
  10532. "</d:response>\n",
  10533. href,
  10534. filep->is_directory ? "<d:collection/>" : "",
  10535. filep->size,
  10536. mtime);
  10537. mg_free(href);
  10538. return 1;
  10539. }
  10540. static int
  10541. print_dav_dir_entry(struct de *de, void *data)
  10542. {
  10543. struct mg_connection *conn = (struct mg_connection *)data;
  10544. if (!de || !conn
  10545. || !print_props(
  10546. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10547. /* stop scan */
  10548. return 1;
  10549. }
  10550. return 0;
  10551. }
  10552. static void
  10553. handle_propfind(struct mg_connection *conn,
  10554. const char *path,
  10555. struct mg_file_stat *filep)
  10556. {
  10557. const char *depth = mg_get_header(conn, "Depth");
  10558. char date[64];
  10559. time_t curtime = time(NULL);
  10560. gmt_time_string(date, sizeof(date), &curtime);
  10561. if (!conn || !path || !filep || !conn->dom_ctx) {
  10562. return;
  10563. }
  10564. conn->must_close = 1;
  10565. /* return 207 "Multi-Status" */
  10566. mg_response_header_start(conn, 207);
  10567. send_static_cache_header(conn);
  10568. send_additional_header(conn);
  10569. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10570. mg_response_header_send(conn);
  10571. /* Content */
  10572. mg_printf(conn,
  10573. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10574. "<d:multistatus xmlns:d='DAV:'>\n");
  10575. /* Print properties for the requested resource itself */
  10576. print_props(conn, conn->request_info.local_uri, "", filep);
  10577. /* If it is a directory, print directory entries too if Depth is not 0
  10578. */
  10579. if (filep->is_directory
  10580. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10581. "yes")
  10582. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10583. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10584. }
  10585. mg_printf(conn, "%s\n", "</d:multistatus>");
  10586. }
  10587. #endif
  10588. void
  10589. mg_lock_connection(struct mg_connection *conn)
  10590. {
  10591. if (conn) {
  10592. (void)pthread_mutex_lock(&conn->mutex);
  10593. }
  10594. }
  10595. void
  10596. mg_unlock_connection(struct mg_connection *conn)
  10597. {
  10598. if (conn) {
  10599. (void)pthread_mutex_unlock(&conn->mutex);
  10600. }
  10601. }
  10602. void
  10603. mg_lock_context(struct mg_context *ctx)
  10604. {
  10605. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10606. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10607. }
  10608. }
  10609. void
  10610. mg_unlock_context(struct mg_context *ctx)
  10611. {
  10612. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10613. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10614. }
  10615. }
  10616. #if defined(USE_LUA)
  10617. #include "mod_lua.inl"
  10618. #endif /* USE_LUA */
  10619. #if defined(USE_DUKTAPE)
  10620. #include "mod_duktape.inl"
  10621. #endif /* USE_DUKTAPE */
  10622. #if defined(USE_WEBSOCKET)
  10623. #if !defined(NO_SSL_DL)
  10624. #define SHA_API static
  10625. #include "sha1.inl"
  10626. #endif
  10627. static int
  10628. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10629. {
  10630. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10631. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10632. size_t dst_len = sizeof(b64_sha);
  10633. SHA_CTX sha_ctx;
  10634. int truncated;
  10635. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10636. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10637. if (truncated) {
  10638. conn->must_close = 1;
  10639. return 0;
  10640. }
  10641. DEBUG_TRACE("%s", "Send websocket handshake");
  10642. SHA1_Init(&sha_ctx);
  10643. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10644. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10645. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  10646. mg_printf(conn,
  10647. "HTTP/1.1 101 Switching Protocols\r\n"
  10648. "Upgrade: websocket\r\n"
  10649. "Connection: Upgrade\r\n"
  10650. "Sec-WebSocket-Accept: %s\r\n",
  10651. b64_sha);
  10652. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10653. // Send negotiated compression extension parameters
  10654. websocket_deflate_response(conn);
  10655. #endif
  10656. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10657. mg_printf(conn,
  10658. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10659. conn->request_info.acceptedWebSocketSubprotocol);
  10660. } else {
  10661. mg_printf(conn, "%s", "\r\n");
  10662. }
  10663. return 1;
  10664. }
  10665. #if !defined(MG_MAX_UNANSWERED_PING)
  10666. /* Configuration of the maximum number of websocket PINGs that might
  10667. * stay unanswered before the connection is considered broken.
  10668. * Note: The name of this define may still change (until it is
  10669. * defined as a compile parameter in a documentation).
  10670. */
  10671. #define MG_MAX_UNANSWERED_PING (5)
  10672. #endif
  10673. static void
  10674. read_websocket(struct mg_connection *conn,
  10675. mg_websocket_data_handler ws_data_handler,
  10676. void *callback_data)
  10677. {
  10678. /* Pointer to the beginning of the portion of the incoming websocket
  10679. * message queue.
  10680. * The original websocket upgrade request is never removed, so the queue
  10681. * begins after it. */
  10682. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10683. int n, error, exit_by_callback;
  10684. int ret;
  10685. /* body_len is the length of the entire queue in bytes
  10686. * len is the length of the current message
  10687. * data_len is the length of the current message's data payload
  10688. * header_len is the length of the current message's header */
  10689. size_t i, len, mask_len = 0, header_len, body_len;
  10690. uint64_t data_len = 0;
  10691. /* "The masking key is a 32-bit value chosen at random by the client."
  10692. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10693. */
  10694. unsigned char mask[4];
  10695. /* data points to the place where the message is stored when passed to
  10696. * the websocket_data callback. This is either mem on the stack, or a
  10697. * dynamically allocated buffer if it is too large. */
  10698. unsigned char mem[4096];
  10699. unsigned char mop; /* mask flag and opcode */
  10700. /* Variables used for connection monitoring */
  10701. double timeout = -1.0;
  10702. int enable_ping_pong = 0;
  10703. int ping_count = 0;
  10704. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10705. enable_ping_pong =
  10706. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10707. "yes");
  10708. }
  10709. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10710. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10711. }
  10712. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10713. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10714. }
  10715. if (timeout <= 0.0) {
  10716. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10717. }
  10718. /* Enter data processing loop */
  10719. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10720. conn->request_info.remote_addr,
  10721. conn->request_info.remote_port);
  10722. conn->in_websocket_handling = 1;
  10723. mg_set_thread_name("wsock");
  10724. /* Loop continuously, reading messages from the socket, invoking the
  10725. * callback, and waiting repeatedly until an error occurs. */
  10726. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10727. && (!conn->must_close)) {
  10728. header_len = 0;
  10729. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10730. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10731. len = buf[1] & 127;
  10732. mask_len = (buf[1] & 128) ? 4 : 0;
  10733. if ((len < 126) && (body_len >= mask_len)) {
  10734. /* inline 7-bit length field */
  10735. data_len = len;
  10736. header_len = 2 + mask_len;
  10737. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10738. /* 16-bit length field */
  10739. header_len = 4 + mask_len;
  10740. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10741. } else if (body_len >= (10 + mask_len)) {
  10742. /* 64-bit length field */
  10743. uint32_t l1, l2;
  10744. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10745. memcpy(&l2, &buf[6], 4);
  10746. header_len = 10 + mask_len;
  10747. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10748. if (data_len > (uint64_t)0x7FFF0000ul) {
  10749. /* no can do */
  10750. mg_cry_internal(
  10751. conn,
  10752. "%s",
  10753. "websocket out of memory; closing connection");
  10754. break;
  10755. }
  10756. }
  10757. }
  10758. if ((header_len > 0) && (body_len >= header_len)) {
  10759. /* Allocate space to hold websocket payload */
  10760. unsigned char *data = mem;
  10761. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10762. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10763. conn->phys_ctx);
  10764. if (data == NULL) {
  10765. /* Allocation failed, exit the loop and then close the
  10766. * connection */
  10767. mg_cry_internal(
  10768. conn,
  10769. "%s",
  10770. "websocket out of memory; closing connection");
  10771. break;
  10772. }
  10773. }
  10774. /* Copy the mask before we shift the queue and destroy it */
  10775. if (mask_len > 0) {
  10776. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10777. } else {
  10778. memset(mask, 0, sizeof(mask));
  10779. }
  10780. /* Read frame payload from the first message in the queue into
  10781. * data and advance the queue by moving the memory in place. */
  10782. DEBUG_ASSERT(body_len >= header_len);
  10783. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10784. mop = buf[0]; /* current mask and opcode */
  10785. /* Overflow case */
  10786. len = body_len - header_len;
  10787. memcpy(data, buf + header_len, len);
  10788. error = 0;
  10789. while ((uint64_t)len < data_len) {
  10790. n = pull_inner(NULL,
  10791. conn,
  10792. (char *)(data + len),
  10793. (int)(data_len - len),
  10794. timeout);
  10795. if (n <= -2) {
  10796. error = 1;
  10797. break;
  10798. } else if (n > 0) {
  10799. len += (size_t)n;
  10800. } else {
  10801. /* Timeout: should retry */
  10802. /* TODO: retry condition */
  10803. }
  10804. }
  10805. if (error) {
  10806. mg_cry_internal(
  10807. conn,
  10808. "%s",
  10809. "Websocket pull failed; closing connection");
  10810. if (data != mem) {
  10811. mg_free(data);
  10812. }
  10813. break;
  10814. }
  10815. conn->data_len = conn->request_len;
  10816. } else {
  10817. mop = buf[0]; /* current mask and opcode, overwritten by
  10818. * memmove() */
  10819. /* Length of the message being read at the front of the
  10820. * queue. Cast to 31 bit is OK, since we limited
  10821. * data_len before. */
  10822. len = (size_t)data_len + header_len;
  10823. /* Copy the data payload into the data pointer for the
  10824. * callback. Cast to 31 bit is OK, since we
  10825. * limited data_len */
  10826. memcpy(data, buf + header_len, (size_t)data_len);
  10827. /* Move the queue forward len bytes */
  10828. memmove(buf, buf + len, body_len - len);
  10829. /* Mark the queue as advanced */
  10830. conn->data_len -= (int)len;
  10831. }
  10832. /* Apply mask if necessary */
  10833. if (mask_len > 0) {
  10834. for (i = 0; i < (size_t)data_len; i++) {
  10835. data[i] ^= mask[i & 3];
  10836. }
  10837. }
  10838. exit_by_callback = 0;
  10839. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10840. /* filter PONG messages */
  10841. DEBUG_TRACE("PONG from %s:%u",
  10842. conn->request_info.remote_addr,
  10843. conn->request_info.remote_port);
  10844. /* No unanwered PINGs left */
  10845. ping_count = 0;
  10846. } else if (enable_ping_pong
  10847. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10848. /* reply PING messages */
  10849. DEBUG_TRACE("Reply PING from %s:%u",
  10850. conn->request_info.remote_addr,
  10851. conn->request_info.remote_port);
  10852. ret = mg_websocket_write(conn,
  10853. MG_WEBSOCKET_OPCODE_PONG,
  10854. (char *)data,
  10855. (size_t)data_len);
  10856. if (ret <= 0) {
  10857. /* Error: send failed */
  10858. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10859. break;
  10860. }
  10861. } else {
  10862. /* Exit the loop if callback signals to exit (server side),
  10863. * or "connection close" opcode received (client side). */
  10864. if (ws_data_handler != NULL) {
  10865. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10866. if (mop & 0x40) {
  10867. /* Inflate the data received if bit RSV1 is set. */
  10868. if (!conn->websocket_deflate_initialized) {
  10869. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10870. exit_by_callback = 1;
  10871. }
  10872. if (!exit_by_callback) {
  10873. size_t inflate_buf_size_old = 0;
  10874. size_t inflate_buf_size =
  10875. data_len
  10876. * 4; // Initial guess of the inflated message
  10877. // size. We double the memory when needed.
  10878. Bytef *inflated = NULL;
  10879. Bytef *new_mem = NULL;
  10880. conn->websocket_inflate_state.avail_in =
  10881. (uInt)(data_len + 4);
  10882. conn->websocket_inflate_state.next_in = data;
  10883. // Add trailing 0x00 0x00 0xff 0xff bytes
  10884. data[data_len] = '\x00';
  10885. data[data_len + 1] = '\x00';
  10886. data[data_len + 2] = '\xff';
  10887. data[data_len + 3] = '\xff';
  10888. do {
  10889. if (inflate_buf_size_old == 0) {
  10890. new_mem =
  10891. (Bytef *)mg_calloc(inflate_buf_size,
  10892. sizeof(Bytef));
  10893. } else {
  10894. inflate_buf_size *= 2;
  10895. new_mem =
  10896. (Bytef *)mg_realloc(inflated,
  10897. inflate_buf_size);
  10898. }
  10899. if (new_mem == NULL) {
  10900. mg_cry_internal(
  10901. conn,
  10902. "Out of memory: Cannot allocate "
  10903. "inflate buffer of %lu bytes",
  10904. (unsigned long)inflate_buf_size);
  10905. exit_by_callback = 1;
  10906. break;
  10907. }
  10908. inflated = new_mem;
  10909. conn->websocket_inflate_state.avail_out =
  10910. (uInt)(inflate_buf_size
  10911. - inflate_buf_size_old);
  10912. conn->websocket_inflate_state.next_out =
  10913. inflated + inflate_buf_size_old;
  10914. ret = inflate(&conn->websocket_inflate_state,
  10915. Z_SYNC_FLUSH);
  10916. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  10917. || ret == Z_MEM_ERROR) {
  10918. mg_cry_internal(
  10919. conn,
  10920. "ZLIB inflate error: %i %s",
  10921. ret,
  10922. (conn->websocket_inflate_state.msg
  10923. ? conn->websocket_inflate_state.msg
  10924. : "<no error message>"));
  10925. exit_by_callback = 1;
  10926. break;
  10927. }
  10928. inflate_buf_size_old = inflate_buf_size;
  10929. } while (conn->websocket_inflate_state.avail_out
  10930. == 0);
  10931. inflate_buf_size -=
  10932. conn->websocket_inflate_state.avail_out;
  10933. if (!ws_data_handler(conn,
  10934. mop,
  10935. (char *)inflated,
  10936. inflate_buf_size,
  10937. callback_data)) {
  10938. exit_by_callback = 1;
  10939. }
  10940. mg_free(inflated);
  10941. }
  10942. } else
  10943. #endif
  10944. if (!ws_data_handler(conn,
  10945. mop,
  10946. (char *)data,
  10947. (size_t)data_len,
  10948. callback_data)) {
  10949. exit_by_callback = 1;
  10950. }
  10951. }
  10952. }
  10953. /* It a buffer has been allocated, free it again */
  10954. if (data != mem) {
  10955. mg_free(data);
  10956. }
  10957. if (exit_by_callback) {
  10958. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10959. conn->request_info.remote_addr,
  10960. conn->request_info.remote_port);
  10961. break;
  10962. }
  10963. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10964. /* Opcode == 8, connection close */
  10965. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10966. conn->request_info.remote_addr,
  10967. conn->request_info.remote_port);
  10968. break;
  10969. }
  10970. /* Not breaking the loop, process next websocket frame. */
  10971. } else {
  10972. /* Read from the socket into the next available location in the
  10973. * message queue. */
  10974. n = pull_inner(NULL,
  10975. conn,
  10976. conn->buf + conn->data_len,
  10977. conn->buf_size - conn->data_len,
  10978. timeout);
  10979. if (n <= -2) {
  10980. /* Error, no bytes read */
  10981. DEBUG_TRACE("PULL from %s:%u failed",
  10982. conn->request_info.remote_addr,
  10983. conn->request_info.remote_port);
  10984. break;
  10985. }
  10986. if (n > 0) {
  10987. conn->data_len += n;
  10988. /* Reset open PING count */
  10989. ping_count = 0;
  10990. } else {
  10991. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10992. && (!conn->must_close)) {
  10993. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10994. /* Stop sending PING */
  10995. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10996. "- closing connection",
  10997. ping_count,
  10998. conn->request_info.remote_addr,
  10999. conn->request_info.remote_port);
  11000. break;
  11001. }
  11002. if (enable_ping_pong) {
  11003. /* Send Websocket PING message */
  11004. DEBUG_TRACE("PING to %s:%u",
  11005. conn->request_info.remote_addr,
  11006. conn->request_info.remote_port);
  11007. ret = mg_websocket_write(conn,
  11008. MG_WEBSOCKET_OPCODE_PING,
  11009. NULL,
  11010. 0);
  11011. if (ret <= 0) {
  11012. /* Error: send failed */
  11013. DEBUG_TRACE("Send PING failed (%i)", ret);
  11014. break;
  11015. }
  11016. ping_count++;
  11017. }
  11018. }
  11019. /* Timeout: should retry */
  11020. /* TODO: get timeout def */
  11021. }
  11022. }
  11023. }
  11024. /* Leave data processing loop */
  11025. mg_set_thread_name("worker");
  11026. conn->in_websocket_handling = 0;
  11027. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11028. conn->request_info.remote_addr,
  11029. conn->request_info.remote_port);
  11030. }
  11031. static int
  11032. mg_websocket_write_exec(struct mg_connection *conn,
  11033. int opcode,
  11034. const char *data,
  11035. size_t dataLen,
  11036. uint32_t masking_key)
  11037. {
  11038. unsigned char header[14];
  11039. size_t headerLen;
  11040. int retval;
  11041. #if defined(GCC_DIAGNOSTIC)
  11042. /* Disable spurious conversion warning for GCC */
  11043. #pragma GCC diagnostic push
  11044. #pragma GCC diagnostic ignored "-Wconversion"
  11045. #endif
  11046. /* Note that POSIX/Winsock's send() is threadsafe
  11047. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11048. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11049. * push(), although that is only a problem if the packet is large or
  11050. * outgoing buffer is full). */
  11051. /* TODO: Check if this lock should be moved to user land.
  11052. * Currently the server sets this lock for websockets, but
  11053. * not for any other connection. It must be set for every
  11054. * conn read/written by more than one thread, no matter if
  11055. * it is a websocket or regular connection. */
  11056. (void)mg_lock_connection(conn);
  11057. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11058. size_t deflated_size = 0;
  11059. Bytef *deflated = 0;
  11060. // Deflate websocket messages over 100kb
  11061. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11062. if (use_deflate) {
  11063. if (!conn->websocket_deflate_initialized) {
  11064. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11065. return 0;
  11066. }
  11067. // Deflating the message
  11068. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11069. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11070. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11071. deflated_size = (Bytef *)compressBound((uLong)dataLen);
  11072. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11073. if (deflated == NULL) {
  11074. mg_cry_internal(
  11075. conn,
  11076. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11077. (unsigned long)deflated_size);
  11078. mg_unlock_connection(conn);
  11079. return -1;
  11080. }
  11081. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11082. conn->websocket_deflate_state.next_out = deflated;
  11083. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11084. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11085. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11086. } else
  11087. #endif
  11088. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11089. #if defined(GCC_DIAGNOSTIC)
  11090. #pragma GCC diagnostic pop
  11091. #endif
  11092. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11093. if (dataLen < 126) {
  11094. /* inline 7-bit length field */
  11095. header[1] = (unsigned char)dataLen;
  11096. headerLen = 2;
  11097. } else if (dataLen <= 0xFFFF) {
  11098. /* 16-bit length field */
  11099. uint16_t len = htons((uint16_t)dataLen);
  11100. header[1] = 126;
  11101. memcpy(header + 2, &len, 2);
  11102. headerLen = 4;
  11103. } else {
  11104. /* 64-bit length field */
  11105. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11106. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11107. header[1] = 127;
  11108. memcpy(header + 2, &len1, 4);
  11109. memcpy(header + 6, &len2, 4);
  11110. headerLen = 10;
  11111. }
  11112. if (masking_key) {
  11113. /* add mask */
  11114. header[1] |= 0x80;
  11115. memcpy(header + headerLen, &masking_key, 4);
  11116. headerLen += 4;
  11117. }
  11118. retval = mg_write(conn, header, headerLen);
  11119. if (retval != (int)headerLen) {
  11120. /* Did not send complete header */
  11121. retval = -1;
  11122. } else {
  11123. if (dataLen > 0) {
  11124. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11125. if (use_deflate) {
  11126. retval = mg_write(conn, deflated, dataLen);
  11127. mg_free(deflated);
  11128. } else
  11129. #endif
  11130. retval = mg_write(conn, data, dataLen);
  11131. }
  11132. /* if dataLen == 0, the header length (2) is returned */
  11133. }
  11134. /* TODO: Remove this unlock as well, when lock is removed. */
  11135. mg_unlock_connection(conn);
  11136. return retval;
  11137. }
  11138. int
  11139. mg_websocket_write(struct mg_connection *conn,
  11140. int opcode,
  11141. const char *data,
  11142. size_t dataLen)
  11143. {
  11144. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11145. }
  11146. static void
  11147. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11148. {
  11149. size_t i = 0;
  11150. i = 0;
  11151. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11152. /* Convert in 32 bit words, if data is 4 byte aligned */
  11153. while (i < (in_len - 3)) {
  11154. *(uint32_t *)(void *)(out + i) =
  11155. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11156. i += 4;
  11157. }
  11158. }
  11159. if (i != in_len) {
  11160. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11161. while (i < in_len) {
  11162. *(uint8_t *)(void *)(out + i) =
  11163. *(uint8_t *)(void *)(in + i)
  11164. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11165. i++;
  11166. }
  11167. }
  11168. }
  11169. int
  11170. mg_websocket_client_write(struct mg_connection *conn,
  11171. int opcode,
  11172. const char *data,
  11173. size_t dataLen)
  11174. {
  11175. int retval = -1;
  11176. char *masked_data =
  11177. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11178. uint32_t masking_key = 0;
  11179. if (masked_data == NULL) {
  11180. /* Return -1 in an error case */
  11181. mg_cry_internal(conn,
  11182. "%s",
  11183. "Cannot allocate buffer for masked websocket response: "
  11184. "Out of memory");
  11185. return -1;
  11186. }
  11187. do {
  11188. /* Get a masking key - but not 0 */
  11189. masking_key = (uint32_t)get_random();
  11190. } while (masking_key == 0);
  11191. mask_data(data, dataLen, masking_key, masked_data);
  11192. retval = mg_websocket_write_exec(
  11193. conn, opcode, masked_data, dataLen, masking_key);
  11194. mg_free(masked_data);
  11195. return retval;
  11196. }
  11197. static void
  11198. handle_websocket_request(struct mg_connection *conn,
  11199. const char *path,
  11200. int is_callback_resource,
  11201. struct mg_websocket_subprotocols *subprotocols,
  11202. mg_websocket_connect_handler ws_connect_handler,
  11203. mg_websocket_ready_handler ws_ready_handler,
  11204. mg_websocket_data_handler ws_data_handler,
  11205. mg_websocket_close_handler ws_close_handler,
  11206. void *cbData)
  11207. {
  11208. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11209. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11210. ptrdiff_t lua_websock = 0;
  11211. #if !defined(USE_LUA)
  11212. (void)path;
  11213. #endif
  11214. /* Step 1: Check websocket protocol version. */
  11215. /* Step 1.1: Check Sec-WebSocket-Key. */
  11216. if (!websock_key) {
  11217. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11218. * requires a Sec-WebSocket-Key header.
  11219. */
  11220. /* It could be the hixie draft version
  11221. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11222. */
  11223. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11224. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11225. char key3[8];
  11226. if ((key1 != NULL) && (key2 != NULL)) {
  11227. /* This version uses 8 byte body data in a GET request */
  11228. conn->content_len = 8;
  11229. if (8 == mg_read(conn, key3, 8)) {
  11230. /* This is the hixie version */
  11231. mg_send_http_error(conn,
  11232. 426,
  11233. "%s",
  11234. "Protocol upgrade to RFC 6455 required");
  11235. return;
  11236. }
  11237. }
  11238. /* This is an unknown version */
  11239. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11240. return;
  11241. }
  11242. /* Step 1.2: Check websocket protocol version. */
  11243. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11244. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11245. /* Reject wrong versions */
  11246. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11247. return;
  11248. }
  11249. /* Step 1.3: Could check for "Host", but we do not really nead this
  11250. * value for anything, so just ignore it. */
  11251. /* Step 2: If a callback is responsible, call it. */
  11252. if (is_callback_resource) {
  11253. /* Step 2.1 check and select subprotocol */
  11254. const char *protocols[64]; // max 64 headers
  11255. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11256. "Sec-WebSocket-Protocol",
  11257. protocols,
  11258. 64);
  11259. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11260. int headerNo, idx;
  11261. size_t len;
  11262. const char *sep, *curSubProtocol,
  11263. *acceptedWebSocketSubprotocol = NULL;
  11264. /* look for matching subprotocol */
  11265. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11266. /* There might be multiple headers ... */
  11267. const char *protocol = protocols[headerNo];
  11268. curSubProtocol = protocol;
  11269. /* ... and in every header there might be a , separated list */
  11270. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11271. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11272. curSubProtocol++;
  11273. sep = strchr(curSubProtocol, ',');
  11274. if (sep) {
  11275. len = (size_t)(sep - curSubProtocol);
  11276. } else {
  11277. len = strlen(curSubProtocol);
  11278. }
  11279. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11280. // COMPARE: curSubProtocol ==
  11281. // subprotocols->subprotocols[idx]
  11282. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11283. && (strncmp(curSubProtocol,
  11284. subprotocols->subprotocols[idx],
  11285. len)
  11286. == 0)) {
  11287. acceptedWebSocketSubprotocol =
  11288. subprotocols->subprotocols[idx];
  11289. break;
  11290. }
  11291. }
  11292. curSubProtocol += len;
  11293. }
  11294. }
  11295. conn->request_info.acceptedWebSocketSubprotocol =
  11296. acceptedWebSocketSubprotocol;
  11297. }
  11298. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11299. websocket_deflate_negotiate(conn);
  11300. #endif
  11301. if ((ws_connect_handler != NULL)
  11302. && (ws_connect_handler(conn, cbData) != 0)) {
  11303. /* C callback has returned non-zero, do not proceed with
  11304. * handshake.
  11305. */
  11306. /* Note that C callbacks are no longer called when Lua is
  11307. * responsible, so C can no longer filter callbacks for Lua. */
  11308. return;
  11309. }
  11310. }
  11311. #if defined(USE_LUA)
  11312. /* Step 3: No callback. Check if Lua is responsible. */
  11313. else {
  11314. /* Step 3.1: Check if Lua is responsible. */
  11315. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11316. lua_websock = match_prefix_strlen(
  11317. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11318. }
  11319. if (lua_websock) {
  11320. /* Step 3.2: Lua is responsible: call it. */
  11321. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11322. if (!conn->lua_websocket_state) {
  11323. /* Lua rejected the new client */
  11324. return;
  11325. }
  11326. }
  11327. }
  11328. #endif
  11329. /* Step 4: Check if there is a responsible websocket handler. */
  11330. if (!is_callback_resource && !lua_websock) {
  11331. /* There is no callback, and Lua is not responsible either. */
  11332. /* Reply with a 404 Not Found. We are still at a standard
  11333. * HTTP request here, before the websocket handshake, so
  11334. * we can still send standard HTTP error replies. */
  11335. mg_send_http_error(conn, 404, "%s", "Not found");
  11336. return;
  11337. }
  11338. /* Step 5: The websocket connection has been accepted */
  11339. if (!send_websocket_handshake(conn, websock_key)) {
  11340. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11341. return;
  11342. }
  11343. /* Step 6: Call the ready handler */
  11344. if (is_callback_resource) {
  11345. if (ws_ready_handler != NULL) {
  11346. ws_ready_handler(conn, cbData);
  11347. }
  11348. #if defined(USE_LUA)
  11349. } else if (lua_websock) {
  11350. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11351. /* the ready handler returned false */
  11352. return;
  11353. }
  11354. #endif
  11355. }
  11356. /* Step 7: Enter the read loop */
  11357. if (is_callback_resource) {
  11358. read_websocket(conn, ws_data_handler, cbData);
  11359. #if defined(USE_LUA)
  11360. } else if (lua_websock) {
  11361. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11362. #endif
  11363. }
  11364. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11365. /* Step 8: Close the deflate & inflate buffers */
  11366. if (conn->websocket_deflate_initialized) {
  11367. deflateEnd(&conn->websocket_deflate_state);
  11368. inflateEnd(&conn->websocket_inflate_state);
  11369. }
  11370. #endif
  11371. /* Step 9: Call the close handler */
  11372. if (ws_close_handler) {
  11373. ws_close_handler(conn, cbData);
  11374. }
  11375. }
  11376. #endif /* !USE_WEBSOCKET */
  11377. /* Is upgrade request:
  11378. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11379. * 1 = upgrade to websocket
  11380. * 2 = upgrade to HTTP/2
  11381. * -1 = upgrade to unknown protocol
  11382. */
  11383. static int
  11384. should_switch_to_protocol(const struct mg_connection *conn)
  11385. {
  11386. const char *upgrade, *connection;
  11387. /* A websocket protocoll has the following HTTP headers:
  11388. *
  11389. * Connection: Upgrade
  11390. * Upgrade: Websocket
  11391. */
  11392. connection = mg_get_header(conn, "Connection");
  11393. if (connection == NULL) {
  11394. return PROTOCOL_TYPE_HTTP1;
  11395. }
  11396. if (!mg_strcasestr(connection, "upgrade")) {
  11397. return PROTOCOL_TYPE_HTTP1;
  11398. }
  11399. upgrade = mg_get_header(conn, "Upgrade");
  11400. if (upgrade == NULL) {
  11401. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11402. return -1;
  11403. }
  11404. /* Upgrade to ... */
  11405. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11406. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11407. * "Sec-WebSocket-Version" are also required.
  11408. * Don't check them here, since even an unsupported websocket protocol
  11409. * request still IS a websocket request (in contrast to a standard HTTP
  11410. * request). It will fail later in handle_websocket_request.
  11411. */
  11412. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11413. }
  11414. if (0 != mg_strcasestr(upgrade, "h2")) {
  11415. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11416. }
  11417. /* Upgrade to another protocol */
  11418. return -1;
  11419. }
  11420. static int
  11421. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11422. {
  11423. int n;
  11424. unsigned int a, b, c, d, slash;
  11425. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11426. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11427. // integer value, but function will not report conversion
  11428. // errors; consider using 'strtol' instead
  11429. slash = 32;
  11430. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11431. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11432. // an integer value, but function will not report conversion
  11433. // errors; consider using 'strtol' instead
  11434. n = 0;
  11435. }
  11436. }
  11437. if ((n > 0) && ((size_t)n == vec->len)) {
  11438. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11439. /* IPv4 format */
  11440. if (sa->sa.sa_family == AF_INET) {
  11441. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11442. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11443. | ((uint32_t)c << 8) | (uint32_t)d;
  11444. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11445. return (ip & mask) == net;
  11446. }
  11447. return 0;
  11448. }
  11449. }
  11450. #if defined(USE_IPV6)
  11451. else {
  11452. char ad[50];
  11453. const char *p;
  11454. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11455. slash = 128;
  11456. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11457. n = 0;
  11458. }
  11459. }
  11460. if ((n <= 0) && no_strict) {
  11461. /* no square brackets? */
  11462. p = strchr(vec->ptr, '/');
  11463. if (p && (p < (vec->ptr + vec->len))) {
  11464. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11465. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11466. n += (int)(p - vec->ptr);
  11467. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11468. } else {
  11469. n = 0;
  11470. }
  11471. } else if (vec->len < sizeof(ad)) {
  11472. n = (int)vec->len;
  11473. slash = 128;
  11474. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11475. }
  11476. }
  11477. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11478. p = ad;
  11479. c = 0;
  11480. /* zone indexes are unsupported, at least two colons are needed */
  11481. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11482. if (*(p++) == ':') {
  11483. c++;
  11484. }
  11485. }
  11486. if ((*p == '\0') && (c >= 2)) {
  11487. struct sockaddr_in6 sin6;
  11488. unsigned int i;
  11489. /* for strict validation, an actual IPv6 argument is needed */
  11490. if (sa->sa.sa_family != AF_INET6) {
  11491. return 0;
  11492. }
  11493. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11494. /* IPv6 format */
  11495. for (i = 0; i < 16; i++) {
  11496. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11497. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11498. uint8_t mask = 0;
  11499. if (8 * i + 8 < slash) {
  11500. mask = 0xFFu;
  11501. } else if (8 * i < slash) {
  11502. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11503. }
  11504. if ((ip & mask) != net) {
  11505. return 0;
  11506. }
  11507. }
  11508. return 1;
  11509. }
  11510. }
  11511. }
  11512. }
  11513. #else
  11514. (void)no_strict;
  11515. #endif
  11516. /* malformed */
  11517. return -1;
  11518. }
  11519. static int
  11520. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11521. {
  11522. int throttle = 0;
  11523. struct vec vec, val;
  11524. char mult;
  11525. double v;
  11526. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11527. mult = ',';
  11528. if ((val.ptr == NULL)
  11529. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11530. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11531. // to an integer value, but function will not report
  11532. // conversion errors; consider using 'strtol' instead
  11533. || (v < 0)
  11534. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11535. && (mult != ','))) {
  11536. continue;
  11537. }
  11538. v *= (lowercase(&mult) == 'k')
  11539. ? 1024
  11540. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11541. if (vec.len == 1 && vec.ptr[0] == '*') {
  11542. throttle = (int)v;
  11543. } else {
  11544. int matched = parse_match_net(&vec, rsa, 0);
  11545. if (matched >= 0) {
  11546. /* a valid IP subnet */
  11547. if (matched) {
  11548. throttle = (int)v;
  11549. }
  11550. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11551. throttle = (int)v;
  11552. }
  11553. }
  11554. }
  11555. return throttle;
  11556. }
  11557. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11558. #include "handle_form.inl"
  11559. static int
  11560. get_first_ssl_listener_index(const struct mg_context *ctx)
  11561. {
  11562. unsigned int i;
  11563. int idx = -1;
  11564. if (ctx) {
  11565. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11566. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11567. }
  11568. }
  11569. return idx;
  11570. }
  11571. /* Return host (without port) */
  11572. static void
  11573. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11574. {
  11575. const char *host_header =
  11576. get_header(ri->http_headers, ri->num_headers, "Host");
  11577. host->ptr = NULL;
  11578. host->len = 0;
  11579. if (host_header != NULL) {
  11580. const char *pos;
  11581. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11582. * is found. */
  11583. if (*host_header == '[') {
  11584. pos = strchr(host_header, ']');
  11585. if (!pos) {
  11586. /* Malformed hostname starts with '[', but no ']' found */
  11587. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11588. return;
  11589. }
  11590. /* terminate after ']' */
  11591. host->ptr = host_header;
  11592. host->len = (size_t)(pos + 1 - host_header);
  11593. } else {
  11594. /* Otherwise, a ':' separates hostname and port number */
  11595. pos = strchr(host_header, ':');
  11596. if (pos != NULL) {
  11597. host->len = (size_t)(pos - host_header);
  11598. } else {
  11599. host->len = strlen(host_header);
  11600. }
  11601. host->ptr = host_header;
  11602. }
  11603. }
  11604. }
  11605. static int
  11606. switch_domain_context(struct mg_connection *conn)
  11607. {
  11608. struct vec host;
  11609. get_host_from_request_info(&host, &conn->request_info);
  11610. if (host.ptr) {
  11611. if (conn->ssl) {
  11612. /* This is a HTTPS connection, maybe we have a hostname
  11613. * from SNI (set in ssl_servername_callback). */
  11614. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11615. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11616. /* We are not using the default domain */
  11617. if ((strlen(sslhost) != host.len)
  11618. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11619. /* Mismatch between SNI domain and HTTP domain */
  11620. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11621. sslhost,
  11622. (int)host.len,
  11623. host.ptr);
  11624. return 0;
  11625. }
  11626. }
  11627. } else {
  11628. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11629. while (dom) {
  11630. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  11631. size_t domNameLen = strlen(domName);
  11632. if ((domNameLen == host.len)
  11633. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  11634. /* Found matching domain */
  11635. DEBUG_TRACE("HTTP domain %s found",
  11636. dom->config[AUTHENTICATION_DOMAIN]);
  11637. /* TODO: Check if this is a HTTP or HTTPS domain */
  11638. conn->dom_ctx = dom;
  11639. break;
  11640. }
  11641. mg_lock_context(conn->phys_ctx);
  11642. dom = dom->next;
  11643. mg_unlock_context(conn->phys_ctx);
  11644. }
  11645. }
  11646. DEBUG_TRACE("HTTP%s Host: %.*s",
  11647. conn->ssl ? "S" : "",
  11648. (int)host.len,
  11649. host.ptr);
  11650. } else {
  11651. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11652. return 1;
  11653. }
  11654. return 1;
  11655. }
  11656. static void
  11657. redirect_to_https_port(struct mg_connection *conn, int port)
  11658. {
  11659. char target_url[MG_BUF_LEN];
  11660. int truncated = 0;
  11661. const char *expect_proto =
  11662. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11663. /* Use "308 Permanent Redirect" */
  11664. int redirect_code = 308;
  11665. /* In any case, close the current connection */
  11666. conn->must_close = 1;
  11667. /* Send host, port, uri and (if it exists) ?query_string */
  11668. if (mg_construct_local_link(
  11669. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11670. < 0) {
  11671. truncated = 1;
  11672. } else if (conn->request_info.query_string != NULL) {
  11673. size_t slen1 = strlen(target_url);
  11674. size_t slen2 = strlen(conn->request_info.query_string);
  11675. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11676. target_url[slen1] = '?';
  11677. memcpy(target_url + slen1 + 1,
  11678. conn->request_info.query_string,
  11679. slen2);
  11680. target_url[slen1 + slen2 + 1] = 0;
  11681. } else {
  11682. truncated = 1;
  11683. }
  11684. }
  11685. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11686. * is used as buffer size) */
  11687. if (truncated) {
  11688. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11689. return;
  11690. }
  11691. /* Use redirect helper function */
  11692. mg_send_http_redirect(conn, target_url, redirect_code);
  11693. }
  11694. static void
  11695. mg_set_handler_type(struct mg_context *phys_ctx,
  11696. struct mg_domain_context *dom_ctx,
  11697. const char *uri,
  11698. int handler_type,
  11699. int is_delete_request,
  11700. mg_request_handler handler,
  11701. struct mg_websocket_subprotocols *subprotocols,
  11702. mg_websocket_connect_handler connect_handler,
  11703. mg_websocket_ready_handler ready_handler,
  11704. mg_websocket_data_handler data_handler,
  11705. mg_websocket_close_handler close_handler,
  11706. mg_authorization_handler auth_handler,
  11707. void *cbdata)
  11708. {
  11709. struct mg_handler_info *tmp_rh, **lastref;
  11710. size_t urilen = strlen(uri);
  11711. if (handler_type == WEBSOCKET_HANDLER) {
  11712. DEBUG_ASSERT(handler == NULL);
  11713. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11714. || ready_handler != NULL || data_handler != NULL
  11715. || close_handler != NULL);
  11716. DEBUG_ASSERT(auth_handler == NULL);
  11717. if (handler != NULL) {
  11718. return;
  11719. }
  11720. if (!is_delete_request && (connect_handler == NULL)
  11721. && (ready_handler == NULL) && (data_handler == NULL)
  11722. && (close_handler == NULL)) {
  11723. return;
  11724. }
  11725. if (auth_handler != NULL) {
  11726. return;
  11727. }
  11728. } else if (handler_type == REQUEST_HANDLER) {
  11729. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11730. && data_handler == NULL && close_handler == NULL);
  11731. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11732. DEBUG_ASSERT(auth_handler == NULL);
  11733. if ((connect_handler != NULL) || (ready_handler != NULL)
  11734. || (data_handler != NULL) || (close_handler != NULL)) {
  11735. return;
  11736. }
  11737. if (!is_delete_request && (handler == NULL)) {
  11738. return;
  11739. }
  11740. if (auth_handler != NULL) {
  11741. return;
  11742. }
  11743. } else if (handler_type == AUTH_HANDLER) {
  11744. DEBUG_ASSERT(handler == NULL);
  11745. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11746. && data_handler == NULL && close_handler == NULL);
  11747. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  11748. if (handler != NULL) {
  11749. return;
  11750. }
  11751. if ((connect_handler != NULL) || (ready_handler != NULL)
  11752. || (data_handler != NULL) || (close_handler != NULL)) {
  11753. return;
  11754. }
  11755. if (!is_delete_request && (auth_handler == NULL)) {
  11756. return;
  11757. }
  11758. } else {
  11759. /* Unknown handler type. */
  11760. return;
  11761. }
  11762. if (!phys_ctx || !dom_ctx) {
  11763. /* no context available */
  11764. return;
  11765. }
  11766. mg_lock_context(phys_ctx);
  11767. /* first try to find an existing handler */
  11768. do {
  11769. lastref = &(dom_ctx->handlers);
  11770. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11771. tmp_rh = tmp_rh->next) {
  11772. if (tmp_rh->handler_type == handler_type
  11773. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11774. if (!is_delete_request) {
  11775. /* update existing handler */
  11776. if (handler_type == REQUEST_HANDLER) {
  11777. /* Wait for end of use before updating */
  11778. if (tmp_rh->refcount) {
  11779. mg_unlock_context(phys_ctx);
  11780. mg_sleep(1);
  11781. mg_lock_context(phys_ctx);
  11782. /* tmp_rh might have been freed, search again. */
  11783. break;
  11784. }
  11785. /* Ok, the handler is no more use -> Update it */
  11786. tmp_rh->handler = handler;
  11787. } else if (handler_type == WEBSOCKET_HANDLER) {
  11788. tmp_rh->subprotocols = subprotocols;
  11789. tmp_rh->connect_handler = connect_handler;
  11790. tmp_rh->ready_handler = ready_handler;
  11791. tmp_rh->data_handler = data_handler;
  11792. tmp_rh->close_handler = close_handler;
  11793. } else { /* AUTH_HANDLER */
  11794. tmp_rh->auth_handler = auth_handler;
  11795. }
  11796. tmp_rh->cbdata = cbdata;
  11797. } else {
  11798. /* remove existing handler */
  11799. if (handler_type == REQUEST_HANDLER) {
  11800. /* Wait for end of use before removing */
  11801. if (tmp_rh->refcount) {
  11802. tmp_rh->removing = 1;
  11803. mg_unlock_context(phys_ctx);
  11804. mg_sleep(1);
  11805. mg_lock_context(phys_ctx);
  11806. /* tmp_rh might have been freed, search again. */
  11807. break;
  11808. }
  11809. /* Ok, the handler is no more used */
  11810. }
  11811. *lastref = tmp_rh->next;
  11812. mg_free(tmp_rh->uri);
  11813. mg_free(tmp_rh);
  11814. }
  11815. mg_unlock_context(phys_ctx);
  11816. return;
  11817. }
  11818. lastref = &(tmp_rh->next);
  11819. }
  11820. } while (tmp_rh != NULL);
  11821. if (is_delete_request) {
  11822. /* no handler to set, this was a remove request to a non-existing
  11823. * handler */
  11824. mg_unlock_context(phys_ctx);
  11825. return;
  11826. }
  11827. tmp_rh =
  11828. (struct mg_handler_info *)mg_calloc_ctx(1,
  11829. sizeof(struct mg_handler_info),
  11830. phys_ctx);
  11831. if (tmp_rh == NULL) {
  11832. mg_unlock_context(phys_ctx);
  11833. mg_cry_ctx_internal(phys_ctx,
  11834. "%s",
  11835. "Cannot create new request handler struct, OOM");
  11836. return;
  11837. }
  11838. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11839. if (!tmp_rh->uri) {
  11840. mg_unlock_context(phys_ctx);
  11841. mg_free(tmp_rh);
  11842. mg_cry_ctx_internal(phys_ctx,
  11843. "%s",
  11844. "Cannot create new request handler struct, OOM");
  11845. return;
  11846. }
  11847. tmp_rh->uri_len = urilen;
  11848. if (handler_type == REQUEST_HANDLER) {
  11849. tmp_rh->refcount = 0;
  11850. tmp_rh->removing = 0;
  11851. tmp_rh->handler = handler;
  11852. } else if (handler_type == WEBSOCKET_HANDLER) {
  11853. tmp_rh->subprotocols = subprotocols;
  11854. tmp_rh->connect_handler = connect_handler;
  11855. tmp_rh->ready_handler = ready_handler;
  11856. tmp_rh->data_handler = data_handler;
  11857. tmp_rh->close_handler = close_handler;
  11858. } else { /* AUTH_HANDLER */
  11859. tmp_rh->auth_handler = auth_handler;
  11860. }
  11861. tmp_rh->cbdata = cbdata;
  11862. tmp_rh->handler_type = handler_type;
  11863. tmp_rh->next = NULL;
  11864. *lastref = tmp_rh;
  11865. mg_unlock_context(phys_ctx);
  11866. }
  11867. void
  11868. mg_set_request_handler(struct mg_context *ctx,
  11869. const char *uri,
  11870. mg_request_handler handler,
  11871. void *cbdata)
  11872. {
  11873. mg_set_handler_type(ctx,
  11874. &(ctx->dd),
  11875. uri,
  11876. REQUEST_HANDLER,
  11877. handler == NULL,
  11878. handler,
  11879. NULL,
  11880. NULL,
  11881. NULL,
  11882. NULL,
  11883. NULL,
  11884. NULL,
  11885. cbdata);
  11886. }
  11887. void
  11888. mg_set_websocket_handler(struct mg_context *ctx,
  11889. const char *uri,
  11890. mg_websocket_connect_handler connect_handler,
  11891. mg_websocket_ready_handler ready_handler,
  11892. mg_websocket_data_handler data_handler,
  11893. mg_websocket_close_handler close_handler,
  11894. void *cbdata)
  11895. {
  11896. mg_set_websocket_handler_with_subprotocols(ctx,
  11897. uri,
  11898. NULL,
  11899. connect_handler,
  11900. ready_handler,
  11901. data_handler,
  11902. close_handler,
  11903. cbdata);
  11904. }
  11905. void
  11906. mg_set_websocket_handler_with_subprotocols(
  11907. struct mg_context *ctx,
  11908. const char *uri,
  11909. struct mg_websocket_subprotocols *subprotocols,
  11910. mg_websocket_connect_handler connect_handler,
  11911. mg_websocket_ready_handler ready_handler,
  11912. mg_websocket_data_handler data_handler,
  11913. mg_websocket_close_handler close_handler,
  11914. void *cbdata)
  11915. {
  11916. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11917. && (data_handler == NULL)
  11918. && (close_handler == NULL);
  11919. mg_set_handler_type(ctx,
  11920. &(ctx->dd),
  11921. uri,
  11922. WEBSOCKET_HANDLER,
  11923. is_delete_request,
  11924. NULL,
  11925. subprotocols,
  11926. connect_handler,
  11927. ready_handler,
  11928. data_handler,
  11929. close_handler,
  11930. NULL,
  11931. cbdata);
  11932. }
  11933. void
  11934. mg_set_auth_handler(struct mg_context *ctx,
  11935. const char *uri,
  11936. mg_authorization_handler handler,
  11937. void *cbdata)
  11938. {
  11939. mg_set_handler_type(ctx,
  11940. &(ctx->dd),
  11941. uri,
  11942. AUTH_HANDLER,
  11943. handler == NULL,
  11944. NULL,
  11945. NULL,
  11946. NULL,
  11947. NULL,
  11948. NULL,
  11949. NULL,
  11950. handler,
  11951. cbdata);
  11952. }
  11953. static int
  11954. get_request_handler(struct mg_connection *conn,
  11955. int handler_type,
  11956. mg_request_handler *handler,
  11957. struct mg_websocket_subprotocols **subprotocols,
  11958. mg_websocket_connect_handler *connect_handler,
  11959. mg_websocket_ready_handler *ready_handler,
  11960. mg_websocket_data_handler *data_handler,
  11961. mg_websocket_close_handler *close_handler,
  11962. mg_authorization_handler *auth_handler,
  11963. void **cbdata,
  11964. struct mg_handler_info **handler_info)
  11965. {
  11966. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11967. if (request_info) {
  11968. const char *uri = request_info->local_uri;
  11969. size_t urilen = strlen(uri);
  11970. struct mg_handler_info *tmp_rh;
  11971. int step, matched;
  11972. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11973. return 0;
  11974. }
  11975. mg_lock_context(conn->phys_ctx);
  11976. for (step = 0; step < 3; step++) {
  11977. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11978. tmp_rh = tmp_rh->next) {
  11979. if (tmp_rh->handler_type != handler_type) {
  11980. continue;
  11981. }
  11982. if (step == 0) {
  11983. /* first try for an exact match */
  11984. matched = (tmp_rh->uri_len == urilen)
  11985. && (strcmp(tmp_rh->uri, uri) == 0);
  11986. } else if (step == 1) {
  11987. /* next try for a partial match, we will accept
  11988. uri/something */
  11989. matched =
  11990. (tmp_rh->uri_len < urilen)
  11991. && (uri[tmp_rh->uri_len] == '/')
  11992. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  11993. } else {
  11994. /* finally try for pattern match */
  11995. matched =
  11996. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  11997. }
  11998. if (matched) {
  11999. if (handler_type == WEBSOCKET_HANDLER) {
  12000. *subprotocols = tmp_rh->subprotocols;
  12001. *connect_handler = tmp_rh->connect_handler;
  12002. *ready_handler = tmp_rh->ready_handler;
  12003. *data_handler = tmp_rh->data_handler;
  12004. *close_handler = tmp_rh->close_handler;
  12005. } else if (handler_type == REQUEST_HANDLER) {
  12006. if (tmp_rh->removing) {
  12007. /* Treat as none found */
  12008. step = 2;
  12009. break;
  12010. }
  12011. *handler = tmp_rh->handler;
  12012. /* Acquire handler and give it back */
  12013. tmp_rh->refcount++;
  12014. *handler_info = tmp_rh;
  12015. } else { /* AUTH_HANDLER */
  12016. *auth_handler = tmp_rh->auth_handler;
  12017. }
  12018. *cbdata = tmp_rh->cbdata;
  12019. mg_unlock_context(conn->phys_ctx);
  12020. return 1;
  12021. }
  12022. }
  12023. }
  12024. mg_unlock_context(conn->phys_ctx);
  12025. }
  12026. return 0; /* none found */
  12027. }
  12028. /* Check if the script file is in a path, allowed for script files.
  12029. * This can be used if uploading files is possible not only for the server
  12030. * admin, and the upload mechanism does not check the file extension.
  12031. */
  12032. static int
  12033. is_in_script_path(const struct mg_connection *conn, const char *path)
  12034. {
  12035. /* TODO (Feature): Add config value for allowed script path.
  12036. * Default: All allowed. */
  12037. (void)conn;
  12038. (void)path;
  12039. return 1;
  12040. }
  12041. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12042. static int
  12043. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12044. int bits,
  12045. char *data,
  12046. size_t len,
  12047. void *cbdata)
  12048. {
  12049. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12050. if (pcallbacks->websocket_data) {
  12051. return pcallbacks->websocket_data(conn, bits, data, len);
  12052. }
  12053. /* No handler set - assume "OK" */
  12054. return 1;
  12055. }
  12056. static void
  12057. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12058. void *cbdata)
  12059. {
  12060. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12061. if (pcallbacks->connection_close) {
  12062. pcallbacks->connection_close(conn);
  12063. }
  12064. }
  12065. #endif
  12066. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12067. */
  12068. static void
  12069. release_handler_ref(struct mg_connection *conn,
  12070. struct mg_handler_info *handler_info)
  12071. {
  12072. if (handler_info != NULL) {
  12073. /* Use context lock for ref counter */
  12074. mg_lock_context(conn->phys_ctx);
  12075. handler_info->refcount--;
  12076. mg_unlock_context(conn->phys_ctx);
  12077. }
  12078. }
  12079. /* This is the heart of the Civetweb's logic.
  12080. * This function is called when the request is read, parsed and validated,
  12081. * and Civetweb must decide what action to take: serve a file, or
  12082. * a directory, or call embedded function, etcetera. */
  12083. static void
  12084. handle_request(struct mg_connection *conn)
  12085. {
  12086. struct mg_request_info *ri = &conn->request_info;
  12087. char path[UTF8_PATH_MAX];
  12088. int uri_len, ssl_index;
  12089. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12090. is_put_or_delete_request = 0, is_callback_resource = 0,
  12091. is_template_text_file = 0;
  12092. int i;
  12093. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12094. mg_request_handler callback_handler = NULL;
  12095. struct mg_handler_info *handler_info = NULL;
  12096. struct mg_websocket_subprotocols *subprotocols;
  12097. mg_websocket_connect_handler ws_connect_handler = NULL;
  12098. mg_websocket_ready_handler ws_ready_handler = NULL;
  12099. mg_websocket_data_handler ws_data_handler = NULL;
  12100. mg_websocket_close_handler ws_close_handler = NULL;
  12101. void *callback_data = NULL;
  12102. mg_authorization_handler auth_handler = NULL;
  12103. void *auth_callback_data = NULL;
  12104. int handler_type;
  12105. time_t curtime = time(NULL);
  12106. char date[64];
  12107. char *tmp;
  12108. path[0] = 0;
  12109. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12110. conn->request_state = 0;
  12111. /* 1. get the request url */
  12112. /* 1.1. split into url and query string */
  12113. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12114. != NULL) {
  12115. *((char *)conn->request_info.query_string++) = '\0';
  12116. }
  12117. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12118. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12119. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12120. if (ssl_index >= 0) {
  12121. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12122. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12123. redirect_to_https_port(conn, port);
  12124. } else {
  12125. /* A http to https forward port has been specified,
  12126. * but no https port to forward to. */
  12127. mg_send_http_error(conn,
  12128. 503,
  12129. "%s",
  12130. "Error: SSL forward not configured properly");
  12131. mg_cry_internal(conn,
  12132. "%s",
  12133. "Can not redirect to SSL, no SSL port available");
  12134. }
  12135. return;
  12136. }
  12137. uri_len = (int)strlen(ri->local_uri);
  12138. /* 1.3. decode url (if config says so) */
  12139. if (should_decode_url(conn)) {
  12140. mg_url_decode(
  12141. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12142. }
  12143. /* URL decode the query-string only if explicity set in the configuration */
  12144. if (conn->request_info.query_string) {
  12145. if (should_decode_query_string(conn)) {
  12146. url_decode_in_place((char *)conn->request_info.query_string);
  12147. }
  12148. }
  12149. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12150. * possible. The fact that we cleaned the URI is stored in that the
  12151. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12152. * ri->local_uri_raw still points to memory allocated in
  12153. * worker_thread_run(). ri->local_uri is private to the request so we
  12154. * don't have to use preallocated memory here. */
  12155. tmp = mg_strdup(ri->local_uri_raw);
  12156. if (!tmp) {
  12157. /* Out of memory. We cannot do anything reasonable here. */
  12158. return;
  12159. }
  12160. remove_dot_segments(tmp);
  12161. ri->local_uri = tmp;
  12162. /* step 1. completed, the url is known now */
  12163. DEBUG_TRACE("URL: %s", ri->local_uri);
  12164. /* 2. if this ip has limited speed, set it for this connection */
  12165. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12166. &conn->client.rsa,
  12167. ri->local_uri);
  12168. /* 3. call a "handle everything" callback, if registered */
  12169. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12170. /* Note that since V1.7 the "begin_request" function is called
  12171. * before an authorization check. If an authorization check is
  12172. * required, use a request_handler instead. */
  12173. i = conn->phys_ctx->callbacks.begin_request(conn);
  12174. if (i > 0) {
  12175. /* callback already processed the request. Store the
  12176. return value as a status code for the access log. */
  12177. conn->status_code = i;
  12178. if (!conn->must_close) {
  12179. discard_unread_request_data(conn);
  12180. }
  12181. return;
  12182. } else if (i == 0) {
  12183. /* civetweb should process the request */
  12184. } else {
  12185. /* unspecified - may change with the next version */
  12186. return;
  12187. }
  12188. }
  12189. /* request not yet handled by a handler or redirect, so the request
  12190. * is processed here */
  12191. /* 4. Check for CORS preflight requests and handle them (if configured).
  12192. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12193. */
  12194. if (!strcmp(ri->request_method, "OPTIONS")) {
  12195. /* Send a response to CORS preflights only if
  12196. * access_control_allow_methods is not NULL and not an empty string.
  12197. * In this case, scripts can still handle CORS. */
  12198. const char *cors_meth_cfg =
  12199. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12200. const char *cors_orig_cfg =
  12201. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12202. const char *cors_origin =
  12203. get_header(ri->http_headers, ri->num_headers, "Origin");
  12204. const char *cors_acrm = get_header(ri->http_headers,
  12205. ri->num_headers,
  12206. "Access-Control-Request-Method");
  12207. /* Todo: check if cors_origin is in cors_orig_cfg.
  12208. * Or, let the client check this. */
  12209. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12210. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12211. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12212. /* This is a valid CORS preflight, and the server is configured
  12213. * to handle it automatically. */
  12214. const char *cors_acrh =
  12215. get_header(ri->http_headers,
  12216. ri->num_headers,
  12217. "Access-Control-Request-Headers");
  12218. gmt_time_string(date, sizeof(date), &curtime);
  12219. mg_printf(conn,
  12220. "HTTP/1.1 200 OK\r\n"
  12221. "Date: %s\r\n"
  12222. "Access-Control-Allow-Origin: %s\r\n"
  12223. "Access-Control-Allow-Methods: %s\r\n"
  12224. "Content-Length: 0\r\n"
  12225. "Connection: %s\r\n",
  12226. date,
  12227. cors_orig_cfg,
  12228. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12229. suggest_connection_header(conn));
  12230. if (cors_acrh != NULL) {
  12231. /* CORS request is asking for additional headers */
  12232. const char *cors_hdr_cfg =
  12233. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12234. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12235. /* Allow only if access_control_allow_headers is
  12236. * not NULL and not an empty string. If this
  12237. * configuration is set to *, allow everything.
  12238. * Otherwise this configuration must be a list
  12239. * of allowed HTTP header names. */
  12240. mg_printf(conn,
  12241. "Access-Control-Allow-Headers: %s\r\n",
  12242. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12243. : cors_hdr_cfg));
  12244. }
  12245. }
  12246. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12247. mg_printf(conn, "\r\n");
  12248. return;
  12249. }
  12250. }
  12251. /* 5. interpret the url to find out how the request must be handled
  12252. */
  12253. /* 5.1. first test, if the request targets the regular http(s)://
  12254. * protocol namespace or the websocket ws(s):// protocol namespace.
  12255. */
  12256. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12257. #if defined(USE_WEBSOCKET)
  12258. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12259. #else
  12260. handler_type = REQUEST_HANDLER;
  12261. #endif /* defined(USE_WEBSOCKET) */
  12262. if (is_websocket_request) {
  12263. HTTP1_only;
  12264. }
  12265. /* 5.2. check if the request will be handled by a callback */
  12266. if (get_request_handler(conn,
  12267. handler_type,
  12268. &callback_handler,
  12269. &subprotocols,
  12270. &ws_connect_handler,
  12271. &ws_ready_handler,
  12272. &ws_data_handler,
  12273. &ws_close_handler,
  12274. NULL,
  12275. &callback_data,
  12276. &handler_info)) {
  12277. /* 5.2.1. A callback will handle this request. All requests
  12278. * handled by a callback have to be considered as requests
  12279. * to a script resource. */
  12280. is_callback_resource = 1;
  12281. is_script_resource = 1;
  12282. is_put_or_delete_request = is_put_or_delete_method(conn);
  12283. } else {
  12284. no_callback_resource:
  12285. /* 5.2.2. No callback is responsible for this request. The URI
  12286. * addresses a file based resource (static content or Lua/cgi
  12287. * scripts in the file system). */
  12288. is_callback_resource = 0;
  12289. interpret_uri(conn,
  12290. path,
  12291. sizeof(path),
  12292. &file.stat,
  12293. &is_found,
  12294. &is_script_resource,
  12295. &is_websocket_request,
  12296. &is_put_or_delete_request,
  12297. &is_template_text_file);
  12298. }
  12299. /* 6. authorization check */
  12300. /* 6.1. a custom authorization handler is installed */
  12301. if (get_request_handler(conn,
  12302. AUTH_HANDLER,
  12303. NULL,
  12304. NULL,
  12305. NULL,
  12306. NULL,
  12307. NULL,
  12308. NULL,
  12309. &auth_handler,
  12310. &auth_callback_data,
  12311. NULL)) {
  12312. if (!auth_handler(conn, auth_callback_data)) {
  12313. /* Callback handler will not be used anymore. Release it */
  12314. release_handler_ref(conn, handler_info);
  12315. return;
  12316. }
  12317. } else if (is_put_or_delete_request && !is_script_resource
  12318. && !is_callback_resource) {
  12319. HTTP1_only;
  12320. /* 6.2. this request is a PUT/DELETE to a real file */
  12321. /* 6.2.1. thus, the server must have real files */
  12322. #if defined(NO_FILES)
  12323. if (1) {
  12324. #else
  12325. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12326. #endif
  12327. /* This code path will not be called for request handlers */
  12328. DEBUG_ASSERT(handler_info == NULL);
  12329. /* This server does not have any real files, thus the
  12330. * PUT/DELETE methods are not valid. */
  12331. mg_send_http_error(conn,
  12332. 405,
  12333. "%s method not allowed",
  12334. conn->request_info.request_method);
  12335. return;
  12336. }
  12337. #if !defined(NO_FILES)
  12338. /* 6.2.2. Check if put authorization for static files is
  12339. * available.
  12340. */
  12341. if (!is_authorized_for_put(conn)) {
  12342. send_authorization_request(conn, NULL);
  12343. return;
  12344. }
  12345. #endif
  12346. } else {
  12347. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12348. * or it is a PUT or DELETE request to a resource that does not
  12349. * correspond to a file. Check authorization. */
  12350. if (!check_authorization(conn, path)) {
  12351. send_authorization_request(conn, NULL);
  12352. /* Callback handler will not be used anymore. Release it */
  12353. release_handler_ref(conn, handler_info);
  12354. return;
  12355. }
  12356. }
  12357. /* request is authorized or does not need authorization */
  12358. /* 7. check if there are request handlers for this uri */
  12359. if (is_callback_resource) {
  12360. HTTP1_only;
  12361. if (!is_websocket_request) {
  12362. i = callback_handler(conn, callback_data);
  12363. /* Callback handler will not be used anymore. Release it */
  12364. release_handler_ref(conn, handler_info);
  12365. if (i > 0) {
  12366. /* Do nothing, callback has served the request. Store
  12367. * then return value as status code for the log and discard
  12368. * all data from the client not used by the callback. */
  12369. conn->status_code = i;
  12370. if (!conn->must_close) {
  12371. discard_unread_request_data(conn);
  12372. }
  12373. } else {
  12374. /* The handler did NOT handle the request. */
  12375. /* Some proper reactions would be:
  12376. * a) close the connections without sending anything
  12377. * b) send a 404 not found
  12378. * c) try if there is a file matching the URI
  12379. * It would be possible to do a, b or c in the callback
  12380. * implementation, and return 1 - we cannot do anything
  12381. * here, that is not possible in the callback.
  12382. *
  12383. * TODO: What would be the best reaction here?
  12384. * (Note: The reaction may change, if there is a better
  12385. * idea.)
  12386. */
  12387. /* For the moment, use option c: We look for a proper file,
  12388. * but since a file request is not always a script resource,
  12389. * the authorization check might be different. */
  12390. interpret_uri(conn,
  12391. path,
  12392. sizeof(path),
  12393. &file.stat,
  12394. &is_found,
  12395. &is_script_resource,
  12396. &is_websocket_request,
  12397. &is_put_or_delete_request,
  12398. &is_template_text_file);
  12399. callback_handler = NULL;
  12400. /* Here we are at a dead end:
  12401. * According to URI matching, a callback should be
  12402. * responsible for handling the request,
  12403. * we called it, but the callback declared itself
  12404. * not responsible.
  12405. * We use a goto here, to get out of this dead end,
  12406. * and continue with the default handling.
  12407. * A goto here is simpler and better to understand
  12408. * than some curious loop. */
  12409. goto no_callback_resource;
  12410. }
  12411. } else {
  12412. #if defined(USE_WEBSOCKET)
  12413. handle_websocket_request(conn,
  12414. path,
  12415. is_callback_resource,
  12416. subprotocols,
  12417. ws_connect_handler,
  12418. ws_ready_handler,
  12419. ws_data_handler,
  12420. ws_close_handler,
  12421. callback_data);
  12422. #endif
  12423. }
  12424. return;
  12425. }
  12426. /* 8. handle websocket requests */
  12427. #if defined(USE_WEBSOCKET)
  12428. if (is_websocket_request) {
  12429. HTTP1_only;
  12430. if (is_script_resource) {
  12431. if (is_in_script_path(conn, path)) {
  12432. /* Websocket Lua script */
  12433. handle_websocket_request(conn,
  12434. path,
  12435. 0 /* Lua Script */,
  12436. NULL,
  12437. NULL,
  12438. NULL,
  12439. NULL,
  12440. NULL,
  12441. conn->phys_ctx->user_data);
  12442. } else {
  12443. /* Script was in an illegal path */
  12444. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12445. }
  12446. } else {
  12447. mg_send_http_error(conn, 404, "%s", "Not found");
  12448. }
  12449. return;
  12450. } else
  12451. #endif
  12452. #if defined(NO_FILES)
  12453. /* 9a. In case the server uses only callbacks, this uri is
  12454. * unknown.
  12455. * Then, all request handling ends here. */
  12456. mg_send_http_error(conn, 404, "%s", "Not Found");
  12457. #else
  12458. /* 9b. This request is either for a static file or resource handled
  12459. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12460. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12461. mg_send_http_error(conn, 404, "%s", "Not Found");
  12462. return;
  12463. }
  12464. /* 10. Request is handled by a script */
  12465. if (is_script_resource) {
  12466. HTTP1_only;
  12467. handle_file_based_request(conn, path, &file);
  12468. return;
  12469. }
  12470. /* 11. Handle put/delete/mkcol requests */
  12471. if (is_put_or_delete_request) {
  12472. HTTP1_only;
  12473. /* 11.1. PUT method */
  12474. if (!strcmp(ri->request_method, "PUT")) {
  12475. put_file(conn, path);
  12476. return;
  12477. }
  12478. /* 11.2. DELETE method */
  12479. if (!strcmp(ri->request_method, "DELETE")) {
  12480. delete_file(conn, path);
  12481. return;
  12482. }
  12483. /* 11.3. MKCOL method */
  12484. if (!strcmp(ri->request_method, "MKCOL")) {
  12485. mkcol(conn, path);
  12486. return;
  12487. }
  12488. /* 11.4. PATCH method
  12489. * This method is not supported for static resources,
  12490. * only for scripts (Lua, CGI) and callbacks. */
  12491. mg_send_http_error(conn,
  12492. 405,
  12493. "%s method not allowed",
  12494. conn->request_info.request_method);
  12495. return;
  12496. }
  12497. /* 11. File does not exist, or it was configured that it should be
  12498. * hidden */
  12499. if (!is_found || (must_hide_file(conn, path))) {
  12500. mg_send_http_error(conn, 404, "%s", "Not found");
  12501. return;
  12502. }
  12503. /* 12. Directory uris should end with a slash */
  12504. if (file.stat.is_directory && ((uri_len = (int) strlen(ri->local_uri)) > 0)
  12505. && (ri->local_uri[uri_len - 1] != '/')) {
  12506. size_t len = strlen(ri->request_uri);
  12507. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12508. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12509. if (!new_path) {
  12510. mg_send_http_error(conn, 500, "out or memory");
  12511. } else {
  12512. memcpy(new_path, ri->request_uri, len);
  12513. new_path[len] = '/';
  12514. new_path[len + 1] = 0;
  12515. if (ri->query_string) {
  12516. new_path[len + 1] = '?';
  12517. /* Copy query string including terminating zero */
  12518. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12519. }
  12520. mg_send_http_redirect(conn, new_path, 301);
  12521. mg_free(new_path);
  12522. }
  12523. return;
  12524. }
  12525. /* 13. Handle other methods than GET/HEAD */
  12526. /* 13.1. Handle PROPFIND */
  12527. if (!strcmp(ri->request_method, "PROPFIND")) {
  12528. handle_propfind(conn, path, &file.stat);
  12529. return;
  12530. }
  12531. /* 13.2. Handle OPTIONS for files */
  12532. if (!strcmp(ri->request_method, "OPTIONS")) {
  12533. /* This standard handler is only used for real files.
  12534. * Scripts should support the OPTIONS method themselves, to allow a
  12535. * maximum flexibility.
  12536. * Lua and CGI scripts may fully support CORS this way (including
  12537. * preflights). */
  12538. send_options(conn);
  12539. return;
  12540. }
  12541. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12542. if ((0 != strcmp(ri->request_method, "GET"))
  12543. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12544. mg_send_http_error(conn,
  12545. 405,
  12546. "%s method not allowed",
  12547. conn->request_info.request_method);
  12548. return;
  12549. }
  12550. /* 14. directories */
  12551. if (file.stat.is_directory) {
  12552. /* Substitute files have already been handled above. */
  12553. /* Here we can either generate and send a directory listing,
  12554. * or send an "access denied" error. */
  12555. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12556. "yes")) {
  12557. handle_directory_request(conn, path);
  12558. } else {
  12559. mg_send_http_error(conn,
  12560. 403,
  12561. "%s",
  12562. "Error: Directory listing denied");
  12563. }
  12564. return;
  12565. }
  12566. /* 15. Files with search/replace patterns: LSP and SSI */
  12567. if (is_template_text_file) {
  12568. HTTP1_only;
  12569. handle_file_based_request(conn, path, &file);
  12570. return;
  12571. }
  12572. /* 16. Static file - maybe cached */
  12573. #if !defined(NO_CACHING)
  12574. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12575. /* Send 304 "Not Modified" - this must not send any body data */
  12576. handle_not_modified_static_file_request(conn, &file);
  12577. return;
  12578. }
  12579. #endif /* !NO_CACHING */
  12580. /* 17. Static file - not cached */
  12581. handle_static_file_request(conn, path, &file, NULL, NULL);
  12582. #endif /* !defined(NO_FILES) */
  12583. }
  12584. #if !defined(NO_FILESYSTEMS)
  12585. static void
  12586. handle_file_based_request(struct mg_connection *conn,
  12587. const char *path,
  12588. struct mg_file *file)
  12589. {
  12590. #if !defined(NO_CGI)
  12591. unsigned char cgi_config_idx, inc, max;
  12592. #endif
  12593. if (!conn || !conn->dom_ctx) {
  12594. return;
  12595. }
  12596. #if defined(USE_LUA)
  12597. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12598. path)
  12599. > 0) {
  12600. if (is_in_script_path(conn, path)) {
  12601. /* Lua server page: an SSI like page containing mostly plain
  12602. * html code plus some tags with server generated contents. */
  12603. handle_lsp_request(conn, path, file, NULL);
  12604. } else {
  12605. /* Script was in an illegal path */
  12606. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12607. }
  12608. return;
  12609. }
  12610. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  12611. > 0) {
  12612. if (is_in_script_path(conn, path)) {
  12613. /* Lua in-server module script: a CGI like script used to
  12614. * generate the entire reply. */
  12615. mg_exec_lua_script(conn, path, NULL);
  12616. } else {
  12617. /* Script was in an illegal path */
  12618. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12619. }
  12620. return;
  12621. }
  12622. #endif
  12623. #if defined(USE_DUKTAPE)
  12624. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12625. path)
  12626. > 0) {
  12627. if (is_in_script_path(conn, path)) {
  12628. /* Call duktape to generate the page */
  12629. mg_exec_duktape_script(conn, path);
  12630. } else {
  12631. /* Script was in an illegal path */
  12632. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12633. }
  12634. return;
  12635. }
  12636. #endif
  12637. #if !defined(NO_CGI)
  12638. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  12639. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  12640. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  12641. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  12642. if (match_prefix_strlen(
  12643. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  12644. path)
  12645. > 0) {
  12646. if (is_in_script_path(conn, path)) {
  12647. /* CGI scripts may support all HTTP methods */
  12648. handle_cgi_request(conn, path, 0);
  12649. } else {
  12650. /* Script was in an illegal path */
  12651. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12652. }
  12653. return;
  12654. }
  12655. }
  12656. }
  12657. #endif /* !NO_CGI */
  12658. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  12659. if (is_in_script_path(conn, path)) {
  12660. handle_ssi_file_request(conn, path, file);
  12661. } else {
  12662. /* Script was in an illegal path */
  12663. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12664. }
  12665. return;
  12666. }
  12667. #if !defined(NO_CACHING)
  12668. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  12669. /* Send 304 "Not Modified" - this must not send any body data */
  12670. handle_not_modified_static_file_request(conn, file);
  12671. return;
  12672. }
  12673. #endif /* !NO_CACHING */
  12674. handle_static_file_request(conn, path, file, NULL, NULL);
  12675. }
  12676. #endif /* NO_FILESYSTEMS */
  12677. static void
  12678. close_all_listening_sockets(struct mg_context *ctx)
  12679. {
  12680. unsigned int i;
  12681. if (!ctx) {
  12682. return;
  12683. }
  12684. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12685. closesocket(ctx->listening_sockets[i].sock);
  12686. #if defined(USE_X_DOM_SOCKET)
  12687. /* For unix domain sockets, the socket name represents a file that has
  12688. * to be deleted. */
  12689. /* See
  12690. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12691. */
  12692. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12693. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12694. IGNORE_UNUSED_RESULT(
  12695. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12696. }
  12697. #endif
  12698. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12699. }
  12700. mg_free(ctx->listening_sockets);
  12701. ctx->listening_sockets = NULL;
  12702. mg_free(ctx->listening_socket_fds);
  12703. ctx->listening_socket_fds = NULL;
  12704. }
  12705. /* Valid listening port specification is: [ip_address:]port[s]
  12706. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12707. * Examples for IPv6: [::]:80, [::1]:80,
  12708. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12709. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12710. * In order to bind to both, IPv4 and IPv6, you can either add
  12711. * both ports using 8080,[::]:8080, or the short form +8080.
  12712. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12713. * one only accepting IPv4 the other only IPv6. +8080 creates
  12714. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12715. * environment, they might work differently, or might not work
  12716. * at all - it must be tested what options work best in the
  12717. * relevant network environment.
  12718. */
  12719. static int
  12720. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12721. {
  12722. unsigned int a, b, c, d;
  12723. unsigned port;
  12724. unsigned long portUL;
  12725. int ch, len;
  12726. const char *cb;
  12727. char *endptr;
  12728. #if defined(USE_IPV6)
  12729. char buf[100] = {0};
  12730. #endif
  12731. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12732. * Also, all-zeroes in the socket address means binding to all addresses
  12733. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12734. memset(so, 0, sizeof(*so));
  12735. so->lsa.sin.sin_family = AF_INET;
  12736. *ip_version = 0;
  12737. /* Initialize len as invalid. */
  12738. port = 0;
  12739. len = 0;
  12740. /* Test for different ways to format this string */
  12741. if (sscanf(vec->ptr,
  12742. "%u.%u.%u.%u:%u%n",
  12743. &a,
  12744. &b,
  12745. &c,
  12746. &d,
  12747. &port,
  12748. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12749. // to an integer value, but function will not report
  12750. // conversion errors; consider using 'strtol' instead
  12751. == 5) {
  12752. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12753. so->lsa.sin.sin_addr.s_addr =
  12754. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12755. so->lsa.sin.sin_port = htons((uint16_t)port);
  12756. *ip_version = 4;
  12757. #if defined(USE_IPV6)
  12758. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12759. && ((size_t)len <= vec->len)
  12760. && mg_inet_pton(
  12761. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12762. /* IPv6 address, examples: see above */
  12763. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12764. */
  12765. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12766. *ip_version = 6;
  12767. #endif
  12768. } else if ((vec->ptr[0] == '+')
  12769. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  12770. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12771. // string to an integer value, but function will not
  12772. // report conversion errors; consider using 'strtol'
  12773. // instead
  12774. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12775. /* Add 1 to len for the + character we skipped before */
  12776. len++;
  12777. #if defined(USE_IPV6)
  12778. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12779. so->lsa.sin6.sin6_family = AF_INET6;
  12780. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12781. *ip_version = 4 + 6;
  12782. #else
  12783. /* Bind to IPv4 only, since IPv6 is not built in. */
  12784. so->lsa.sin.sin_port = htons((uint16_t)port);
  12785. *ip_version = 4;
  12786. #endif
  12787. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12788. && (vec->ptr != endptr)) {
  12789. len = (int)(endptr - vec->ptr);
  12790. port = (uint16_t)portUL;
  12791. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12792. so->lsa.sin.sin_port = htons((uint16_t)port);
  12793. *ip_version = 4;
  12794. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12795. /* String could be a hostname. This check algotithm
  12796. * will only work for RFC 952 compliant hostnames,
  12797. * starting with a letter, containing only letters,
  12798. * digits and hyphen ('-'). Newer specs may allow
  12799. * more, but this is not guaranteed here, since it
  12800. * may interfere with rules for port option lists. */
  12801. /* According to RFC 1035, hostnames are restricted to 255 characters
  12802. * in total (63 between two dots). */
  12803. char hostname[256];
  12804. size_t hostnlen = (size_t)(cb - vec->ptr);
  12805. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12806. /* This would be invalid in any case */
  12807. *ip_version = 0;
  12808. return 0;
  12809. }
  12810. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12811. if (mg_inet_pton(
  12812. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12813. if (sscanf(cb + 1, "%u%n", &port, &len)
  12814. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12815. // string to an integer value, but function will not
  12816. // report conversion errors; consider using 'strtol'
  12817. // instead
  12818. *ip_version = 4;
  12819. so->lsa.sin.sin_port = htons((uint16_t)port);
  12820. len += (int)(hostnlen + 1);
  12821. } else {
  12822. len = 0;
  12823. }
  12824. #if defined(USE_IPV6)
  12825. } else if (mg_inet_pton(AF_INET6,
  12826. hostname,
  12827. &so->lsa.sin6,
  12828. sizeof(so->lsa.sin6),
  12829. 1)) {
  12830. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12831. *ip_version = 6;
  12832. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12833. len += (int)(hostnlen + 1);
  12834. } else {
  12835. len = 0;
  12836. }
  12837. #endif
  12838. } else {
  12839. len = 0;
  12840. }
  12841. #if defined(USE_X_DOM_SOCKET)
  12842. } else if (vec->ptr[0] == 'x') {
  12843. /* unix (linux) domain socket */
  12844. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  12845. len = vec->len;
  12846. so->lsa.sun.sun_family = AF_UNIX;
  12847. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  12848. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  12849. port = 0;
  12850. *ip_version = 99;
  12851. } else {
  12852. /* String too long */
  12853. len = 0;
  12854. }
  12855. #endif
  12856. } else {
  12857. /* Parsing failure. */
  12858. len = 0;
  12859. }
  12860. /* sscanf and the option splitting code ensure the following condition
  12861. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12862. if ((len > 0) && is_valid_port(port)
  12863. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  12864. /* Next character after the port number */
  12865. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12866. so->is_ssl = (ch == 's');
  12867. so->ssl_redir = (ch == 'r');
  12868. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12869. return 1;
  12870. }
  12871. }
  12872. /* Reset ip_version to 0 if there is an error */
  12873. *ip_version = 0;
  12874. return 0;
  12875. }
  12876. /* Is there any SSL port in use? */
  12877. static int
  12878. is_ssl_port_used(const char *ports)
  12879. {
  12880. if (ports) {
  12881. /* There are several different allowed syntax variants:
  12882. * - "80" for a single port using every network interface
  12883. * - "localhost:80" for a single port using only localhost
  12884. * - "80,localhost:8080" for two ports, one bound to localhost
  12885. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12886. * to IPv4 localhost, one to IPv6 localhost
  12887. * - "+80" use port 80 for IPv4 and IPv6
  12888. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12889. * for both: IPv4 and IPv4
  12890. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12891. * additionally port 8080 bound to localhost connections
  12892. *
  12893. * If we just look for 's' anywhere in the string, "localhost:80"
  12894. * will be detected as SSL (false positive).
  12895. * Looking for 's' after a digit may cause false positives in
  12896. * "my24service:8080".
  12897. * Looking from 's' backward if there are only ':' and numbers
  12898. * before will not work for "24service:8080" (non SSL, port 8080)
  12899. * or "24s" (SSL, port 24).
  12900. *
  12901. * Remark: Initially hostnames were not allowed to start with a
  12902. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12903. * Section 2.1).
  12904. *
  12905. * To get this correct, the entire string must be parsed as a whole,
  12906. * reading it as a list element for element and parsing with an
  12907. * algorithm equivalent to parse_port_string.
  12908. *
  12909. * In fact, we use local interface names here, not arbitrary
  12910. * hostnames, so in most cases the only name will be "localhost".
  12911. *
  12912. * So, for now, we use this simple algorithm, that may still return
  12913. * a false positive in bizarre cases.
  12914. */
  12915. int i;
  12916. int portslen = (int)strlen(ports);
  12917. char prevIsNumber = 0;
  12918. for (i = 0; i < portslen; i++) {
  12919. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12920. return 1;
  12921. }
  12922. if (ports[i] >= '0' && ports[i] <= '9') {
  12923. prevIsNumber = 1;
  12924. } else {
  12925. prevIsNumber = 0;
  12926. }
  12927. }
  12928. }
  12929. return 0;
  12930. }
  12931. static int
  12932. set_ports_option(struct mg_context *phys_ctx)
  12933. {
  12934. const char *list;
  12935. int on = 1;
  12936. #if defined(USE_IPV6)
  12937. int off = 0;
  12938. #endif
  12939. struct vec vec;
  12940. struct socket so, *ptr;
  12941. struct mg_pollfd *pfd;
  12942. union usa usa;
  12943. socklen_t len;
  12944. int ip_version;
  12945. int portsTotal = 0;
  12946. int portsOk = 0;
  12947. const char *opt_txt;
  12948. long opt_listen_backlog;
  12949. if (!phys_ctx) {
  12950. return 0;
  12951. }
  12952. memset(&so, 0, sizeof(so));
  12953. memset(&usa, 0, sizeof(usa));
  12954. len = sizeof(usa);
  12955. list = phys_ctx->dd.config[LISTENING_PORTS];
  12956. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12957. portsTotal++;
  12958. if (!parse_port_string(&vec, &so, &ip_version)) {
  12959. mg_cry_ctx_internal(
  12960. phys_ctx,
  12961. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12962. (int)vec.len,
  12963. vec.ptr,
  12964. portsTotal,
  12965. "[IP_ADDRESS:]PORT[s|r]");
  12966. continue;
  12967. }
  12968. #if !defined(NO_SSL)
  12969. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12970. mg_cry_ctx_internal(phys_ctx,
  12971. "Cannot add SSL socket (entry %i)",
  12972. portsTotal);
  12973. continue;
  12974. }
  12975. #endif
  12976. /* Create socket. */
  12977. /* For a list of protocol numbers (e.g., TCP==6) see:
  12978. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  12979. */
  12980. if ((so.sock =
  12981. socket(so.lsa.sa.sa_family,
  12982. SOCK_STREAM,
  12983. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  12984. == INVALID_SOCKET) {
  12985. mg_cry_ctx_internal(phys_ctx,
  12986. "cannot create socket (entry %i)",
  12987. portsTotal);
  12988. continue;
  12989. }
  12990. #if defined(_WIN32)
  12991. /* Windows SO_REUSEADDR lets many procs binds to a
  12992. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12993. * if someone already has the socket -- DTL */
  12994. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12995. * Windows might need a few seconds before
  12996. * the same port can be used again in the
  12997. * same process, so a short Sleep may be
  12998. * required between mg_stop and mg_start.
  12999. */
  13000. if (setsockopt(so.sock,
  13001. SOL_SOCKET,
  13002. SO_EXCLUSIVEADDRUSE,
  13003. (SOCK_OPT_TYPE)&on,
  13004. sizeof(on))
  13005. != 0) {
  13006. /* Set reuse option, but don't abort on errors. */
  13007. mg_cry_ctx_internal(
  13008. phys_ctx,
  13009. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13010. portsTotal);
  13011. }
  13012. #else
  13013. if (setsockopt(so.sock,
  13014. SOL_SOCKET,
  13015. SO_REUSEADDR,
  13016. (SOCK_OPT_TYPE)&on,
  13017. sizeof(on))
  13018. != 0) {
  13019. /* Set reuse option, but don't abort on errors. */
  13020. mg_cry_ctx_internal(
  13021. phys_ctx,
  13022. "cannot set socket option SO_REUSEADDR (entry %i)",
  13023. portsTotal);
  13024. }
  13025. #endif
  13026. #if defined(USE_X_DOM_SOCKET)
  13027. if (ip_version == 99) {
  13028. /* Unix domain socket */
  13029. } else
  13030. #endif
  13031. if (ip_version > 4) {
  13032. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13033. #if defined(USE_IPV6)
  13034. if (ip_version > 6) {
  13035. if (so.lsa.sa.sa_family == AF_INET6
  13036. && setsockopt(so.sock,
  13037. IPPROTO_IPV6,
  13038. IPV6_V6ONLY,
  13039. (void *)&off,
  13040. sizeof(off))
  13041. != 0) {
  13042. /* Set IPv6 only option, but don't abort on errors. */
  13043. mg_cry_ctx_internal(phys_ctx,
  13044. "cannot set socket option "
  13045. "IPV6_V6ONLY=off (entry %i)",
  13046. portsTotal);
  13047. }
  13048. } else {
  13049. if (so.lsa.sa.sa_family == AF_INET6
  13050. && setsockopt(so.sock,
  13051. IPPROTO_IPV6,
  13052. IPV6_V6ONLY,
  13053. (void *)&on,
  13054. sizeof(on))
  13055. != 0) {
  13056. /* Set IPv6 only option, but don't abort on errors. */
  13057. mg_cry_ctx_internal(phys_ctx,
  13058. "cannot set socket option "
  13059. "IPV6_V6ONLY=on (entry %i)",
  13060. portsTotal);
  13061. }
  13062. }
  13063. #else
  13064. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13065. closesocket(so.sock);
  13066. so.sock = INVALID_SOCKET;
  13067. continue;
  13068. #endif
  13069. }
  13070. if (so.lsa.sa.sa_family == AF_INET) {
  13071. len = sizeof(so.lsa.sin);
  13072. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13073. mg_cry_ctx_internal(phys_ctx,
  13074. "cannot bind to %.*s: %d (%s)",
  13075. (int)vec.len,
  13076. vec.ptr,
  13077. (int)ERRNO,
  13078. strerror(errno));
  13079. closesocket(so.sock);
  13080. so.sock = INVALID_SOCKET;
  13081. continue;
  13082. }
  13083. }
  13084. #if defined(USE_IPV6)
  13085. else if (so.lsa.sa.sa_family == AF_INET6) {
  13086. len = sizeof(so.lsa.sin6);
  13087. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13088. mg_cry_ctx_internal(phys_ctx,
  13089. "cannot bind to IPv6 %.*s: %d (%s)",
  13090. (int)vec.len,
  13091. vec.ptr,
  13092. (int)ERRNO,
  13093. strerror(errno));
  13094. closesocket(so.sock);
  13095. so.sock = INVALID_SOCKET;
  13096. continue;
  13097. }
  13098. }
  13099. #endif
  13100. #if defined(USE_X_DOM_SOCKET)
  13101. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13102. len = sizeof(so.lsa.sun);
  13103. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13104. mg_cry_ctx_internal(phys_ctx,
  13105. "cannot bind to unix socket %s: %d (%s)",
  13106. so.lsa.sun.sun_path,
  13107. (int)ERRNO,
  13108. strerror(errno));
  13109. closesocket(so.sock);
  13110. so.sock = INVALID_SOCKET;
  13111. continue;
  13112. }
  13113. }
  13114. #endif
  13115. else {
  13116. mg_cry_ctx_internal(
  13117. phys_ctx,
  13118. "cannot bind: address family not supported (entry %i)",
  13119. portsTotal);
  13120. closesocket(so.sock);
  13121. so.sock = INVALID_SOCKET;
  13122. continue;
  13123. }
  13124. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13125. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13126. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13127. mg_cry_ctx_internal(phys_ctx,
  13128. "%s value \"%s\" is invalid",
  13129. config_options[LISTEN_BACKLOG_SIZE].name,
  13130. opt_txt);
  13131. closesocket(so.sock);
  13132. so.sock = INVALID_SOCKET;
  13133. continue;
  13134. }
  13135. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13136. mg_cry_ctx_internal(phys_ctx,
  13137. "cannot listen to %.*s: %d (%s)",
  13138. (int)vec.len,
  13139. vec.ptr,
  13140. (int)ERRNO,
  13141. strerror(errno));
  13142. closesocket(so.sock);
  13143. so.sock = INVALID_SOCKET;
  13144. continue;
  13145. }
  13146. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13147. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13148. int err = (int)ERRNO;
  13149. mg_cry_ctx_internal(phys_ctx,
  13150. "call to getsockname failed %.*s: %d (%s)",
  13151. (int)vec.len,
  13152. vec.ptr,
  13153. err,
  13154. strerror(errno));
  13155. closesocket(so.sock);
  13156. so.sock = INVALID_SOCKET;
  13157. continue;
  13158. }
  13159. /* Update lsa port in case of random free ports */
  13160. #if defined(USE_IPV6)
  13161. if (so.lsa.sa.sa_family == AF_INET6) {
  13162. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13163. } else
  13164. #endif
  13165. {
  13166. so.lsa.sin.sin_port = usa.sin.sin_port;
  13167. }
  13168. if ((ptr = (struct socket *)
  13169. mg_realloc_ctx(phys_ctx->listening_sockets,
  13170. (phys_ctx->num_listening_sockets + 1)
  13171. * sizeof(phys_ctx->listening_sockets[0]),
  13172. phys_ctx))
  13173. == NULL) {
  13174. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13175. closesocket(so.sock);
  13176. so.sock = INVALID_SOCKET;
  13177. continue;
  13178. }
  13179. if ((pfd = (struct mg_pollfd *)
  13180. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13181. (phys_ctx->num_listening_sockets + 1)
  13182. * sizeof(phys_ctx->listening_socket_fds[0]),
  13183. phys_ctx))
  13184. == NULL) {
  13185. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13186. closesocket(so.sock);
  13187. so.sock = INVALID_SOCKET;
  13188. mg_free(ptr);
  13189. continue;
  13190. }
  13191. set_close_on_exec(so.sock, NULL, phys_ctx);
  13192. phys_ctx->listening_sockets = ptr;
  13193. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13194. phys_ctx->listening_socket_fds = pfd;
  13195. phys_ctx->num_listening_sockets++;
  13196. portsOk++;
  13197. }
  13198. if (portsOk != portsTotal) {
  13199. close_all_listening_sockets(phys_ctx);
  13200. portsOk = 0;
  13201. }
  13202. return portsOk;
  13203. }
  13204. static const char *
  13205. header_val(const struct mg_connection *conn, const char *header)
  13206. {
  13207. const char *header_value;
  13208. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13209. return "-";
  13210. } else {
  13211. return header_value;
  13212. }
  13213. }
  13214. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13215. #include "external_log_access.inl"
  13216. #elif !defined(NO_FILESYSTEMS)
  13217. static void
  13218. log_access(const struct mg_connection *conn)
  13219. {
  13220. const struct mg_request_info *ri;
  13221. struct mg_file fi;
  13222. char date[64], src_addr[IP_ADDR_STR_LEN];
  13223. struct tm *tm;
  13224. const char *referer;
  13225. const char *user_agent;
  13226. char log_buf[4096];
  13227. if (!conn || !conn->dom_ctx) {
  13228. return;
  13229. }
  13230. /* Set log message to "empty" */
  13231. log_buf[0] = 0;
  13232. #if defined(USE_LUA)
  13233. if (conn->phys_ctx->lua_bg_log_available) {
  13234. int ret;
  13235. struct mg_context *ctx = conn->phys_ctx;
  13236. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13237. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13238. /* call "log()" in Lua */
  13239. lua_getglobal(lstate, "log");
  13240. prepare_lua_request_info_inner(conn, lstate);
  13241. push_lua_response_log_data(conn, lstate);
  13242. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13243. if (ret == 0) {
  13244. int t = lua_type(lstate, -1);
  13245. if (t == LUA_TBOOLEAN) {
  13246. if (lua_toboolean(lstate, -1) == 0) {
  13247. /* log() returned false: do not log */
  13248. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13249. return;
  13250. }
  13251. /* log returned true: continue logging */
  13252. } else if (t == LUA_TSTRING) {
  13253. size_t len;
  13254. const char *txt = lua_tolstring(lstate, -1, &len);
  13255. if ((len == 0) || (*txt == 0)) {
  13256. /* log() returned empty string: do not log */
  13257. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13258. return;
  13259. }
  13260. /* Copy test from Lua into log_buf */
  13261. if (len >= sizeof(log_buf)) {
  13262. len = sizeof(log_buf) - 1;
  13263. }
  13264. memcpy(log_buf, txt, len);
  13265. log_buf[len] = 0;
  13266. }
  13267. } else {
  13268. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13269. }
  13270. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13271. }
  13272. #endif
  13273. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13274. if (mg_fopen(conn,
  13275. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13276. MG_FOPEN_MODE_APPEND,
  13277. &fi)
  13278. == 0) {
  13279. fi.access.fp = NULL;
  13280. }
  13281. } else {
  13282. fi.access.fp = NULL;
  13283. }
  13284. /* Log is written to a file and/or a callback. If both are not set,
  13285. * executing the rest of the function is pointless. */
  13286. if ((fi.access.fp == NULL)
  13287. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13288. return;
  13289. }
  13290. /* If we did not get a log message from Lua, create it here. */
  13291. if (!log_buf[0]) {
  13292. tm = localtime(&conn->conn_birth_time);
  13293. if (tm != NULL) {
  13294. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13295. } else {
  13296. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13297. date[sizeof(date) - 1] = '\0';
  13298. }
  13299. ri = &conn->request_info;
  13300. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13301. referer = header_val(conn, "Referer");
  13302. user_agent = header_val(conn, "User-Agent");
  13303. mg_snprintf(conn,
  13304. NULL, /* Ignore truncation in access log */
  13305. log_buf,
  13306. sizeof(log_buf),
  13307. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13308. " %s %s",
  13309. src_addr,
  13310. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13311. date,
  13312. ri->request_method ? ri->request_method : "-",
  13313. ri->request_uri ? ri->request_uri : "-",
  13314. ri->query_string ? "?" : "",
  13315. ri->query_string ? ri->query_string : "",
  13316. ri->http_version,
  13317. conn->status_code,
  13318. conn->num_bytes_sent,
  13319. referer,
  13320. user_agent);
  13321. }
  13322. /* Here we have a log message in log_buf. Call the callback */
  13323. if (conn->phys_ctx->callbacks.log_access) {
  13324. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13325. /* do not log if callack returns non-zero */
  13326. if (fi.access.fp) {
  13327. mg_fclose(&fi.access);
  13328. }
  13329. return;
  13330. }
  13331. }
  13332. /* Store in file */
  13333. if (fi.access.fp) {
  13334. int ok = 1;
  13335. flockfile(fi.access.fp);
  13336. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13337. ok = 0;
  13338. }
  13339. if (fflush(fi.access.fp) != 0) {
  13340. ok = 0;
  13341. }
  13342. funlockfile(fi.access.fp);
  13343. if (mg_fclose(&fi.access) != 0) {
  13344. ok = 0;
  13345. }
  13346. if (!ok) {
  13347. mg_cry_internal(conn,
  13348. "Error writing log file %s",
  13349. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13350. }
  13351. }
  13352. }
  13353. #else
  13354. #error "Either enable filesystems or provide a custom log_access implementation"
  13355. #endif /* Externally provided function */
  13356. /* Verify given socket address against the ACL.
  13357. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13358. */
  13359. static int
  13360. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13361. {
  13362. int allowed, flag, matched;
  13363. struct vec vec;
  13364. if (phys_ctx) {
  13365. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13366. /* If any ACL is set, deny by default */
  13367. allowed = (list == NULL) ? '+' : '-';
  13368. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13369. flag = vec.ptr[0];
  13370. matched = -1;
  13371. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13372. vec.ptr++;
  13373. vec.len--;
  13374. matched = parse_match_net(&vec, sa, 1);
  13375. }
  13376. if (matched < 0) {
  13377. mg_cry_ctx_internal(phys_ctx,
  13378. "%s: subnet must be [+|-]IP-addr[/x]",
  13379. __func__);
  13380. return -1;
  13381. }
  13382. if (matched) {
  13383. allowed = flag;
  13384. }
  13385. }
  13386. return allowed == '+';
  13387. }
  13388. return -1;
  13389. }
  13390. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13391. static int
  13392. set_uid_option(struct mg_context *phys_ctx)
  13393. {
  13394. int success = 0;
  13395. if (phys_ctx) {
  13396. /* We are currently running as curr_uid. */
  13397. const uid_t curr_uid = getuid();
  13398. /* If set, we want to run as run_as_user. */
  13399. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13400. const struct passwd *to_pw = NULL;
  13401. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13402. /* run_as_user does not exist on the system. We can't proceed
  13403. * further. */
  13404. mg_cry_ctx_internal(phys_ctx,
  13405. "%s: unknown user [%s]",
  13406. __func__,
  13407. run_as_user);
  13408. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13409. /* There was either no request to change user, or we're already
  13410. * running as run_as_user. Nothing else to do.
  13411. */
  13412. success = 1;
  13413. } else {
  13414. /* Valid change request. */
  13415. if (setgid(to_pw->pw_gid) == -1) {
  13416. mg_cry_ctx_internal(phys_ctx,
  13417. "%s: setgid(%s): %s",
  13418. __func__,
  13419. run_as_user,
  13420. strerror(errno));
  13421. } else if (setgroups(0, NULL) == -1) {
  13422. mg_cry_ctx_internal(phys_ctx,
  13423. "%s: setgroups(): %s",
  13424. __func__,
  13425. strerror(errno));
  13426. } else if (setuid(to_pw->pw_uid) == -1) {
  13427. mg_cry_ctx_internal(phys_ctx,
  13428. "%s: setuid(%s): %s",
  13429. __func__,
  13430. run_as_user,
  13431. strerror(errno));
  13432. } else {
  13433. success = 1;
  13434. }
  13435. }
  13436. }
  13437. return success;
  13438. }
  13439. #endif /* !_WIN32 */
  13440. static void
  13441. tls_dtor(void *key)
  13442. {
  13443. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13444. /* key == pthread_getspecific(sTlsKey); */
  13445. if (tls) {
  13446. if (tls->is_master == 2) {
  13447. tls->is_master = -3; /* Mark memory as dead */
  13448. mg_free(tls);
  13449. }
  13450. }
  13451. pthread_setspecific(sTlsKey, NULL);
  13452. }
  13453. #if defined(USE_MBEDTLS)
  13454. /* Check if SSL is required.
  13455. * If so, set up ctx->ssl_ctx pointer. */
  13456. static int
  13457. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13458. {
  13459. if (!phys_ctx) {
  13460. return 0;
  13461. }
  13462. if (!dom_ctx) {
  13463. dom_ctx = &(phys_ctx->dd);
  13464. }
  13465. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13466. /* No SSL port is set. No need to setup SSL. */
  13467. return 1;
  13468. }
  13469. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13470. if (dom_ctx->ssl_ctx == NULL) {
  13471. fprintf(stderr, "ssl_ctx malloc failed\n");
  13472. return 0;
  13473. }
  13474. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13475. == 0
  13476. ? 1
  13477. : 0;
  13478. }
  13479. #elif !defined(NO_SSL)
  13480. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13481. struct mg_domain_context *dom_ctx,
  13482. const char *pem,
  13483. const char *chain);
  13484. static const char *ssl_error(void);
  13485. static int
  13486. refresh_trust(struct mg_connection *conn)
  13487. {
  13488. struct stat cert_buf;
  13489. int64_t t = 0;
  13490. const char *pem;
  13491. const char *chain;
  13492. int should_verify_peer;
  13493. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13494. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13495. * refresh_trust still can not work. */
  13496. return 0;
  13497. }
  13498. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13499. if (chain == NULL) {
  13500. /* pem is not NULL here */
  13501. chain = pem;
  13502. }
  13503. if (*chain == 0) {
  13504. chain = NULL;
  13505. }
  13506. if (stat(pem, &cert_buf) != -1) {
  13507. t = (int64_t)cert_buf.st_mtime;
  13508. }
  13509. mg_lock_context(conn->phys_ctx);
  13510. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13511. conn->dom_ctx->ssl_cert_last_mtime = t;
  13512. should_verify_peer = 0;
  13513. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13514. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13515. == 0) {
  13516. should_verify_peer = 1;
  13517. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13518. "optional")
  13519. == 0) {
  13520. should_verify_peer = 1;
  13521. }
  13522. }
  13523. if (should_verify_peer) {
  13524. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13525. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13526. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13527. ca_file,
  13528. ca_path)
  13529. != 1) {
  13530. mg_unlock_context(conn->phys_ctx);
  13531. mg_cry_ctx_internal(
  13532. conn->phys_ctx,
  13533. "SSL_CTX_load_verify_locations error: %s "
  13534. "ssl_verify_peer requires setting "
  13535. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13536. "present in "
  13537. "the .conf file?",
  13538. ssl_error());
  13539. return 0;
  13540. }
  13541. }
  13542. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13543. mg_unlock_context(conn->phys_ctx);
  13544. return 0;
  13545. }
  13546. }
  13547. mg_unlock_context(conn->phys_ctx);
  13548. return 1;
  13549. }
  13550. #if defined(OPENSSL_API_1_1)
  13551. #else
  13552. static pthread_mutex_t *ssl_mutexes;
  13553. #endif /* OPENSSL_API_1_1 */
  13554. static int
  13555. sslize(struct mg_connection *conn,
  13556. int (*func)(SSL *),
  13557. const struct mg_client_options *client_options)
  13558. {
  13559. int ret, err;
  13560. int short_trust;
  13561. unsigned timeout = 1024;
  13562. unsigned i;
  13563. if (!conn) {
  13564. return 0;
  13565. }
  13566. short_trust =
  13567. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13568. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13569. if (short_trust) {
  13570. int trust_ret = refresh_trust(conn);
  13571. if (!trust_ret) {
  13572. return trust_ret;
  13573. }
  13574. }
  13575. mg_lock_context(conn->phys_ctx);
  13576. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13577. mg_unlock_context(conn->phys_ctx);
  13578. if (conn->ssl == NULL) {
  13579. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13580. OPENSSL_REMOVE_THREAD_STATE();
  13581. return 0;
  13582. }
  13583. SSL_set_app_data(conn->ssl, (char *)conn);
  13584. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13585. if (ret != 1) {
  13586. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13587. SSL_free(conn->ssl);
  13588. conn->ssl = NULL;
  13589. OPENSSL_REMOVE_THREAD_STATE();
  13590. return 0;
  13591. }
  13592. if (client_options) {
  13593. if (client_options->host_name) {
  13594. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13595. }
  13596. }
  13597. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13598. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13599. /* NOTE: The loop below acts as a back-off, so we can end
  13600. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13601. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13602. if (to >= 0) {
  13603. timeout = (unsigned)to;
  13604. }
  13605. }
  13606. /* SSL functions may fail and require to be called again:
  13607. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13608. * Here "func" could be SSL_connect or SSL_accept. */
  13609. for (i = 0; i <= timeout; i += 50) {
  13610. ERR_clear_error();
  13611. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13612. ret = func(conn->ssl);
  13613. if (ret != 1) {
  13614. err = SSL_get_error(conn->ssl, ret);
  13615. if ((err == SSL_ERROR_WANT_CONNECT)
  13616. || (err == SSL_ERROR_WANT_ACCEPT)
  13617. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13618. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13619. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13620. /* Don't wait if the server is going to be stopped. */
  13621. break;
  13622. }
  13623. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13624. /* Simply retry the function call. */
  13625. mg_sleep(50);
  13626. } else {
  13627. /* Need to retry the function call "later".
  13628. * See https://linux.die.net/man/3/ssl_get_error
  13629. * This is typical for non-blocking sockets. */
  13630. struct mg_pollfd pfd;
  13631. int pollres;
  13632. pfd.fd = conn->client.sock;
  13633. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13634. || (err == SSL_ERROR_WANT_WRITE))
  13635. ? POLLOUT
  13636. : POLLIN;
  13637. pollres =
  13638. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13639. if (pollres < 0) {
  13640. /* Break if error occured (-1)
  13641. * or server shutdown (-2) */
  13642. break;
  13643. }
  13644. }
  13645. } else if (err == SSL_ERROR_SYSCALL) {
  13646. /* This is an IO error. Look at errno. */
  13647. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13648. break;
  13649. } else {
  13650. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13651. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13652. break;
  13653. }
  13654. } else {
  13655. /* success */
  13656. break;
  13657. }
  13658. }
  13659. ERR_clear_error();
  13660. if (ret != 1) {
  13661. SSL_free(conn->ssl);
  13662. conn->ssl = NULL;
  13663. OPENSSL_REMOVE_THREAD_STATE();
  13664. return 0;
  13665. }
  13666. return 1;
  13667. }
  13668. /* Return OpenSSL error message (from CRYPTO lib) */
  13669. static const char *
  13670. ssl_error(void)
  13671. {
  13672. unsigned long err;
  13673. err = ERR_get_error();
  13674. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13675. }
  13676. static int
  13677. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13678. {
  13679. int i;
  13680. const char hexdigit[] = "0123456789abcdef";
  13681. if ((memlen <= 0) || (buflen <= 0)) {
  13682. return 0;
  13683. }
  13684. if (buflen < (3 * memlen)) {
  13685. return 0;
  13686. }
  13687. for (i = 0; i < memlen; i++) {
  13688. if (i > 0) {
  13689. buf[3 * i - 1] = ' ';
  13690. }
  13691. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13692. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13693. }
  13694. buf[3 * memlen - 1] = 0;
  13695. return 1;
  13696. }
  13697. static int
  13698. ssl_get_client_cert_info(const struct mg_connection *conn,
  13699. struct mg_client_cert *client_cert)
  13700. {
  13701. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13702. if (cert) {
  13703. char str_buf[1024];
  13704. unsigned char buf[256];
  13705. char *str_serial = NULL;
  13706. unsigned int ulen;
  13707. int ilen;
  13708. unsigned char *tmp_buf;
  13709. unsigned char *tmp_p;
  13710. /* Handle to algorithm used for fingerprint */
  13711. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13712. /* Get Subject and issuer */
  13713. X509_NAME *subj = X509_get_subject_name(cert);
  13714. X509_NAME *iss = X509_get_issuer_name(cert);
  13715. /* Get serial number */
  13716. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13717. /* Translate serial number to a hex string */
  13718. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13719. if (serial_bn) {
  13720. str_serial = BN_bn2hex(serial_bn);
  13721. BN_free(serial_bn);
  13722. }
  13723. client_cert->serial =
  13724. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13725. /* Translate subject and issuer to a string */
  13726. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13727. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13728. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13729. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13730. /* Calculate SHA1 fingerprint and store as a hex string */
  13731. ulen = 0;
  13732. /* ASN1_digest is deprecated. Do the calculation manually,
  13733. * using EVP_Digest. */
  13734. ilen = i2d_X509(cert, NULL);
  13735. tmp_buf = (ilen > 0)
  13736. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13737. conn->phys_ctx)
  13738. : NULL;
  13739. if (tmp_buf) {
  13740. tmp_p = tmp_buf;
  13741. (void)i2d_X509(cert, &tmp_p);
  13742. if (!EVP_Digest(
  13743. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13744. ulen = 0;
  13745. }
  13746. mg_free(tmp_buf);
  13747. }
  13748. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13749. *str_buf = 0;
  13750. }
  13751. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13752. client_cert->peer_cert = (void *)cert;
  13753. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13754. * see https://linux.die.net/man/3/bn_bn2hex */
  13755. OPENSSL_free(str_serial);
  13756. return 1;
  13757. }
  13758. return 0;
  13759. }
  13760. #if defined(OPENSSL_API_1_1)
  13761. #else
  13762. static void
  13763. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13764. {
  13765. (void)line;
  13766. (void)file;
  13767. if (mode & 1) {
  13768. /* 1 is CRYPTO_LOCK */
  13769. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13770. } else {
  13771. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13772. }
  13773. }
  13774. #endif /* OPENSSL_API_1_1 */
  13775. #if !defined(NO_SSL_DL)
  13776. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13777. static void *
  13778. load_tls_dll(char *ebuf,
  13779. size_t ebuf_len,
  13780. const char *dll_name,
  13781. struct ssl_func *sw,
  13782. int *feature_missing)
  13783. {
  13784. union {
  13785. void *p;
  13786. void (*fp)(void);
  13787. } u;
  13788. void *dll_handle;
  13789. struct ssl_func *fp;
  13790. int ok;
  13791. int truncated = 0;
  13792. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13793. mg_snprintf(NULL,
  13794. NULL, /* No truncation check for ebuf */
  13795. ebuf,
  13796. ebuf_len,
  13797. "%s: cannot load %s",
  13798. __func__,
  13799. dll_name);
  13800. return NULL;
  13801. }
  13802. ok = 1;
  13803. for (fp = sw; fp->name != NULL; fp++) {
  13804. #if defined(_WIN32)
  13805. /* GetProcAddress() returns pointer to function */
  13806. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13807. #else
  13808. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13809. * pointers to function pointers. We need to use a union to make a
  13810. * cast. */
  13811. u.p = dlsym(dll_handle, fp->name);
  13812. #endif /* _WIN32 */
  13813. /* Set pointer (might be NULL) */
  13814. fp->ptr = u.fp;
  13815. if (u.fp == NULL) {
  13816. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13817. if (feature_missing) {
  13818. feature_missing[fp->required]++;
  13819. }
  13820. if (fp->required == TLS_Mandatory) {
  13821. /* Mandatory function is missing */
  13822. if (ok) {
  13823. /* This is the first missing function.
  13824. * Create a new error message. */
  13825. mg_snprintf(NULL,
  13826. &truncated,
  13827. ebuf,
  13828. ebuf_len,
  13829. "%s: %s: cannot find %s",
  13830. __func__,
  13831. dll_name,
  13832. fp->name);
  13833. ok = 0;
  13834. } else {
  13835. /* This is yet anothermissing function.
  13836. * Append existing error message. */
  13837. size_t cur_len = strlen(ebuf);
  13838. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13839. mg_snprintf(NULL,
  13840. &truncated,
  13841. ebuf + cur_len,
  13842. ebuf_len - cur_len - 3,
  13843. ", %s",
  13844. fp->name);
  13845. if (truncated) {
  13846. /* If truncated, add "..." */
  13847. strcat(ebuf, "...");
  13848. }
  13849. }
  13850. }
  13851. }
  13852. }
  13853. }
  13854. if (!ok) {
  13855. (void)dlclose(dll_handle);
  13856. return NULL;
  13857. }
  13858. return dll_handle;
  13859. }
  13860. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13861. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13862. #endif /* NO_SSL_DL */
  13863. #if defined(SSL_ALREADY_INITIALIZED)
  13864. static volatile ptrdiff_t cryptolib_users =
  13865. 1; /* Reference counter for crypto library. */
  13866. #else
  13867. static volatile ptrdiff_t cryptolib_users =
  13868. 0; /* Reference counter for crypto library. */
  13869. #endif
  13870. static int
  13871. initialize_openssl(char *ebuf, size_t ebuf_len)
  13872. {
  13873. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13874. int i, num_locks;
  13875. size_t size;
  13876. #endif
  13877. if (ebuf_len > 0) {
  13878. ebuf[0] = 0;
  13879. }
  13880. #if !defined(NO_SSL_DL)
  13881. if (!cryptolib_dll_handle) {
  13882. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13883. cryptolib_dll_handle = load_tls_dll(
  13884. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13885. if (!cryptolib_dll_handle) {
  13886. mg_snprintf(NULL,
  13887. NULL, /* No truncation check for ebuf */
  13888. ebuf,
  13889. ebuf_len,
  13890. "%s: error loading library %s",
  13891. __func__,
  13892. CRYPTO_LIB);
  13893. DEBUG_TRACE("%s", ebuf);
  13894. return 0;
  13895. }
  13896. }
  13897. #endif /* NO_SSL_DL */
  13898. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13899. return 1;
  13900. }
  13901. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13902. /* Initialize locking callbacks, needed for thread safety.
  13903. * http://www.openssl.org/support/faq.html#PROG1
  13904. */
  13905. num_locks = CRYPTO_num_locks();
  13906. if (num_locks < 0) {
  13907. num_locks = 0;
  13908. }
  13909. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13910. /* allocate mutex array, if required */
  13911. if (num_locks == 0) {
  13912. /* No mutex array required */
  13913. ssl_mutexes = NULL;
  13914. } else {
  13915. /* Mutex array required - allocate it */
  13916. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13917. /* Check OOM */
  13918. if (ssl_mutexes == NULL) {
  13919. mg_snprintf(NULL,
  13920. NULL, /* No truncation check for ebuf */
  13921. ebuf,
  13922. ebuf_len,
  13923. "%s: cannot allocate mutexes: %s",
  13924. __func__,
  13925. ssl_error());
  13926. DEBUG_TRACE("%s", ebuf);
  13927. return 0;
  13928. }
  13929. /* initialize mutex array */
  13930. for (i = 0; i < num_locks; i++) {
  13931. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13932. mg_snprintf(NULL,
  13933. NULL, /* No truncation check for ebuf */
  13934. ebuf,
  13935. ebuf_len,
  13936. "%s: error initializing mutex %i of %i",
  13937. __func__,
  13938. i,
  13939. num_locks);
  13940. DEBUG_TRACE("%s", ebuf);
  13941. mg_free(ssl_mutexes);
  13942. return 0;
  13943. }
  13944. }
  13945. }
  13946. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13947. CRYPTO_set_id_callback(&mg_current_thread_id);
  13948. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  13949. #if !defined(NO_SSL_DL)
  13950. if (!ssllib_dll_handle) {
  13951. ssllib_dll_handle =
  13952. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13953. if (!ssllib_dll_handle) {
  13954. #if !defined(OPENSSL_API_1_1)
  13955. mg_free(ssl_mutexes);
  13956. #endif
  13957. DEBUG_TRACE("%s", ebuf);
  13958. return 0;
  13959. }
  13960. }
  13961. #endif /* NO_SSL_DL */
  13962. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  13963. && !defined(NO_SSL_DL)
  13964. /* Initialize SSL library */
  13965. OPENSSL_init_ssl(0, NULL);
  13966. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13967. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13968. NULL);
  13969. #else
  13970. /* Initialize SSL library */
  13971. SSL_library_init();
  13972. SSL_load_error_strings();
  13973. #endif
  13974. return 1;
  13975. }
  13976. static int
  13977. ssl_use_pem_file(struct mg_context *phys_ctx,
  13978. struct mg_domain_context *dom_ctx,
  13979. const char *pem,
  13980. const char *chain)
  13981. {
  13982. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13983. mg_cry_ctx_internal(phys_ctx,
  13984. "%s: cannot open certificate file %s: %s",
  13985. __func__,
  13986. pem,
  13987. ssl_error());
  13988. return 0;
  13989. }
  13990. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13991. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13992. mg_cry_ctx_internal(phys_ctx,
  13993. "%s: cannot open private key file %s: %s",
  13994. __func__,
  13995. pem,
  13996. ssl_error());
  13997. return 0;
  13998. }
  13999. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14000. mg_cry_ctx_internal(phys_ctx,
  14001. "%s: certificate and private key do not match: %s",
  14002. __func__,
  14003. pem);
  14004. return 0;
  14005. }
  14006. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14007. * chain files that contain private keys and certificates in
  14008. * SSL_CTX_use_certificate_chain_file.
  14009. * The CivetWeb-Server used pem-Files that contained both information.
  14010. * In order to make wolfSSL work, it is split in two files.
  14011. * One file that contains key and certificate used by the server and
  14012. * an optional chain file for the ssl stack.
  14013. */
  14014. if (chain) {
  14015. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14016. mg_cry_ctx_internal(phys_ctx,
  14017. "%s: cannot use certificate chain file %s: %s",
  14018. __func__,
  14019. chain,
  14020. ssl_error());
  14021. return 0;
  14022. }
  14023. }
  14024. return 1;
  14025. }
  14026. #if defined(OPENSSL_API_1_1)
  14027. static unsigned long
  14028. ssl_get_protocol(int version_id)
  14029. {
  14030. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14031. if (version_id > 0)
  14032. ret |= SSL_OP_NO_SSLv2;
  14033. if (version_id > 1)
  14034. ret |= SSL_OP_NO_SSLv3;
  14035. if (version_id > 2)
  14036. ret |= SSL_OP_NO_TLSv1;
  14037. if (version_id > 3)
  14038. ret |= SSL_OP_NO_TLSv1_1;
  14039. if (version_id > 4)
  14040. ret |= SSL_OP_NO_TLSv1_2;
  14041. #if defined(SSL_OP_NO_TLSv1_3)
  14042. if (version_id > 5)
  14043. ret |= SSL_OP_NO_TLSv1_3;
  14044. #endif
  14045. return ret;
  14046. }
  14047. #else
  14048. static long
  14049. ssl_get_protocol(int version_id)
  14050. {
  14051. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14052. if (version_id > 0)
  14053. ret |= SSL_OP_NO_SSLv2;
  14054. if (version_id > 1)
  14055. ret |= SSL_OP_NO_SSLv3;
  14056. if (version_id > 2)
  14057. ret |= SSL_OP_NO_TLSv1;
  14058. if (version_id > 3)
  14059. ret |= SSL_OP_NO_TLSv1_1;
  14060. if (version_id > 4)
  14061. ret |= SSL_OP_NO_TLSv1_2;
  14062. #if defined(SSL_OP_NO_TLSv1_3)
  14063. if (version_id > 5)
  14064. ret |= SSL_OP_NO_TLSv1_3;
  14065. #endif
  14066. return (long)ret;
  14067. }
  14068. #endif /* OPENSSL_API_1_1 */
  14069. /* SSL callback documentation:
  14070. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14071. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14072. * https://linux.die.net/man/3/ssl_set_info_callback */
  14073. /* Note: There is no "const" for the first argument in the documentation
  14074. * examples, however some (maybe most, but not all) headers of OpenSSL
  14075. * versions / OpenSSL compatibility layers have it. Having a different
  14076. * definition will cause a warning in C and an error in C++. Use "const SSL
  14077. * *", while automatical conversion from "SSL *" works for all compilers,
  14078. * but not other way around */
  14079. static void
  14080. ssl_info_callback(const SSL *ssl, int what, int ret)
  14081. {
  14082. (void)ret;
  14083. if (what & SSL_CB_HANDSHAKE_START) {
  14084. SSL_get_app_data(ssl);
  14085. }
  14086. if (what & SSL_CB_HANDSHAKE_DONE) {
  14087. /* TODO: check for openSSL 1.1 */
  14088. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14089. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14090. }
  14091. }
  14092. static int
  14093. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14094. {
  14095. #if defined(GCC_DIAGNOSTIC)
  14096. #pragma GCC diagnostic push
  14097. #pragma GCC diagnostic ignored "-Wcast-align"
  14098. #endif /* defined(GCC_DIAGNOSTIC) */
  14099. /* We used an aligned pointer in SSL_set_app_data */
  14100. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14101. #if defined(GCC_DIAGNOSTIC)
  14102. #pragma GCC diagnostic pop
  14103. #endif /* defined(GCC_DIAGNOSTIC) */
  14104. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14105. (void)ad;
  14106. (void)arg;
  14107. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14108. DEBUG_ASSERT(0);
  14109. return SSL_TLSEXT_ERR_NOACK;
  14110. }
  14111. conn->dom_ctx = &(conn->phys_ctx->dd);
  14112. /* Old clients (Win XP) will not support SNI. Then, there
  14113. * is no server name available in the request - we can
  14114. * only work with the default certificate.
  14115. * Multiple HTTPS hosts on one IP+port are only possible
  14116. * with a certificate containing all alternative names.
  14117. */
  14118. if ((servername == NULL) || (*servername == 0)) {
  14119. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14120. mg_lock_context(conn->phys_ctx);
  14121. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14122. mg_unlock_context(conn->phys_ctx);
  14123. return SSL_TLSEXT_ERR_NOACK;
  14124. }
  14125. DEBUG_TRACE("TLS connection to host %s", servername);
  14126. while (conn->dom_ctx) {
  14127. if (!mg_strcasecmp(servername,
  14128. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14129. /* Found matching domain */
  14130. DEBUG_TRACE("TLS domain %s found",
  14131. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14132. break;
  14133. }
  14134. mg_lock_context(conn->phys_ctx);
  14135. conn->dom_ctx = conn->dom_ctx->next;
  14136. mg_unlock_context(conn->phys_ctx);
  14137. }
  14138. if (conn->dom_ctx == NULL) {
  14139. /* Default domain */
  14140. DEBUG_TRACE("TLS default domain %s used",
  14141. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14142. conn->dom_ctx = &(conn->phys_ctx->dd);
  14143. }
  14144. mg_lock_context(conn->phys_ctx);
  14145. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14146. mg_unlock_context(conn->phys_ctx);
  14147. return SSL_TLSEXT_ERR_OK;
  14148. }
  14149. #if defined(USE_ALPN)
  14150. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14151. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14152. alpn_proto_list + 3 + 8,
  14153. NULL};
  14154. #if defined(USE_HTTP2)
  14155. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14156. alpn_proto_list + 3,
  14157. alpn_proto_list + 3 + 8,
  14158. NULL};
  14159. #endif
  14160. static int
  14161. alpn_select_cb(SSL *ssl,
  14162. const unsigned char **out,
  14163. unsigned char *outlen,
  14164. const unsigned char *in,
  14165. unsigned int inlen,
  14166. void *arg)
  14167. {
  14168. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14169. unsigned int i, j, enable_http2 = 0;
  14170. const char **alpn_proto_order = alpn_proto_order_http1;
  14171. struct mg_workerTLS *tls =
  14172. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14173. (void)ssl;
  14174. if (tls == NULL) {
  14175. /* Need to store protocol in Thread Local Storage */
  14176. /* If there is no Thread Local Storage, don't use ALPN */
  14177. return SSL_TLSEXT_ERR_NOACK;
  14178. }
  14179. #if defined(USE_HTTP2)
  14180. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14181. if (enable_http2) {
  14182. alpn_proto_order = alpn_proto_order_http2;
  14183. }
  14184. #endif
  14185. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14186. /* check all accepted protocols in this order */
  14187. const char *alpn_proto = alpn_proto_order[j];
  14188. /* search input for matching protocol */
  14189. for (i = 0; i < inlen; i++) {
  14190. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14191. *out = in + i + 1;
  14192. *outlen = in[i];
  14193. tls->alpn_proto = alpn_proto;
  14194. return SSL_TLSEXT_ERR_OK;
  14195. }
  14196. }
  14197. }
  14198. /* Nothing found */
  14199. return SSL_TLSEXT_ERR_NOACK;
  14200. }
  14201. static int
  14202. next_protos_advertised_cb(SSL *ssl,
  14203. const unsigned char **data,
  14204. unsigned int *len,
  14205. void *arg)
  14206. {
  14207. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14208. *data = (const unsigned char *)alpn_proto_list;
  14209. *len = (unsigned int)strlen((const char *)data);
  14210. (void)ssl;
  14211. (void)dom_ctx;
  14212. return SSL_TLSEXT_ERR_OK;
  14213. }
  14214. static int
  14215. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14216. {
  14217. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14218. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14219. (const unsigned char *)alpn_proto_list,
  14220. alpn_len);
  14221. if (ret != 0) {
  14222. mg_cry_ctx_internal(phys_ctx,
  14223. "SSL_CTX_set_alpn_protos error: %s",
  14224. ssl_error());
  14225. }
  14226. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14227. alpn_select_cb,
  14228. (void *)dom_ctx);
  14229. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14230. next_protos_advertised_cb,
  14231. (void *)dom_ctx);
  14232. return ret;
  14233. }
  14234. #endif
  14235. /* Setup SSL CTX as required by CivetWeb */
  14236. static int
  14237. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14238. struct mg_domain_context *dom_ctx,
  14239. const char *pem,
  14240. const char *chain)
  14241. {
  14242. int callback_ret;
  14243. int should_verify_peer;
  14244. int peer_certificate_optional;
  14245. const char *ca_path;
  14246. const char *ca_file;
  14247. int use_default_verify_paths;
  14248. int verify_depth;
  14249. struct timespec now_mt;
  14250. md5_byte_t ssl_context_id[16];
  14251. md5_state_t md5state;
  14252. int protocol_ver;
  14253. int ssl_cache_timeout;
  14254. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14255. && !defined(NO_SSL_DL)
  14256. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14257. mg_cry_ctx_internal(phys_ctx,
  14258. "SSL_CTX_new (server) error: %s",
  14259. ssl_error());
  14260. return 0;
  14261. }
  14262. #else
  14263. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14264. mg_cry_ctx_internal(phys_ctx,
  14265. "SSL_CTX_new (server) error: %s",
  14266. ssl_error());
  14267. return 0;
  14268. }
  14269. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14270. #if defined(SSL_OP_NO_TLSv1_3)
  14271. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14272. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14273. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14274. | SSL_OP_NO_TLSv1_3);
  14275. #else
  14276. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14277. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14278. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14279. #endif
  14280. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14281. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14282. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14283. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14284. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14285. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14286. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14287. #if defined(SSL_OP_NO_RENEGOTIATION)
  14288. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14289. #endif
  14290. #if !defined(NO_SSL_DL)
  14291. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14292. #endif /* NO_SSL_DL */
  14293. /* In SSL documentation examples callback defined without const
  14294. * specifier 'void (*)(SSL *, int, int)' See:
  14295. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14296. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14297. * But in the source code const SSL is used:
  14298. * 'void (*)(const SSL *, int, int)' See:
  14299. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14300. * Problem about wrong documentation described, but not resolved:
  14301. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14302. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14303. * But when compiled with modern C++ compiler, correct const should be
  14304. * provided
  14305. */
  14306. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14307. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14308. ssl_servername_callback);
  14309. /* If a callback has been specified, call it. */
  14310. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14311. ? 0
  14312. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14313. phys_ctx->user_data));
  14314. /* If callback returns 0, civetweb sets up the SSL certificate.
  14315. * If it returns 1, civetweb assumes the calback already did this.
  14316. * If it returns -1, initializing ssl fails. */
  14317. if (callback_ret < 0) {
  14318. mg_cry_ctx_internal(phys_ctx,
  14319. "SSL callback returned error: %i",
  14320. callback_ret);
  14321. return 0;
  14322. }
  14323. if (callback_ret > 0) {
  14324. /* Callback did everything. */
  14325. return 1;
  14326. }
  14327. /* If a domain callback has been specified, call it. */
  14328. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14329. ? 0
  14330. : (phys_ctx->callbacks.init_ssl_domain(
  14331. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14332. dom_ctx->ssl_ctx,
  14333. phys_ctx->user_data));
  14334. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14335. * If it returns 1, civetweb assumes the calback already did this.
  14336. * If it returns -1, initializing ssl fails. */
  14337. if (callback_ret < 0) {
  14338. mg_cry_ctx_internal(phys_ctx,
  14339. "Domain SSL callback returned error: %i",
  14340. callback_ret);
  14341. return 0;
  14342. }
  14343. if (callback_ret > 0) {
  14344. /* Domain callback did everything. */
  14345. return 1;
  14346. }
  14347. /* Use some combination of start time, domain and port as a SSL
  14348. * context ID. This should be unique on the current machine. */
  14349. md5_init(&md5state);
  14350. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14351. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14352. md5_append(&md5state,
  14353. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14354. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14355. md5_append(&md5state,
  14356. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14357. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14358. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14359. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14360. md5_finish(&md5state, ssl_context_id);
  14361. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14362. (unsigned char *)ssl_context_id,
  14363. sizeof(ssl_context_id));
  14364. if (pem != NULL) {
  14365. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14366. return 0;
  14367. }
  14368. }
  14369. /* Should we support client certificates? */
  14370. /* Default is "no". */
  14371. should_verify_peer = 0;
  14372. peer_certificate_optional = 0;
  14373. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14374. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14375. /* Yes, they are mandatory */
  14376. should_verify_peer = 1;
  14377. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14378. "optional")
  14379. == 0) {
  14380. /* Yes, they are optional */
  14381. should_verify_peer = 1;
  14382. peer_certificate_optional = 1;
  14383. }
  14384. }
  14385. use_default_verify_paths =
  14386. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14387. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14388. == 0);
  14389. if (should_verify_peer) {
  14390. ca_path = dom_ctx->config[SSL_CA_PATH];
  14391. ca_file = dom_ctx->config[SSL_CA_FILE];
  14392. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14393. != 1) {
  14394. mg_cry_ctx_internal(phys_ctx,
  14395. "SSL_CTX_load_verify_locations error: %s "
  14396. "ssl_verify_peer requires setting "
  14397. "either ssl_ca_path or ssl_ca_file. "
  14398. "Is any of them present in the "
  14399. ".conf file?",
  14400. ssl_error());
  14401. return 0;
  14402. }
  14403. if (peer_certificate_optional) {
  14404. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14405. } else {
  14406. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14407. SSL_VERIFY_PEER
  14408. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14409. NULL);
  14410. }
  14411. if (use_default_verify_paths
  14412. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14413. mg_cry_ctx_internal(phys_ctx,
  14414. "SSL_CTX_set_default_verify_paths error: %s",
  14415. ssl_error());
  14416. return 0;
  14417. }
  14418. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14419. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14420. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14421. }
  14422. }
  14423. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14424. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14425. dom_ctx->config[SSL_CIPHER_LIST])
  14426. != 1) {
  14427. mg_cry_ctx_internal(phys_ctx,
  14428. "SSL_CTX_set_cipher_list error: %s",
  14429. ssl_error());
  14430. }
  14431. }
  14432. /* SSL session caching */
  14433. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14434. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14435. : 0);
  14436. if (ssl_cache_timeout > 0) {
  14437. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14438. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14439. * default */
  14440. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14441. }
  14442. #if defined(USE_ALPN)
  14443. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14444. #if !defined(NO_SSL_DL)
  14445. if (!tls_feature_missing[TLS_ALPN])
  14446. #endif
  14447. {
  14448. init_alpn(phys_ctx, dom_ctx);
  14449. }
  14450. #endif
  14451. return 1;
  14452. }
  14453. /* Check if SSL is required.
  14454. * If so, dynamically load SSL library
  14455. * and set up ctx->ssl_ctx pointer. */
  14456. static int
  14457. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14458. {
  14459. void *ssl_ctx = 0;
  14460. int callback_ret;
  14461. const char *pem;
  14462. const char *chain;
  14463. char ebuf[128];
  14464. if (!phys_ctx) {
  14465. return 0;
  14466. }
  14467. if (!dom_ctx) {
  14468. dom_ctx = &(phys_ctx->dd);
  14469. }
  14470. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14471. /* No SSL port is set. No need to setup SSL. */
  14472. return 1;
  14473. }
  14474. /* Check for external SSL_CTX */
  14475. callback_ret =
  14476. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14477. ? 0
  14478. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14479. phys_ctx->user_data));
  14480. if (callback_ret < 0) {
  14481. /* Callback exists and returns <0: Initializing failed. */
  14482. mg_cry_ctx_internal(phys_ctx,
  14483. "external_ssl_ctx callback returned error: %i",
  14484. callback_ret);
  14485. return 0;
  14486. } else if (callback_ret > 0) {
  14487. /* Callback exists and returns >0: Initializing complete,
  14488. * civetweb should not modify the SSL context. */
  14489. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14490. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14491. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14492. return 0;
  14493. }
  14494. return 1;
  14495. }
  14496. /* If the callback does not exist or return 0, civetweb must initialize
  14497. * the SSL context. Handle "domain" callback next. */
  14498. /* Check for external domain SSL_CTX callback. */
  14499. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14500. ? 0
  14501. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14502. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14503. &ssl_ctx,
  14504. phys_ctx->user_data));
  14505. if (callback_ret < 0) {
  14506. /* Callback < 0: Error. Abort init. */
  14507. mg_cry_ctx_internal(
  14508. phys_ctx,
  14509. "external_ssl_ctx_domain callback returned error: %i",
  14510. callback_ret);
  14511. return 0;
  14512. } else if (callback_ret > 0) {
  14513. /* Callback > 0: Consider init done. */
  14514. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14515. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14516. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14517. return 0;
  14518. }
  14519. return 1;
  14520. }
  14521. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14522. * 0, CivetWeb should continue initializing SSL */
  14523. /* If PEM file is not specified and the init_ssl callbacks
  14524. * are not specified, setup will fail. */
  14525. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14526. && (phys_ctx->callbacks.init_ssl == NULL)
  14527. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14528. /* No certificate and no init_ssl callbacks:
  14529. * Essential data to set up TLS is missing.
  14530. */
  14531. mg_cry_ctx_internal(phys_ctx,
  14532. "Initializing SSL failed: -%s is not set",
  14533. config_options[SSL_CERTIFICATE].name);
  14534. return 0;
  14535. }
  14536. /* If a certificate chain is configured, use it. */
  14537. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14538. if (chain == NULL) {
  14539. /* Default: certificate chain in PEM file */
  14540. chain = pem;
  14541. }
  14542. if ((chain != NULL) && (*chain == 0)) {
  14543. /* If the chain is an empty string, don't use it. */
  14544. chain = NULL;
  14545. }
  14546. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14547. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14548. return 0;
  14549. }
  14550. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14551. }
  14552. static void
  14553. uninitialize_openssl(void)
  14554. {
  14555. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14556. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14557. /* Shutdown according to
  14558. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14559. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14560. */
  14561. CONF_modules_unload(1);
  14562. #else
  14563. int i;
  14564. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14565. /* Shutdown according to
  14566. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14567. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14568. */
  14569. CRYPTO_set_locking_callback(NULL);
  14570. CRYPTO_set_id_callback(NULL);
  14571. ENGINE_cleanup();
  14572. CONF_modules_unload(1);
  14573. ERR_free_strings();
  14574. EVP_cleanup();
  14575. CRYPTO_cleanup_all_ex_data();
  14576. OPENSSL_REMOVE_THREAD_STATE();
  14577. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14578. pthread_mutex_destroy(&ssl_mutexes[i]);
  14579. }
  14580. mg_free(ssl_mutexes);
  14581. ssl_mutexes = NULL;
  14582. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14583. }
  14584. }
  14585. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  14586. #if !defined(NO_FILESYSTEMS)
  14587. static int
  14588. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14589. {
  14590. if (phys_ctx) {
  14591. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14592. const char *path;
  14593. struct mg_connection fc;
  14594. if (!dom_ctx) {
  14595. dom_ctx = &(phys_ctx->dd);
  14596. }
  14597. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14598. if ((path != NULL)
  14599. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14600. mg_cry_ctx_internal(phys_ctx,
  14601. "Cannot open %s: %s",
  14602. path,
  14603. strerror(ERRNO));
  14604. return 0;
  14605. }
  14606. return 1;
  14607. }
  14608. return 0;
  14609. }
  14610. #endif /* NO_FILESYSTEMS */
  14611. static int
  14612. set_acl_option(struct mg_context *phys_ctx)
  14613. {
  14614. union usa sa;
  14615. memset(&sa, 0, sizeof(sa));
  14616. #if defined(USE_IPV6)
  14617. sa.sin6.sin6_family = AF_INET6;
  14618. #else
  14619. sa.sin.sin_family = AF_INET;
  14620. #endif
  14621. return check_acl(phys_ctx, &sa) != -1;
  14622. }
  14623. static void
  14624. reset_per_request_attributes(struct mg_connection *conn)
  14625. {
  14626. if (!conn) {
  14627. return;
  14628. }
  14629. conn->num_bytes_sent = conn->consumed_content = 0;
  14630. conn->path_info = NULL;
  14631. conn->status_code = -1;
  14632. conn->content_len = -1;
  14633. conn->is_chunked = 0;
  14634. conn->must_close = 0;
  14635. conn->request_len = 0;
  14636. conn->request_state = 0;
  14637. conn->throttle = 0;
  14638. conn->accept_gzip = 0;
  14639. conn->response_info.content_length = conn->request_info.content_length = -1;
  14640. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14641. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14642. conn->response_info.status_text = NULL;
  14643. conn->response_info.status_code = 0;
  14644. conn->request_info.remote_user = NULL;
  14645. conn->request_info.request_method = NULL;
  14646. conn->request_info.request_uri = NULL;
  14647. /* Free cleaned local URI (if any) */
  14648. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  14649. mg_free((void *)conn->request_info.local_uri);
  14650. conn->request_info.local_uri = NULL;
  14651. }
  14652. conn->request_info.local_uri = NULL;
  14653. #if defined(USE_SERVER_STATS)
  14654. conn->processing_time = 0;
  14655. #endif
  14656. }
  14657. static int
  14658. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14659. {
  14660. if ((so->lsa.sa.sa_family == AF_INET)
  14661. || (so->lsa.sa.sa_family == AF_INET6)) {
  14662. /* Only for TCP sockets */
  14663. if (setsockopt(so->sock,
  14664. IPPROTO_TCP,
  14665. TCP_NODELAY,
  14666. (SOCK_OPT_TYPE)&nodelay_on,
  14667. sizeof(nodelay_on))
  14668. != 0) {
  14669. /* Error */
  14670. return 1;
  14671. }
  14672. }
  14673. /* OK */
  14674. return 0;
  14675. }
  14676. #if !defined(__ZEPHYR__)
  14677. static void
  14678. close_socket_gracefully(struct mg_connection *conn)
  14679. {
  14680. #if defined(_WIN32)
  14681. char buf[MG_BUF_LEN];
  14682. int n;
  14683. #endif
  14684. struct linger linger;
  14685. int error_code = 0;
  14686. int linger_timeout = -2;
  14687. socklen_t opt_len = sizeof(error_code);
  14688. if (!conn) {
  14689. return;
  14690. }
  14691. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14692. * "Note that enabling a nonzero timeout on a nonblocking socket
  14693. * is not recommended.", so set it to blocking now */
  14694. set_blocking_mode(conn->client.sock);
  14695. /* Send FIN to the client */
  14696. shutdown(conn->client.sock, SHUTDOWN_WR);
  14697. #if defined(_WIN32)
  14698. /* Read and discard pending incoming data. If we do not do that and
  14699. * close
  14700. * the socket, the data in the send buffer may be discarded. This
  14701. * behaviour is seen on Windows, when client keeps sending data
  14702. * when server decides to close the connection; then when client
  14703. * does recv() it gets no data back. */
  14704. do {
  14705. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14706. } while (n > 0);
  14707. #endif
  14708. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14709. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14710. }
  14711. /* Set linger option according to configuration */
  14712. if (linger_timeout >= 0) {
  14713. /* Set linger option to avoid socket hanging out after close. This
  14714. * prevent ephemeral port exhaust problem under high QPS. */
  14715. linger.l_onoff = 1;
  14716. #if defined(_MSC_VER)
  14717. #pragma warning(push)
  14718. #pragma warning(disable : 4244)
  14719. #endif
  14720. #if defined(GCC_DIAGNOSTIC)
  14721. #pragma GCC diagnostic push
  14722. #pragma GCC diagnostic ignored "-Wconversion"
  14723. #endif
  14724. /* Data type of linger structure elements may differ,
  14725. * so we don't know what cast we need here.
  14726. * Disable type conversion warnings. */
  14727. linger.l_linger = (linger_timeout + 999) / 1000;
  14728. #if defined(GCC_DIAGNOSTIC)
  14729. #pragma GCC diagnostic pop
  14730. #endif
  14731. #if defined(_MSC_VER)
  14732. #pragma warning(pop)
  14733. #endif
  14734. } else {
  14735. linger.l_onoff = 0;
  14736. linger.l_linger = 0;
  14737. }
  14738. if (linger_timeout < -1) {
  14739. /* Default: don't configure any linger */
  14740. } else if (getsockopt(conn->client.sock,
  14741. SOL_SOCKET,
  14742. SO_ERROR,
  14743. #if defined(_WIN32) /* WinSock uses different data type here */
  14744. (char *)&error_code,
  14745. #else
  14746. &error_code,
  14747. #endif
  14748. &opt_len)
  14749. != 0) {
  14750. /* Cannot determine if socket is already closed. This should
  14751. * not occur and never did in a test. Log an error message
  14752. * and continue. */
  14753. mg_cry_internal(conn,
  14754. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14755. __func__,
  14756. strerror(ERRNO));
  14757. #if defined(_WIN32)
  14758. } else if (error_code == WSAECONNRESET) {
  14759. #else
  14760. } else if (error_code == ECONNRESET) {
  14761. #endif
  14762. /* Socket already closed by client/peer, close socket without linger
  14763. */
  14764. } else {
  14765. /* Set linger timeout */
  14766. if (setsockopt(conn->client.sock,
  14767. SOL_SOCKET,
  14768. SO_LINGER,
  14769. (char *)&linger,
  14770. sizeof(linger))
  14771. != 0) {
  14772. mg_cry_internal(
  14773. conn,
  14774. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14775. __func__,
  14776. linger.l_onoff,
  14777. linger.l_linger,
  14778. strerror(ERRNO));
  14779. }
  14780. }
  14781. /* Now we know that our FIN is ACK-ed, safe to close */
  14782. closesocket(conn->client.sock);
  14783. conn->client.sock = INVALID_SOCKET;
  14784. }
  14785. #endif
  14786. static void
  14787. close_connection(struct mg_connection *conn)
  14788. {
  14789. #if defined(USE_SERVER_STATS)
  14790. conn->conn_state = 6; /* to close */
  14791. #endif
  14792. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14793. if (conn->lua_websocket_state) {
  14794. lua_websocket_close(conn, conn->lua_websocket_state);
  14795. conn->lua_websocket_state = NULL;
  14796. }
  14797. #endif
  14798. mg_lock_connection(conn);
  14799. /* Set close flag, so keep-alive loops will stop */
  14800. conn->must_close = 1;
  14801. /* call the connection_close callback if assigned */
  14802. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14803. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14804. conn->phys_ctx->callbacks.connection_close(conn);
  14805. }
  14806. }
  14807. /* Reset user data, after close callback is called.
  14808. * Do not reuse it. If the user needs a destructor,
  14809. * it must be done in the connection_close callback. */
  14810. mg_set_user_connection_data(conn, NULL);
  14811. #if defined(USE_SERVER_STATS)
  14812. conn->conn_state = 7; /* closing */
  14813. #endif
  14814. #if defined(USE_MBEDTLS)
  14815. if (conn->ssl != NULL) {
  14816. mbed_ssl_close(conn->ssl);
  14817. conn->ssl = NULL;
  14818. }
  14819. #elif !defined(NO_SSL)
  14820. if (conn->ssl != NULL) {
  14821. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14822. */
  14823. SSL_shutdown(conn->ssl);
  14824. SSL_free(conn->ssl);
  14825. OPENSSL_REMOVE_THREAD_STATE();
  14826. conn->ssl = NULL;
  14827. }
  14828. #endif
  14829. if (conn->client.sock != INVALID_SOCKET) {
  14830. #if defined(__ZEPHYR__)
  14831. closesocket(conn->client.sock);
  14832. #else
  14833. close_socket_gracefully(conn);
  14834. #endif
  14835. conn->client.sock = INVALID_SOCKET;
  14836. }
  14837. /* call the connection_closed callback if assigned */
  14838. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  14839. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14840. conn->phys_ctx->callbacks.connection_closed(conn);
  14841. }
  14842. }
  14843. mg_unlock_connection(conn);
  14844. #if defined(USE_SERVER_STATS)
  14845. conn->conn_state = 8; /* closed */
  14846. #endif
  14847. }
  14848. void
  14849. mg_close_connection(struct mg_connection *conn)
  14850. {
  14851. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14852. return;
  14853. }
  14854. #if defined(USE_WEBSOCKET)
  14855. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14856. if (conn->in_websocket_handling) {
  14857. /* Set close flag, so the server thread can exit. */
  14858. conn->must_close = 1;
  14859. return;
  14860. }
  14861. }
  14862. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14863. unsigned int i;
  14864. /* client context: loops must end */
  14865. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14866. conn->must_close = 1;
  14867. /* We need to get the client thread out of the select/recv call
  14868. * here. */
  14869. /* Since we use a sleep quantum of some seconds to check for recv
  14870. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14871. /* join worker thread */
  14872. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14873. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14874. }
  14875. }
  14876. #endif /* defined(USE_WEBSOCKET) */
  14877. close_connection(conn);
  14878. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14879. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14880. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14881. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14882. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14883. }
  14884. #endif
  14885. #if defined(USE_WEBSOCKET)
  14886. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14887. mg_free(conn->phys_ctx->worker_threadids);
  14888. (void)pthread_mutex_destroy(&conn->mutex);
  14889. mg_free(conn);
  14890. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14891. (void)pthread_mutex_destroy(&conn->mutex);
  14892. mg_free(conn);
  14893. }
  14894. #else
  14895. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14896. (void)pthread_mutex_destroy(&conn->mutex);
  14897. mg_free(conn);
  14898. }
  14899. #endif /* defined(USE_WEBSOCKET) */
  14900. }
  14901. static struct mg_connection *
  14902. mg_connect_client_impl(const struct mg_client_options *client_options,
  14903. int use_ssl,
  14904. char *ebuf,
  14905. size_t ebuf_len)
  14906. {
  14907. struct mg_connection *conn = NULL;
  14908. SOCKET sock;
  14909. union usa sa;
  14910. struct sockaddr *psa;
  14911. socklen_t len;
  14912. unsigned max_req_size =
  14913. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14914. /* Size of structures, aligned to 8 bytes */
  14915. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14916. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14917. conn =
  14918. (struct mg_connection *)mg_calloc(1,
  14919. conn_size + ctx_size + max_req_size);
  14920. if (conn == NULL) {
  14921. mg_snprintf(NULL,
  14922. NULL, /* No truncation check for ebuf */
  14923. ebuf,
  14924. ebuf_len,
  14925. "calloc(): %s",
  14926. strerror(ERRNO));
  14927. return NULL;
  14928. }
  14929. #if defined(GCC_DIAGNOSTIC)
  14930. #pragma GCC diagnostic push
  14931. #pragma GCC diagnostic ignored "-Wcast-align"
  14932. #endif /* defined(GCC_DIAGNOSTIC) */
  14933. /* conn_size is aligned to 8 bytes */
  14934. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14935. #if defined(GCC_DIAGNOSTIC)
  14936. #pragma GCC diagnostic pop
  14937. #endif /* defined(GCC_DIAGNOSTIC) */
  14938. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14939. conn->buf_size = (int)max_req_size;
  14940. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14941. conn->dom_ctx = &(conn->phys_ctx->dd);
  14942. if (!connect_socket(conn->phys_ctx,
  14943. client_options->host,
  14944. client_options->port,
  14945. use_ssl,
  14946. ebuf,
  14947. ebuf_len,
  14948. &sock,
  14949. &sa)) {
  14950. /* ebuf is set by connect_socket,
  14951. * free all memory and return NULL; */
  14952. mg_free(conn);
  14953. return NULL;
  14954. }
  14955. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14956. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14957. && !defined(NO_SSL_DL)
  14958. if (use_ssl
  14959. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14960. == NULL) {
  14961. mg_snprintf(NULL,
  14962. NULL, /* No truncation check for ebuf */
  14963. ebuf,
  14964. ebuf_len,
  14965. "SSL_CTX_new error: %s",
  14966. ssl_error());
  14967. closesocket(sock);
  14968. mg_free(conn);
  14969. return NULL;
  14970. }
  14971. #else
  14972. if (use_ssl
  14973. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14974. == NULL) {
  14975. mg_snprintf(NULL,
  14976. NULL, /* No truncation check for ebuf */
  14977. ebuf,
  14978. ebuf_len,
  14979. "SSL_CTX_new error: %s",
  14980. ssl_error());
  14981. closesocket(sock);
  14982. mg_free(conn);
  14983. return NULL;
  14984. }
  14985. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14986. #endif /* NO_SSL */
  14987. #if defined(USE_IPV6)
  14988. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14989. : sizeof(conn->client.rsa.sin6);
  14990. psa = (sa.sa.sa_family == AF_INET)
  14991. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14992. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14993. #else
  14994. len = sizeof(conn->client.rsa.sin);
  14995. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14996. #endif
  14997. conn->client.sock = sock;
  14998. conn->client.lsa = sa;
  14999. if (getsockname(sock, psa, &len) != 0) {
  15000. mg_cry_internal(conn,
  15001. "%s: getsockname() failed: %s",
  15002. __func__,
  15003. strerror(ERRNO));
  15004. }
  15005. conn->client.is_ssl = use_ssl ? 1 : 0;
  15006. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15007. mg_snprintf(NULL,
  15008. NULL, /* No truncation check for ebuf */
  15009. ebuf,
  15010. ebuf_len,
  15011. "Can not create mutex");
  15012. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15013. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15014. #endif
  15015. closesocket(sock);
  15016. mg_free(conn);
  15017. return NULL;
  15018. }
  15019. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15020. if (use_ssl) {
  15021. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15022. * SSL_CTX_set_verify call is needed to switch off server
  15023. * certificate checking, which is off by default in OpenSSL and
  15024. * on in yaSSL. */
  15025. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15026. * SSL_VERIFY_PEER, verify_ssl_server); */
  15027. if (client_options->client_cert) {
  15028. if (!ssl_use_pem_file(conn->phys_ctx,
  15029. conn->dom_ctx,
  15030. client_options->client_cert,
  15031. NULL)) {
  15032. mg_snprintf(NULL,
  15033. NULL, /* No truncation check for ebuf */
  15034. ebuf,
  15035. ebuf_len,
  15036. "Can not use SSL client certificate");
  15037. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15038. closesocket(sock);
  15039. mg_free(conn);
  15040. return NULL;
  15041. }
  15042. }
  15043. if (client_options->server_cert) {
  15044. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15045. client_options->server_cert,
  15046. NULL)
  15047. != 1) {
  15048. mg_cry_internal(conn,
  15049. "SSL_CTX_load_verify_locations error: %s ",
  15050. ssl_error());
  15051. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15052. closesocket(sock);
  15053. mg_free(conn);
  15054. return NULL;
  15055. }
  15056. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15057. } else {
  15058. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15059. }
  15060. if (!sslize(conn, SSL_connect, client_options)) {
  15061. mg_snprintf(NULL,
  15062. NULL, /* No truncation check for ebuf */
  15063. ebuf,
  15064. ebuf_len,
  15065. "SSL connection error");
  15066. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15067. closesocket(sock);
  15068. mg_free(conn);
  15069. return NULL;
  15070. }
  15071. }
  15072. #endif
  15073. return conn;
  15074. }
  15075. CIVETWEB_API struct mg_connection *
  15076. mg_connect_client_secure(const struct mg_client_options *client_options,
  15077. char *error_buffer,
  15078. size_t error_buffer_size)
  15079. {
  15080. return mg_connect_client_impl(client_options,
  15081. 1,
  15082. error_buffer,
  15083. error_buffer_size);
  15084. }
  15085. struct mg_connection *
  15086. mg_connect_client(const char *host,
  15087. int port,
  15088. int use_ssl,
  15089. char *error_buffer,
  15090. size_t error_buffer_size)
  15091. {
  15092. struct mg_client_options opts;
  15093. memset(&opts, 0, sizeof(opts));
  15094. opts.host = host;
  15095. opts.port = port;
  15096. return mg_connect_client_impl(&opts,
  15097. use_ssl,
  15098. error_buffer,
  15099. error_buffer_size);
  15100. }
  15101. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15102. struct mg_connection *
  15103. mg_connect_client2(const char *host,
  15104. const char *protocol,
  15105. int port,
  15106. const char *path,
  15107. struct mg_init_data *init,
  15108. struct mg_error_data *error)
  15109. {
  15110. (void)path;
  15111. (void)init;
  15112. int is_ssl, is_ws;
  15113. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15114. if (error != NULL) {
  15115. error->code = 0;
  15116. if (error->text_buffer_size > 0) {
  15117. *error->text = 0;
  15118. }
  15119. }
  15120. if ((host == NULL) || (protocol == NULL)) {
  15121. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15122. mg_snprintf(NULL,
  15123. NULL, /* No truncation check for error buffers */
  15124. error->text,
  15125. error->text_buffer_size,
  15126. "%s",
  15127. "Invalid parameters");
  15128. }
  15129. return NULL;
  15130. }
  15131. /* check all known protocolls */
  15132. if (!mg_strcasecmp(protocol, "http")) {
  15133. is_ssl = 0;
  15134. is_ws = 0;
  15135. } else if (!mg_strcasecmp(protocol, "https")) {
  15136. is_ssl = 1;
  15137. is_ws = 0;
  15138. #if defined(USE_WEBSOCKET)
  15139. } else if (!mg_strcasecmp(protocol, "ws")) {
  15140. is_ssl = 0;
  15141. is_ws = 1;
  15142. } else if (!mg_strcasecmp(protocol, "wss")) {
  15143. is_ssl = 1;
  15144. is_ws = 1;
  15145. #endif
  15146. } else {
  15147. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15148. mg_snprintf(NULL,
  15149. NULL, /* No truncation check for error buffers */
  15150. error->text,
  15151. error->text_buffer_size,
  15152. "Protocol %s not supported",
  15153. protocol);
  15154. }
  15155. return NULL;
  15156. }
  15157. /* TODO: The current implementation here just calls the old
  15158. * implementations, without using any new options. This is just a first
  15159. * step to test the new interfaces. */
  15160. #if defined(USE_WEBSOCKET)
  15161. if (is_ws) {
  15162. /* TODO: implement all options */
  15163. return mg_connect_websocket_client(
  15164. host,
  15165. port,
  15166. is_ssl,
  15167. ((error != NULL) ? error->text : NULL),
  15168. ((error != NULL) ? error->text_buffer_size : 0),
  15169. (path ? path : ""),
  15170. NULL /* TODO: origin */,
  15171. experimental_websocket_client_data_wrapper,
  15172. experimental_websocket_client_close_wrapper,
  15173. (void *)init->callbacks);
  15174. }
  15175. #else
  15176. (void)is_ws;
  15177. #endif
  15178. /* TODO: all additional options */
  15179. struct mg_client_options opts;
  15180. memset(&opts, 0, sizeof(opts));
  15181. opts.host = host;
  15182. opts.port = port;
  15183. return mg_connect_client_impl(&opts,
  15184. is_ssl,
  15185. ((error != NULL) ? error->text : NULL),
  15186. ((error != NULL) ? error->text_buffer_size
  15187. : 0));
  15188. }
  15189. #endif
  15190. static const struct {
  15191. const char *proto;
  15192. size_t proto_len;
  15193. unsigned default_port;
  15194. } abs_uri_protocols[] = {{"http://", 7, 80},
  15195. {"https://", 8, 443},
  15196. {"ws://", 5, 80},
  15197. {"wss://", 6, 443},
  15198. {NULL, 0, 0}};
  15199. /* Check if the uri is valid.
  15200. * return 0 for invalid uri,
  15201. * return 1 for *,
  15202. * return 2 for relative uri,
  15203. * return 3 for absolute uri without port,
  15204. * return 4 for absolute uri with port */
  15205. static int
  15206. get_uri_type(const char *uri)
  15207. {
  15208. int i;
  15209. const char *hostend, *portbegin;
  15210. char *portend;
  15211. unsigned long port;
  15212. /* According to the HTTP standard
  15213. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15214. * URI can be an asterisk (*) or should start with slash (relative uri),
  15215. * or it should start with the protocol (absolute uri). */
  15216. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15217. /* asterisk */
  15218. return 1;
  15219. }
  15220. /* Valid URIs according to RFC 3986
  15221. * (https://www.ietf.org/rfc/rfc3986.txt)
  15222. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15223. * and unreserved characters A-Z a-z 0-9 and -._~
  15224. * and % encoded symbols.
  15225. */
  15226. for (i = 0; uri[i] != 0; i++) {
  15227. if (uri[i] < 33) {
  15228. /* control characters and spaces are invalid */
  15229. return 0;
  15230. }
  15231. /* Allow everything else here (See #894) */
  15232. }
  15233. /* A relative uri starts with a / character */
  15234. if (uri[0] == '/') {
  15235. /* relative uri */
  15236. return 2;
  15237. }
  15238. /* It could be an absolute uri: */
  15239. /* This function only checks if the uri is valid, not if it is
  15240. * addressing the current server. So civetweb can also be used
  15241. * as a proxy server. */
  15242. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15243. if (mg_strncasecmp(uri,
  15244. abs_uri_protocols[i].proto,
  15245. abs_uri_protocols[i].proto_len)
  15246. == 0) {
  15247. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15248. if (!hostend) {
  15249. return 0;
  15250. }
  15251. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15252. if (!portbegin) {
  15253. return 3;
  15254. }
  15255. port = strtoul(portbegin + 1, &portend, 10);
  15256. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15257. return 0;
  15258. }
  15259. return 4;
  15260. }
  15261. }
  15262. return 0;
  15263. }
  15264. /* Return NULL or the relative uri at the current server */
  15265. static const char *
  15266. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15267. {
  15268. const char *server_domain;
  15269. size_t server_domain_len;
  15270. size_t request_domain_len = 0;
  15271. unsigned long port = 0;
  15272. int i, auth_domain_check_enabled;
  15273. const char *hostbegin = NULL;
  15274. const char *hostend = NULL;
  15275. const char *portbegin;
  15276. char *portend;
  15277. auth_domain_check_enabled =
  15278. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15279. /* DNS is case insensitive, so use case insensitive string compare here
  15280. */
  15281. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15282. if (mg_strncasecmp(uri,
  15283. abs_uri_protocols[i].proto,
  15284. abs_uri_protocols[i].proto_len)
  15285. == 0) {
  15286. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15287. hostend = strchr(hostbegin, '/');
  15288. if (!hostend) {
  15289. return 0;
  15290. }
  15291. portbegin = strchr(hostbegin, ':');
  15292. if ((!portbegin) || (portbegin > hostend)) {
  15293. port = abs_uri_protocols[i].default_port;
  15294. request_domain_len = (size_t)(hostend - hostbegin);
  15295. } else {
  15296. port = strtoul(portbegin + 1, &portend, 10);
  15297. if ((portend != hostend) || (port <= 0)
  15298. || !is_valid_port(port)) {
  15299. return 0;
  15300. }
  15301. request_domain_len = (size_t)(portbegin - hostbegin);
  15302. }
  15303. /* protocol found, port set */
  15304. break;
  15305. }
  15306. }
  15307. if (!port) {
  15308. /* port remains 0 if the protocol is not found */
  15309. return 0;
  15310. }
  15311. /* Check if the request is directed to a different server. */
  15312. /* First check if the port is the same. */
  15313. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15314. /* Request is directed to a different port */
  15315. return 0;
  15316. }
  15317. /* Finally check if the server corresponds to the authentication
  15318. * domain of the server (the server domain).
  15319. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15320. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15321. * but do not allow substrings (like
  15322. * http://notmydomain.com/path/file.ext
  15323. * or http://mydomain.com.fake/path/file.ext).
  15324. */
  15325. if (auth_domain_check_enabled) {
  15326. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15327. server_domain_len = strlen(server_domain);
  15328. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15329. return 0;
  15330. }
  15331. if ((request_domain_len == server_domain_len)
  15332. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15333. /* Request is directed to this server - full name match. */
  15334. } else {
  15335. if (request_domain_len < (server_domain_len + 2)) {
  15336. /* Request is directed to another server: The server name
  15337. * is longer than the request name.
  15338. * Drop this case here to avoid overflows in the
  15339. * following checks. */
  15340. return 0;
  15341. }
  15342. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15343. /* Request is directed to another server: It could be a
  15344. * substring
  15345. * like notmyserver.com */
  15346. return 0;
  15347. }
  15348. if (0
  15349. != memcmp(server_domain,
  15350. hostbegin + request_domain_len - server_domain_len,
  15351. server_domain_len)) {
  15352. /* Request is directed to another server:
  15353. * The server name is different. */
  15354. return 0;
  15355. }
  15356. }
  15357. }
  15358. return hostend;
  15359. }
  15360. static int
  15361. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15362. {
  15363. if (ebuf_len > 0) {
  15364. ebuf[0] = '\0';
  15365. }
  15366. *err = 0;
  15367. reset_per_request_attributes(conn);
  15368. if (!conn) {
  15369. mg_snprintf(conn,
  15370. NULL, /* No truncation check for ebuf */
  15371. ebuf,
  15372. ebuf_len,
  15373. "%s",
  15374. "Internal error");
  15375. *err = 500;
  15376. return 0;
  15377. }
  15378. /* Set the time the request was received. This value should be used for
  15379. * timeouts. */
  15380. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15381. conn->request_len =
  15382. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15383. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15384. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15385. mg_snprintf(conn,
  15386. NULL, /* No truncation check for ebuf */
  15387. ebuf,
  15388. ebuf_len,
  15389. "%s",
  15390. "Invalid message size");
  15391. *err = 500;
  15392. return 0;
  15393. }
  15394. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15395. mg_snprintf(conn,
  15396. NULL, /* No truncation check for ebuf */
  15397. ebuf,
  15398. ebuf_len,
  15399. "%s",
  15400. "Message too large");
  15401. *err = 413;
  15402. return 0;
  15403. }
  15404. if (conn->request_len <= 0) {
  15405. if (conn->data_len > 0) {
  15406. mg_snprintf(conn,
  15407. NULL, /* No truncation check for ebuf */
  15408. ebuf,
  15409. ebuf_len,
  15410. "%s",
  15411. "Malformed message");
  15412. *err = 400;
  15413. } else {
  15414. /* Server did not recv anything -> just close the connection */
  15415. conn->must_close = 1;
  15416. mg_snprintf(conn,
  15417. NULL, /* No truncation check for ebuf */
  15418. ebuf,
  15419. ebuf_len,
  15420. "%s",
  15421. "No data received");
  15422. *err = 0;
  15423. }
  15424. return 0;
  15425. }
  15426. return 1;
  15427. }
  15428. static int
  15429. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15430. {
  15431. const char *cl;
  15432. conn->connection_type =
  15433. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15434. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15435. return 0;
  15436. }
  15437. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15438. <= 0) {
  15439. mg_snprintf(conn,
  15440. NULL, /* No truncation check for ebuf */
  15441. ebuf,
  15442. ebuf_len,
  15443. "%s",
  15444. "Bad request");
  15445. *err = 400;
  15446. return 0;
  15447. }
  15448. /* Message is a valid request */
  15449. if (!switch_domain_context(conn)) {
  15450. mg_snprintf(conn,
  15451. NULL, /* No truncation check for ebuf */
  15452. ebuf,
  15453. ebuf_len,
  15454. "%s",
  15455. "Bad request: Host mismatch");
  15456. *err = 400;
  15457. return 0;
  15458. }
  15459. #if USE_ZLIB
  15460. if (((cl = get_header(conn->request_info.http_headers,
  15461. conn->request_info.num_headers,
  15462. "Accept-Encoding"))
  15463. != NULL)
  15464. && strstr(cl, "gzip")) {
  15465. conn->accept_gzip = 1;
  15466. }
  15467. #endif
  15468. if (((cl = get_header(conn->request_info.http_headers,
  15469. conn->request_info.num_headers,
  15470. "Transfer-Encoding"))
  15471. != NULL)
  15472. && mg_strcasecmp(cl, "identity")) {
  15473. if (mg_strcasecmp(cl, "chunked")) {
  15474. mg_snprintf(conn,
  15475. NULL, /* No truncation check for ebuf */
  15476. ebuf,
  15477. ebuf_len,
  15478. "%s",
  15479. "Bad request");
  15480. *err = 400;
  15481. return 0;
  15482. }
  15483. conn->is_chunked = 1;
  15484. conn->content_len = 0; /* not yet read */
  15485. } else if ((cl = get_header(conn->request_info.http_headers,
  15486. conn->request_info.num_headers,
  15487. "Content-Length"))
  15488. != NULL) {
  15489. /* Request has content length set */
  15490. char *endptr = NULL;
  15491. conn->content_len = strtoll(cl, &endptr, 10);
  15492. if ((endptr == cl) || (conn->content_len < 0)) {
  15493. mg_snprintf(conn,
  15494. NULL, /* No truncation check for ebuf */
  15495. ebuf,
  15496. ebuf_len,
  15497. "%s",
  15498. "Bad request");
  15499. *err = 411;
  15500. return 0;
  15501. }
  15502. /* Publish the content length back to the request info. */
  15503. conn->request_info.content_length = conn->content_len;
  15504. } else {
  15505. /* There is no exception, see RFC7230. */
  15506. conn->content_len = 0;
  15507. }
  15508. return 1;
  15509. }
  15510. /* conn is assumed to be valid in this internal function */
  15511. static int
  15512. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15513. {
  15514. const char *cl;
  15515. conn->connection_type =
  15516. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15517. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15518. return 0;
  15519. }
  15520. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15521. <= 0) {
  15522. mg_snprintf(conn,
  15523. NULL, /* No truncation check for ebuf */
  15524. ebuf,
  15525. ebuf_len,
  15526. "%s",
  15527. "Bad response");
  15528. *err = 400;
  15529. return 0;
  15530. }
  15531. /* Message is a valid response */
  15532. if (((cl = get_header(conn->response_info.http_headers,
  15533. conn->response_info.num_headers,
  15534. "Transfer-Encoding"))
  15535. != NULL)
  15536. && mg_strcasecmp(cl, "identity")) {
  15537. if (mg_strcasecmp(cl, "chunked")) {
  15538. mg_snprintf(conn,
  15539. NULL, /* No truncation check for ebuf */
  15540. ebuf,
  15541. ebuf_len,
  15542. "%s",
  15543. "Bad request");
  15544. *err = 400;
  15545. return 0;
  15546. }
  15547. conn->is_chunked = 1;
  15548. conn->content_len = 0; /* not yet read */
  15549. } else if ((cl = get_header(conn->response_info.http_headers,
  15550. conn->response_info.num_headers,
  15551. "Content-Length"))
  15552. != NULL) {
  15553. char *endptr = NULL;
  15554. conn->content_len = strtoll(cl, &endptr, 10);
  15555. if ((endptr == cl) || (conn->content_len < 0)) {
  15556. mg_snprintf(conn,
  15557. NULL, /* No truncation check for ebuf */
  15558. ebuf,
  15559. ebuf_len,
  15560. "%s",
  15561. "Bad request");
  15562. *err = 411;
  15563. return 0;
  15564. }
  15565. /* Publish the content length back to the response info. */
  15566. conn->response_info.content_length = conn->content_len;
  15567. /* TODO: check if it is still used in response_info */
  15568. conn->request_info.content_length = conn->content_len;
  15569. /* TODO: we should also consider HEAD method */
  15570. if (conn->response_info.status_code == 304) {
  15571. conn->content_len = 0;
  15572. }
  15573. } else {
  15574. /* TODO: we should also consider HEAD method */
  15575. if (((conn->response_info.status_code >= 100)
  15576. && (conn->response_info.status_code <= 199))
  15577. || (conn->response_info.status_code == 204)
  15578. || (conn->response_info.status_code == 304)) {
  15579. conn->content_len = 0;
  15580. } else {
  15581. conn->content_len = -1; /* unknown content length */
  15582. }
  15583. }
  15584. return 1;
  15585. }
  15586. int
  15587. mg_get_response(struct mg_connection *conn,
  15588. char *ebuf,
  15589. size_t ebuf_len,
  15590. int timeout)
  15591. {
  15592. int err, ret;
  15593. char txt[32]; /* will not overflow */
  15594. char *save_timeout;
  15595. char *new_timeout;
  15596. if (ebuf_len > 0) {
  15597. ebuf[0] = '\0';
  15598. }
  15599. if (!conn) {
  15600. mg_snprintf(conn,
  15601. NULL, /* No truncation check for ebuf */
  15602. ebuf,
  15603. ebuf_len,
  15604. "%s",
  15605. "Parameter error");
  15606. return -1;
  15607. }
  15608. /* Reset the previous responses */
  15609. conn->data_len = 0;
  15610. /* Implementation of API function for HTTP clients */
  15611. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15612. if (timeout >= 0) {
  15613. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15614. new_timeout = txt;
  15615. } else {
  15616. new_timeout = NULL;
  15617. }
  15618. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15619. ret = get_response(conn, ebuf, ebuf_len, &err);
  15620. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15621. /* TODO: here, the URI is the http response code */
  15622. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15623. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15624. /* TODO (mid): Define proper return values - maybe return length?
  15625. * For the first test use <0 for error and >0 for OK */
  15626. return (ret == 0) ? -1 : +1;
  15627. }
  15628. struct mg_connection *
  15629. mg_download(const char *host,
  15630. int port,
  15631. int use_ssl,
  15632. char *ebuf,
  15633. size_t ebuf_len,
  15634. const char *fmt,
  15635. ...)
  15636. {
  15637. struct mg_connection *conn;
  15638. va_list ap;
  15639. int i;
  15640. int reqerr;
  15641. if (ebuf_len > 0) {
  15642. ebuf[0] = '\0';
  15643. }
  15644. va_start(ap, fmt);
  15645. /* open a connection */
  15646. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15647. if (conn != NULL) {
  15648. i = mg_vprintf(conn, fmt, ap);
  15649. if (i <= 0) {
  15650. mg_snprintf(conn,
  15651. NULL, /* No truncation check for ebuf */
  15652. ebuf,
  15653. ebuf_len,
  15654. "%s",
  15655. "Error sending request");
  15656. } else {
  15657. /* make sure the buffer is clear */
  15658. conn->data_len = 0;
  15659. get_response(conn, ebuf, ebuf_len, &reqerr);
  15660. /* TODO: here, the URI is the http response code */
  15661. conn->request_info.local_uri = conn->request_info.request_uri;
  15662. }
  15663. }
  15664. /* if an error occurred, close the connection */
  15665. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15666. mg_close_connection(conn);
  15667. conn = NULL;
  15668. }
  15669. va_end(ap);
  15670. return conn;
  15671. }
  15672. struct websocket_client_thread_data {
  15673. struct mg_connection *conn;
  15674. mg_websocket_data_handler data_handler;
  15675. mg_websocket_close_handler close_handler;
  15676. void *callback_data;
  15677. };
  15678. #if defined(USE_WEBSOCKET)
  15679. #if defined(_WIN32)
  15680. static unsigned __stdcall websocket_client_thread(void *data)
  15681. #else
  15682. static void *
  15683. websocket_client_thread(void *data)
  15684. #endif
  15685. {
  15686. struct websocket_client_thread_data *cdata =
  15687. (struct websocket_client_thread_data *)data;
  15688. void *user_thread_ptr = NULL;
  15689. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15690. struct sigaction sa;
  15691. /* Ignore SIGPIPE */
  15692. memset(&sa, 0, sizeof(sa));
  15693. sa.sa_handler = SIG_IGN;
  15694. sigaction(SIGPIPE, &sa, NULL);
  15695. #endif
  15696. mg_set_thread_name("ws-clnt");
  15697. if (cdata->conn->phys_ctx) {
  15698. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15699. /* 3 indicates a websocket client thread */
  15700. /* TODO: check if conn->phys_ctx can be set */
  15701. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15702. cdata->conn->phys_ctx, 3);
  15703. }
  15704. }
  15705. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15706. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15707. if (cdata->close_handler != NULL) {
  15708. cdata->close_handler(cdata->conn, cdata->callback_data);
  15709. }
  15710. /* The websocket_client context has only this thread. If it runs out,
  15711. set the stop_flag to 2 (= "stopped"). */
  15712. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15713. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15714. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15715. 3,
  15716. user_thread_ptr);
  15717. }
  15718. mg_free((void *)cdata);
  15719. #if defined(_WIN32)
  15720. return 0;
  15721. #else
  15722. return NULL;
  15723. #endif
  15724. }
  15725. #endif
  15726. static struct mg_connection *
  15727. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15728. int use_ssl,
  15729. char *error_buffer,
  15730. size_t error_buffer_size,
  15731. const char *path,
  15732. const char *origin,
  15733. const char *extensions,
  15734. mg_websocket_data_handler data_func,
  15735. mg_websocket_close_handler close_func,
  15736. void *user_data)
  15737. {
  15738. struct mg_connection *conn = NULL;
  15739. #if defined(USE_WEBSOCKET)
  15740. struct websocket_client_thread_data *thread_data;
  15741. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15742. const char *host = client_options->host;
  15743. int i;
  15744. #if defined(__clang__)
  15745. #pragma clang diagnostic push
  15746. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15747. #endif
  15748. /* Establish the client connection and request upgrade */
  15749. conn = mg_connect_client_impl(client_options,
  15750. use_ssl,
  15751. error_buffer,
  15752. error_buffer_size);
  15753. /* Connection object will be null if something goes wrong */
  15754. if (conn == NULL) {
  15755. /* error_buffer should be already filled ... */
  15756. if (!error_buffer[0]) {
  15757. /* ... if not add an error message */
  15758. mg_snprintf(conn,
  15759. NULL, /* No truncation check for ebuf */
  15760. error_buffer,
  15761. error_buffer_size,
  15762. "Unexpected error");
  15763. }
  15764. return NULL;
  15765. }
  15766. if (origin != NULL) {
  15767. if (extensions != NULL) {
  15768. i = mg_printf(conn,
  15769. "GET %s HTTP/1.1\r\n"
  15770. "Host: %s\r\n"
  15771. "Upgrade: websocket\r\n"
  15772. "Connection: Upgrade\r\n"
  15773. "Sec-WebSocket-Key: %s\r\n"
  15774. "Sec-WebSocket-Version: 13\r\n"
  15775. "Sec-WebSocket-Extensions: %s\r\n"
  15776. "Origin: %s\r\n"
  15777. "\r\n",
  15778. path,
  15779. host,
  15780. magic,
  15781. extensions,
  15782. origin);
  15783. } else {
  15784. i = mg_printf(conn,
  15785. "GET %s HTTP/1.1\r\n"
  15786. "Host: %s\r\n"
  15787. "Upgrade: websocket\r\n"
  15788. "Connection: Upgrade\r\n"
  15789. "Sec-WebSocket-Key: %s\r\n"
  15790. "Sec-WebSocket-Version: 13\r\n"
  15791. "Origin: %s\r\n"
  15792. "\r\n",
  15793. path,
  15794. host,
  15795. magic,
  15796. origin);
  15797. }
  15798. } else {
  15799. if (extensions != NULL) {
  15800. i = mg_printf(conn,
  15801. "GET %s HTTP/1.1\r\n"
  15802. "Host: %s\r\n"
  15803. "Upgrade: websocket\r\n"
  15804. "Connection: Upgrade\r\n"
  15805. "Sec-WebSocket-Key: %s\r\n"
  15806. "Sec-WebSocket-Version: 13\r\n"
  15807. "Sec-WebSocket-Extensions: %s\r\n"
  15808. "\r\n",
  15809. path,
  15810. host,
  15811. magic,
  15812. extensions);
  15813. } else {
  15814. i = mg_printf(conn,
  15815. "GET %s HTTP/1.1\r\n"
  15816. "Host: %s\r\n"
  15817. "Upgrade: websocket\r\n"
  15818. "Connection: Upgrade\r\n"
  15819. "Sec-WebSocket-Key: %s\r\n"
  15820. "Sec-WebSocket-Version: 13\r\n"
  15821. "\r\n",
  15822. path,
  15823. host,
  15824. magic);
  15825. }
  15826. }
  15827. if (i <= 0) {
  15828. mg_snprintf(conn,
  15829. NULL, /* No truncation check for ebuf */
  15830. error_buffer,
  15831. error_buffer_size,
  15832. "%s",
  15833. "Error sending request");
  15834. mg_close_connection(conn);
  15835. return NULL;
  15836. }
  15837. conn->data_len = 0;
  15838. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15839. mg_close_connection(conn);
  15840. return NULL;
  15841. }
  15842. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15843. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15844. #if defined(__clang__)
  15845. #pragma clang diagnostic pop
  15846. #endif
  15847. if (conn->response_info.status_code != 101) {
  15848. /* We sent an "upgrade" request. For a correct websocket
  15849. * protocol handshake, we expect a "101 Continue" response.
  15850. * Otherwise it is a protocol violation. Maybe the HTTP
  15851. * Server does not know websockets. */
  15852. if (!*error_buffer) {
  15853. /* set an error, if not yet set */
  15854. mg_snprintf(conn,
  15855. NULL, /* No truncation check for ebuf */
  15856. error_buffer,
  15857. error_buffer_size,
  15858. "Unexpected server reply");
  15859. }
  15860. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15861. mg_close_connection(conn);
  15862. return NULL;
  15863. }
  15864. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15865. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15866. if (!thread_data) {
  15867. DEBUG_TRACE("%s\r\n", "Out of memory");
  15868. mg_close_connection(conn);
  15869. return NULL;
  15870. }
  15871. thread_data->conn = conn;
  15872. thread_data->data_handler = data_func;
  15873. thread_data->close_handler = close_func;
  15874. thread_data->callback_data = user_data;
  15875. conn->phys_ctx->worker_threadids =
  15876. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15877. if (!conn->phys_ctx->worker_threadids) {
  15878. DEBUG_TRACE("%s\r\n", "Out of memory");
  15879. mg_free(thread_data);
  15880. mg_close_connection(conn);
  15881. return NULL;
  15882. }
  15883. /* Now upgrade to ws/wss client context */
  15884. conn->phys_ctx->user_data = user_data;
  15885. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15886. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15887. /* Start a thread to read the websocket client connection
  15888. * This thread will automatically stop when mg_disconnect is
  15889. * called on the client connection */
  15890. if (mg_start_thread_with_id(websocket_client_thread,
  15891. thread_data,
  15892. conn->phys_ctx->worker_threadids)
  15893. != 0) {
  15894. conn->phys_ctx->cfg_worker_threads = 0;
  15895. mg_free(thread_data);
  15896. mg_close_connection(conn);
  15897. conn = NULL;
  15898. DEBUG_TRACE("%s",
  15899. "Websocket client connect thread could not be started\r\n");
  15900. }
  15901. #else
  15902. /* Appease "unused parameter" warnings */
  15903. (void)client_options;
  15904. (void)use_ssl;
  15905. (void)error_buffer;
  15906. (void)error_buffer_size;
  15907. (void)path;
  15908. (void)origin;
  15909. (void)extensions;
  15910. (void)user_data;
  15911. (void)data_func;
  15912. (void)close_func;
  15913. #endif
  15914. return conn;
  15915. }
  15916. struct mg_connection *
  15917. mg_connect_websocket_client(const char *host,
  15918. int port,
  15919. int use_ssl,
  15920. char *error_buffer,
  15921. size_t error_buffer_size,
  15922. const char *path,
  15923. const char *origin,
  15924. mg_websocket_data_handler data_func,
  15925. mg_websocket_close_handler close_func,
  15926. void *user_data)
  15927. {
  15928. struct mg_client_options client_options;
  15929. memset(&client_options, 0, sizeof(client_options));
  15930. client_options.host = host;
  15931. client_options.port = port;
  15932. return mg_connect_websocket_client_impl(&client_options,
  15933. use_ssl,
  15934. error_buffer,
  15935. error_buffer_size,
  15936. path,
  15937. origin,
  15938. NULL,
  15939. data_func,
  15940. close_func,
  15941. user_data);
  15942. }
  15943. struct mg_connection *
  15944. mg_connect_websocket_client_secure(
  15945. const struct mg_client_options *client_options,
  15946. char *error_buffer,
  15947. size_t error_buffer_size,
  15948. const char *path,
  15949. const char *origin,
  15950. mg_websocket_data_handler data_func,
  15951. mg_websocket_close_handler close_func,
  15952. void *user_data)
  15953. {
  15954. if (!client_options) {
  15955. return NULL;
  15956. }
  15957. return mg_connect_websocket_client_impl(client_options,
  15958. 1,
  15959. error_buffer,
  15960. error_buffer_size,
  15961. path,
  15962. origin,
  15963. NULL,
  15964. data_func,
  15965. close_func,
  15966. user_data);
  15967. }
  15968. struct mg_connection *
  15969. mg_connect_websocket_client_extensions(const char *host,
  15970. int port,
  15971. int use_ssl,
  15972. char *error_buffer,
  15973. size_t error_buffer_size,
  15974. const char *path,
  15975. const char *origin,
  15976. const char *extensions,
  15977. mg_websocket_data_handler data_func,
  15978. mg_websocket_close_handler close_func,
  15979. void *user_data)
  15980. {
  15981. struct mg_client_options client_options;
  15982. memset(&client_options, 0, sizeof(client_options));
  15983. client_options.host = host;
  15984. client_options.port = port;
  15985. return mg_connect_websocket_client_impl(&client_options,
  15986. use_ssl,
  15987. error_buffer,
  15988. error_buffer_size,
  15989. path,
  15990. origin,
  15991. extensions,
  15992. data_func,
  15993. close_func,
  15994. user_data);
  15995. }
  15996. struct mg_connection *
  15997. mg_connect_websocket_client_secure_extensions(
  15998. const struct mg_client_options *client_options,
  15999. char *error_buffer,
  16000. size_t error_buffer_size,
  16001. const char *path,
  16002. const char *origin,
  16003. const char *extensions,
  16004. mg_websocket_data_handler data_func,
  16005. mg_websocket_close_handler close_func,
  16006. void *user_data)
  16007. {
  16008. if (!client_options) {
  16009. return NULL;
  16010. }
  16011. return mg_connect_websocket_client_impl(client_options,
  16012. 1,
  16013. error_buffer,
  16014. error_buffer_size,
  16015. path,
  16016. origin,
  16017. extensions,
  16018. data_func,
  16019. close_func,
  16020. user_data);
  16021. }
  16022. /* Prepare connection data structure */
  16023. static void
  16024. init_connection(struct mg_connection *conn)
  16025. {
  16026. /* Is keep alive allowed by the server */
  16027. int keep_alive_enabled =
  16028. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16029. if (!keep_alive_enabled) {
  16030. conn->must_close = 1;
  16031. }
  16032. /* Important: on new connection, reset the receiving buffer. Credit
  16033. * goes to crule42. */
  16034. conn->data_len = 0;
  16035. conn->handled_requests = 0;
  16036. conn->connection_type = CONNECTION_TYPE_INVALID;
  16037. mg_set_user_connection_data(conn, NULL);
  16038. #if defined(USE_SERVER_STATS)
  16039. conn->conn_state = 2; /* init */
  16040. #endif
  16041. /* call the init_connection callback if assigned */
  16042. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16043. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16044. void *conn_data = NULL;
  16045. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16046. mg_set_user_connection_data(conn, conn_data);
  16047. }
  16048. }
  16049. }
  16050. /* Process a connection - may handle multiple requests
  16051. * using the same connection.
  16052. * Must be called with a valid connection (conn and
  16053. * conn->phys_ctx must be valid).
  16054. */
  16055. static void
  16056. process_new_connection(struct mg_connection *conn)
  16057. {
  16058. struct mg_request_info *ri = &conn->request_info;
  16059. int keep_alive, discard_len;
  16060. char ebuf[100];
  16061. const char *hostend;
  16062. int reqerr, uri_type;
  16063. #if defined(USE_SERVER_STATS)
  16064. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16065. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16066. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16067. #endif
  16068. DEBUG_TRACE("Start processing connection from %s",
  16069. conn->request_info.remote_addr);
  16070. /* Loop over multiple requests sent using the same connection
  16071. * (while "keep alive"). */
  16072. do {
  16073. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16074. conn->handled_requests + 1);
  16075. #if defined(USE_SERVER_STATS)
  16076. conn->conn_state = 3; /* ready */
  16077. #endif
  16078. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16079. /* The request sent by the client could not be understood by
  16080. * the server, or it was incomplete or a timeout. Send an
  16081. * error message and close the connection. */
  16082. if (reqerr > 0) {
  16083. DEBUG_ASSERT(ebuf[0] != '\0');
  16084. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16085. }
  16086. } else if (strcmp(ri->http_version, "1.0")
  16087. && strcmp(ri->http_version, "1.1")) {
  16088. /* HTTP/2 is not allowed here */
  16089. mg_snprintf(conn,
  16090. NULL, /* No truncation check for ebuf */
  16091. ebuf,
  16092. sizeof(ebuf),
  16093. "Bad HTTP version: [%s]",
  16094. ri->http_version);
  16095. mg_send_http_error(conn, 505, "%s", ebuf);
  16096. }
  16097. if (ebuf[0] == '\0') {
  16098. uri_type = get_uri_type(conn->request_info.request_uri);
  16099. switch (uri_type) {
  16100. case 1:
  16101. /* Asterisk */
  16102. conn->request_info.local_uri_raw = 0;
  16103. /* TODO: Deal with '*'. */
  16104. break;
  16105. case 2:
  16106. /* relative uri */
  16107. conn->request_info.local_uri_raw =
  16108. conn->request_info.request_uri;
  16109. break;
  16110. case 3:
  16111. case 4:
  16112. /* absolute uri (with/without port) */
  16113. hostend = get_rel_url_at_current_server(
  16114. conn->request_info.request_uri, conn);
  16115. if (hostend) {
  16116. conn->request_info.local_uri_raw = hostend;
  16117. } else {
  16118. conn->request_info.local_uri_raw = NULL;
  16119. }
  16120. break;
  16121. default:
  16122. mg_snprintf(conn,
  16123. NULL, /* No truncation check for ebuf */
  16124. ebuf,
  16125. sizeof(ebuf),
  16126. "Invalid URI");
  16127. mg_send_http_error(conn, 400, "%s", ebuf);
  16128. conn->request_info.local_uri_raw = NULL;
  16129. break;
  16130. }
  16131. conn->request_info.local_uri =
  16132. (char *)conn->request_info.local_uri_raw;
  16133. }
  16134. if (ebuf[0] != '\0') {
  16135. conn->protocol_type = -1;
  16136. } else {
  16137. /* HTTP/1 allows protocol upgrade */
  16138. conn->protocol_type = should_switch_to_protocol(conn);
  16139. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16140. /* This will occur, if a HTTP/1.1 request should be upgraded
  16141. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16142. * Since most (all?) major browsers only support HTTP/2 using
  16143. * ALPN, this is hard to test and very low priority.
  16144. * Deactivate it (at least for now).
  16145. */
  16146. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16147. }
  16148. }
  16149. DEBUG_TRACE("http: %s, error: %s",
  16150. (ri->http_version ? ri->http_version : "none"),
  16151. (ebuf[0] ? ebuf : "none"));
  16152. if (ebuf[0] == '\0') {
  16153. if (conn->request_info.local_uri) {
  16154. /* handle request to local server */
  16155. handle_request_stat_log(conn);
  16156. } else {
  16157. /* TODO: handle non-local request (PROXY) */
  16158. conn->must_close = 1;
  16159. }
  16160. } else {
  16161. conn->must_close = 1;
  16162. }
  16163. /* Response complete. Free header buffer */
  16164. free_buffered_response_header_list(conn);
  16165. if (ri->remote_user != NULL) {
  16166. mg_free((void *)ri->remote_user);
  16167. /* Important! When having connections with and without auth
  16168. * would cause double free and then crash */
  16169. ri->remote_user = NULL;
  16170. }
  16171. /* NOTE(lsm): order is important here. should_keep_alive() call
  16172. * is using parsed request, which will be invalid after
  16173. * memmove's below.
  16174. * Therefore, memorize should_keep_alive() result now for later
  16175. * use in loop exit condition. */
  16176. /* Enable it only if this request is completely discardable. */
  16177. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16178. && should_keep_alive(conn) && (conn->content_len >= 0)
  16179. && (conn->request_len > 0)
  16180. && ((conn->is_chunked == 4)
  16181. || (!conn->is_chunked
  16182. && ((conn->consumed_content == conn->content_len)
  16183. || ((conn->request_len + conn->content_len)
  16184. <= conn->data_len))))
  16185. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16186. if (keep_alive) {
  16187. /* Discard all buffered data for this request */
  16188. discard_len =
  16189. ((conn->request_len + conn->content_len) < conn->data_len)
  16190. ? (int)(conn->request_len + conn->content_len)
  16191. : conn->data_len;
  16192. conn->data_len -= discard_len;
  16193. if (conn->data_len > 0) {
  16194. DEBUG_TRACE("discard_len = %d", discard_len);
  16195. memmove(conn->buf,
  16196. conn->buf + discard_len,
  16197. (size_t)conn->data_len);
  16198. }
  16199. }
  16200. DEBUG_ASSERT(conn->data_len >= 0);
  16201. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16202. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16203. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16204. (long int)conn->data_len,
  16205. (long int)conn->buf_size);
  16206. break;
  16207. }
  16208. conn->handled_requests++;
  16209. } while (keep_alive);
  16210. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16211. conn->request_info.remote_addr,
  16212. difftime(time(NULL), conn->conn_birth_time));
  16213. close_connection(conn);
  16214. #if defined(USE_SERVER_STATS)
  16215. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16216. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16217. #endif
  16218. }
  16219. #if defined(ALTERNATIVE_QUEUE)
  16220. static void
  16221. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16222. {
  16223. unsigned int i;
  16224. while (!ctx->stop_flag) {
  16225. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16226. /* find a free worker slot and signal it */
  16227. if (ctx->client_socks[i].in_use == 2) {
  16228. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16229. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16230. ctx->client_socks[i] = *sp;
  16231. ctx->client_socks[i].in_use = 1;
  16232. /* socket has been moved to the consumer */
  16233. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16234. (void)event_signal(ctx->client_wait_events[i]);
  16235. return;
  16236. }
  16237. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16238. }
  16239. }
  16240. /* queue is full */
  16241. mg_sleep(1);
  16242. }
  16243. /* must consume */
  16244. set_blocking_mode(sp->sock);
  16245. closesocket(sp->sock);
  16246. }
  16247. static int
  16248. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16249. {
  16250. DEBUG_TRACE("%s", "going idle");
  16251. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16252. ctx->client_socks[thread_index].in_use = 2;
  16253. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16254. event_wait(ctx->client_wait_events[thread_index]);
  16255. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16256. *sp = ctx->client_socks[thread_index];
  16257. if (ctx->stop_flag) {
  16258. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16259. if (sp->in_use == 1) {
  16260. /* must consume */
  16261. set_blocking_mode(sp->sock);
  16262. closesocket(sp->sock);
  16263. }
  16264. return 0;
  16265. }
  16266. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16267. if (sp->in_use == 1) {
  16268. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16269. return 1;
  16270. }
  16271. /* must not reach here */
  16272. DEBUG_ASSERT(0);
  16273. return 0;
  16274. }
  16275. #else /* ALTERNATIVE_QUEUE */
  16276. /* Worker threads take accepted socket from the queue */
  16277. static int
  16278. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16279. {
  16280. (void)thread_index;
  16281. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16282. DEBUG_TRACE("%s", "going idle");
  16283. /* If the queue is empty, wait. We're idle at this point. */
  16284. while ((ctx->sq_head == ctx->sq_tail)
  16285. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16286. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16287. }
  16288. /* If we're stopping, sq_head may be equal to sq_tail. */
  16289. if (ctx->sq_head > ctx->sq_tail) {
  16290. /* Copy socket from the queue and increment tail */
  16291. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16292. ctx->sq_tail++;
  16293. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16294. /* Wrap pointers if needed */
  16295. while (ctx->sq_tail > ctx->sq_size) {
  16296. ctx->sq_tail -= ctx->sq_size;
  16297. ctx->sq_head -= ctx->sq_size;
  16298. }
  16299. }
  16300. (void)pthread_cond_signal(&ctx->sq_empty);
  16301. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16302. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16303. }
  16304. /* Master thread adds accepted socket to a queue */
  16305. static void
  16306. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16307. {
  16308. int queue_filled;
  16309. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16310. queue_filled = ctx->sq_head - ctx->sq_tail;
  16311. /* If the queue is full, wait */
  16312. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16313. && (queue_filled >= ctx->sq_size)) {
  16314. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16315. #if defined(USE_SERVER_STATS)
  16316. if (queue_filled > ctx->sq_max_fill) {
  16317. ctx->sq_max_fill = queue_filled;
  16318. }
  16319. #endif
  16320. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16321. ctx->sq_blocked = 0; /* Not blocked now */
  16322. queue_filled = ctx->sq_head - ctx->sq_tail;
  16323. }
  16324. if (queue_filled < ctx->sq_size) {
  16325. /* Copy socket to the queue and increment head */
  16326. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16327. ctx->sq_head++;
  16328. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16329. }
  16330. queue_filled = ctx->sq_head - ctx->sq_tail;
  16331. #if defined(USE_SERVER_STATS)
  16332. if (queue_filled > ctx->sq_max_fill) {
  16333. ctx->sq_max_fill = queue_filled;
  16334. }
  16335. #endif
  16336. (void)pthread_cond_signal(&ctx->sq_full);
  16337. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16338. }
  16339. #endif /* ALTERNATIVE_QUEUE */
  16340. static void
  16341. worker_thread_run(struct mg_connection *conn)
  16342. {
  16343. struct mg_context *ctx = conn->phys_ctx;
  16344. int thread_index;
  16345. struct mg_workerTLS tls;
  16346. mg_set_thread_name("worker");
  16347. tls.is_master = 0;
  16348. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16349. #if defined(_WIN32)
  16350. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16351. #endif
  16352. /* Initialize thread local storage before calling any callback */
  16353. pthread_setspecific(sTlsKey, &tls);
  16354. /* Check if there is a user callback */
  16355. if (ctx->callbacks.init_thread) {
  16356. /* call init_thread for a worker thread (type 1), and store the
  16357. * return value */
  16358. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16359. } else {
  16360. /* No callback: set user pointer to NULL */
  16361. tls.user_ptr = NULL;
  16362. }
  16363. /* Connection structure has been pre-allocated */
  16364. thread_index = (int)(conn - ctx->worker_connections);
  16365. if ((thread_index < 0)
  16366. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16367. mg_cry_ctx_internal(ctx,
  16368. "Internal error: Invalid worker index %i",
  16369. thread_index);
  16370. return;
  16371. }
  16372. /* Request buffers are not pre-allocated. They are private to the
  16373. * request and do not contain any state information that might be
  16374. * of interest to anyone observing a server status. */
  16375. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16376. if (conn->buf == NULL) {
  16377. mg_cry_ctx_internal(
  16378. ctx,
  16379. "Out of memory: Cannot allocate buffer for worker %i",
  16380. thread_index);
  16381. return;
  16382. }
  16383. conn->buf_size = (int)ctx->max_request_size;
  16384. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16385. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16386. conn->request_info.user_data = ctx->user_data;
  16387. /* Allocate a mutex for this connection to allow communication both
  16388. * within the request handler and from elsewhere in the application
  16389. */
  16390. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16391. mg_free(conn->buf);
  16392. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16393. return;
  16394. }
  16395. #if defined(USE_SERVER_STATS)
  16396. conn->conn_state = 1; /* not consumed */
  16397. #endif
  16398. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16399. * signal sq_empty condvar to wake up the master waiting in
  16400. * produce_socket() */
  16401. while (consume_socket(ctx, &conn->client, thread_index)) {
  16402. /* New connections must start with new protocol negotiation */
  16403. tls.alpn_proto = NULL;
  16404. #if defined(USE_SERVER_STATS)
  16405. conn->conn_close_time = 0;
  16406. #endif
  16407. conn->conn_birth_time = time(NULL);
  16408. /* Fill in IP, port info early so even if SSL setup below fails,
  16409. * error handler would have the corresponding info.
  16410. * Thanks to Johannes Winkelmann for the patch.
  16411. */
  16412. conn->request_info.remote_port =
  16413. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16414. conn->request_info.server_port =
  16415. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16416. sockaddr_to_string(conn->request_info.remote_addr,
  16417. sizeof(conn->request_info.remote_addr),
  16418. &conn->client.rsa);
  16419. DEBUG_TRACE("Incomming %sconnection from %s",
  16420. (conn->client.is_ssl ? "SSL " : ""),
  16421. conn->request_info.remote_addr);
  16422. conn->request_info.is_ssl = conn->client.is_ssl;
  16423. if (conn->client.is_ssl) {
  16424. #if defined(USE_MBEDTLS)
  16425. /* HTTPS connection */
  16426. if (mbed_ssl_accept(&(conn->ssl),
  16427. conn->dom_ctx->ssl_ctx,
  16428. (int *)&(conn->client.sock),
  16429. conn->phys_ctx)
  16430. == 0) {
  16431. /* conn->dom_ctx is set in get_request */
  16432. /* process HTTPS connection */
  16433. init_connection(conn);
  16434. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16435. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16436. process_new_connection(conn);
  16437. } else {
  16438. /* make sure the connection is cleaned up on SSL failure */
  16439. close_connection(conn);
  16440. }
  16441. #elif !defined(NO_SSL)
  16442. /* HTTPS connection */
  16443. if (sslize(conn, SSL_accept, NULL)) {
  16444. /* conn->dom_ctx is set in get_request */
  16445. /* Get SSL client certificate information (if set) */
  16446. struct mg_client_cert client_cert;
  16447. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16448. conn->request_info.client_cert = &client_cert;
  16449. }
  16450. /* process HTTPS connection */
  16451. #if defined(USE_HTTP2)
  16452. if ((tls.alpn_proto != NULL)
  16453. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16454. /* process HTTPS/2 connection */
  16455. init_connection(conn);
  16456. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16457. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16458. conn->content_len =
  16459. -1; /* content length is not predefined */
  16460. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16461. process_new_http2_connection(conn);
  16462. } else
  16463. #endif
  16464. {
  16465. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16466. init_connection(conn);
  16467. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16468. /* Start with HTTP, WS will be an "upgrade" request later */
  16469. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16470. process_new_connection(conn);
  16471. }
  16472. /* Free client certificate info */
  16473. if (conn->request_info.client_cert) {
  16474. mg_free((void *)(conn->request_info.client_cert->subject));
  16475. mg_free((void *)(conn->request_info.client_cert->issuer));
  16476. mg_free((void *)(conn->request_info.client_cert->serial));
  16477. mg_free((void *)(conn->request_info.client_cert->finger));
  16478. /* Free certificate memory */
  16479. X509_free(
  16480. (X509 *)conn->request_info.client_cert->peer_cert);
  16481. conn->request_info.client_cert->peer_cert = 0;
  16482. conn->request_info.client_cert->subject = 0;
  16483. conn->request_info.client_cert->issuer = 0;
  16484. conn->request_info.client_cert->serial = 0;
  16485. conn->request_info.client_cert->finger = 0;
  16486. conn->request_info.client_cert = 0;
  16487. }
  16488. } else {
  16489. /* make sure the connection is cleaned up on SSL failure */
  16490. close_connection(conn);
  16491. }
  16492. #endif
  16493. } else {
  16494. /* process HTTP connection */
  16495. init_connection(conn);
  16496. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16497. /* Start with HTTP, WS will be an "upgrade" request later */
  16498. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16499. process_new_connection(conn);
  16500. }
  16501. DEBUG_TRACE("%s", "Connection closed");
  16502. #if defined(USE_SERVER_STATS)
  16503. conn->conn_close_time = time(NULL);
  16504. #endif
  16505. }
  16506. /* Call exit thread user callback */
  16507. if (ctx->callbacks.exit_thread) {
  16508. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16509. }
  16510. /* delete thread local storage objects */
  16511. pthread_setspecific(sTlsKey, NULL);
  16512. #if defined(_WIN32)
  16513. CloseHandle(tls.pthread_cond_helper_mutex);
  16514. #endif
  16515. pthread_mutex_destroy(&conn->mutex);
  16516. /* Free the request buffer. */
  16517. conn->buf_size = 0;
  16518. mg_free(conn->buf);
  16519. conn->buf = NULL;
  16520. /* Free cleaned URI (if any) */
  16521. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16522. mg_free((void *)conn->request_info.local_uri);
  16523. conn->request_info.local_uri = NULL;
  16524. }
  16525. #if defined(USE_SERVER_STATS)
  16526. conn->conn_state = 9; /* done */
  16527. #endif
  16528. DEBUG_TRACE("%s", "exiting");
  16529. }
  16530. /* Threads have different return types on Windows and Unix. */
  16531. #if defined(_WIN32)
  16532. static unsigned __stdcall worker_thread(void *thread_func_param)
  16533. {
  16534. worker_thread_run((struct mg_connection *)thread_func_param);
  16535. return 0;
  16536. }
  16537. #else
  16538. static void *
  16539. worker_thread(void *thread_func_param)
  16540. {
  16541. #if !defined(__ZEPHYR__)
  16542. struct sigaction sa;
  16543. /* Ignore SIGPIPE */
  16544. memset(&sa, 0, sizeof(sa));
  16545. sa.sa_handler = SIG_IGN;
  16546. sigaction(SIGPIPE, &sa, NULL);
  16547. #endif
  16548. worker_thread_run((struct mg_connection *)thread_func_param);
  16549. return NULL;
  16550. }
  16551. #endif /* _WIN32 */
  16552. /* This is an internal function, thus all arguments are expected to be
  16553. * valid - a NULL check is not required. */
  16554. static void
  16555. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16556. {
  16557. struct socket so;
  16558. char src_addr[IP_ADDR_STR_LEN];
  16559. socklen_t len = sizeof(so.rsa);
  16560. #if !defined(__ZEPHYR__)
  16561. int on = 1;
  16562. #endif
  16563. memset(&so, 0, sizeof(so));
  16564. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16565. == INVALID_SOCKET) {
  16566. } else if (check_acl(ctx, &so.rsa) != 1) {
  16567. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16568. mg_cry_ctx_internal(ctx,
  16569. "%s: %s is not allowed to connect",
  16570. __func__,
  16571. src_addr);
  16572. closesocket(so.sock);
  16573. } else {
  16574. /* Put so socket structure into the queue */
  16575. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16576. set_close_on_exec(so.sock, NULL, ctx);
  16577. so.is_ssl = listener->is_ssl;
  16578. so.ssl_redir = listener->ssl_redir;
  16579. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16580. mg_cry_ctx_internal(ctx,
  16581. "%s: getsockname() failed: %s",
  16582. __func__,
  16583. strerror(ERRNO));
  16584. }
  16585. #if !defined(__ZEPHYR__)
  16586. if ((so.lsa.sa.sa_family == AF_INET)
  16587. || (so.lsa.sa.sa_family == AF_INET6)) {
  16588. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16589. * This is needed because if HTTP-level keep-alive
  16590. * is enabled, and client resets the connection, server won't get
  16591. * TCP FIN or RST and will keep the connection open forever. With
  16592. * TCP keep-alive, next keep-alive handshake will figure out that
  16593. * the client is down and will close the server end.
  16594. * Thanks to Igor Klopov who suggested the patch. */
  16595. if (setsockopt(so.sock,
  16596. SOL_SOCKET,
  16597. SO_KEEPALIVE,
  16598. (SOCK_OPT_TYPE)&on,
  16599. sizeof(on))
  16600. != 0) {
  16601. mg_cry_ctx_internal(
  16602. ctx,
  16603. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16604. __func__,
  16605. strerror(ERRNO));
  16606. }
  16607. }
  16608. #endif
  16609. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16610. * to effectively fill up the underlying IP packet payload and
  16611. * reduce the overhead of sending lots of small buffers. However
  16612. * this hurts the server's throughput (ie. operations per second)
  16613. * when HTTP 1.1 persistent connections are used and the responses
  16614. * are relatively small (eg. less than 1400 bytes).
  16615. */
  16616. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16617. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16618. if (set_tcp_nodelay(&so, 1) != 0) {
  16619. mg_cry_ctx_internal(
  16620. ctx,
  16621. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16622. __func__,
  16623. strerror(ERRNO));
  16624. }
  16625. }
  16626. /* The "non blocking" property should already be
  16627. * inherited from the parent socket. Set it for
  16628. * non-compliant socket implementations. */
  16629. set_non_blocking_mode(so.sock);
  16630. so.in_use = 0;
  16631. produce_socket(ctx, &so);
  16632. }
  16633. }
  16634. static void
  16635. master_thread_run(struct mg_context *ctx)
  16636. {
  16637. struct mg_workerTLS tls;
  16638. struct mg_pollfd *pfd;
  16639. unsigned int i;
  16640. unsigned int workerthreadcount;
  16641. if (!ctx) {
  16642. return;
  16643. }
  16644. mg_set_thread_name("master");
  16645. /* Increase priority of the master thread */
  16646. #if defined(_WIN32)
  16647. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16648. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16649. int min_prio = sched_get_priority_min(SCHED_RR);
  16650. int max_prio = sched_get_priority_max(SCHED_RR);
  16651. if ((min_prio >= 0) && (max_prio >= 0)
  16652. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16653. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16654. struct sched_param sched_param = {0};
  16655. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16656. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16657. }
  16658. #endif
  16659. /* Initialize thread local storage */
  16660. #if defined(_WIN32)
  16661. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16662. #endif
  16663. tls.is_master = 1;
  16664. pthread_setspecific(sTlsKey, &tls);
  16665. if (ctx->callbacks.init_thread) {
  16666. /* Callback for the master thread (type 0) */
  16667. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16668. } else {
  16669. tls.user_ptr = NULL;
  16670. }
  16671. /* Lua background script "start" event */
  16672. #if defined(USE_LUA)
  16673. if (ctx->lua_background_state) {
  16674. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16675. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16676. /* call "start()" in Lua */
  16677. lua_getglobal(lstate, "start");
  16678. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16679. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16680. if (ret != 0) {
  16681. struct mg_connection fc;
  16682. lua_cry(fake_connection(&fc, ctx),
  16683. ret,
  16684. lstate,
  16685. "lua_background_script",
  16686. "start");
  16687. }
  16688. } else {
  16689. lua_pop(lstate, 1);
  16690. }
  16691. /* determine if there is a "log()" function in Lua background script */
  16692. lua_getglobal(lstate, "log");
  16693. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16694. ctx->lua_bg_log_available = 1;
  16695. }
  16696. lua_pop(lstate, 1);
  16697. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16698. }
  16699. #endif
  16700. /* Server starts *now* */
  16701. ctx->start_time = time(NULL);
  16702. /* Server accept loop */
  16703. pfd = ctx->listening_socket_fds;
  16704. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16705. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16706. pfd[i].fd = ctx->listening_sockets[i].sock;
  16707. pfd[i].events = POLLIN;
  16708. }
  16709. if (mg_poll(pfd,
  16710. ctx->num_listening_sockets,
  16711. SOCKET_TIMEOUT_QUANTUM,
  16712. &(ctx->stop_flag))
  16713. > 0) {
  16714. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16715. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16716. * successful poll, and POLLIN is defined as
  16717. * (POLLRDNORM | POLLRDBAND)
  16718. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16719. * pfd[i].revents == POLLIN. */
  16720. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16721. && (pfd[i].revents & POLLIN)) {
  16722. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16723. }
  16724. }
  16725. }
  16726. }
  16727. /* Here stop_flag is 1 - Initiate shutdown. */
  16728. DEBUG_TRACE("%s", "stopping workers");
  16729. /* Stop signal received: somebody called mg_stop. Quit. */
  16730. close_all_listening_sockets(ctx);
  16731. /* Wakeup workers that are waiting for connections to handle. */
  16732. #if defined(ALTERNATIVE_QUEUE)
  16733. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16734. event_signal(ctx->client_wait_events[i]);
  16735. }
  16736. #else
  16737. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16738. pthread_cond_broadcast(&ctx->sq_full);
  16739. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16740. #endif
  16741. /* Join all worker threads to avoid leaking threads. */
  16742. workerthreadcount = ctx->cfg_worker_threads;
  16743. for (i = 0; i < workerthreadcount; i++) {
  16744. if (ctx->worker_threadids[i] != 0) {
  16745. mg_join_thread(ctx->worker_threadids[i]);
  16746. }
  16747. }
  16748. #if defined(USE_LUA)
  16749. /* Free Lua state of lua background task */
  16750. if (ctx->lua_background_state) {
  16751. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16752. ctx->lua_bg_log_available = 0;
  16753. /* call "stop()" in Lua */
  16754. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16755. lua_getglobal(lstate, "stop");
  16756. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16757. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16758. if (ret != 0) {
  16759. struct mg_connection fc;
  16760. lua_cry(fake_connection(&fc, ctx),
  16761. ret,
  16762. lstate,
  16763. "lua_background_script",
  16764. "stop");
  16765. }
  16766. }
  16767. lua_close(lstate);
  16768. ctx->lua_background_state = 0;
  16769. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16770. }
  16771. #endif
  16772. DEBUG_TRACE("%s", "exiting");
  16773. /* call exit thread callback */
  16774. if (ctx->callbacks.exit_thread) {
  16775. /* Callback for the master thread (type 0) */
  16776. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16777. }
  16778. #if defined(_WIN32)
  16779. CloseHandle(tls.pthread_cond_helper_mutex);
  16780. #endif
  16781. pthread_setspecific(sTlsKey, NULL);
  16782. /* Signal mg_stop() that we're done.
  16783. * WARNING: This must be the very last thing this
  16784. * thread does, as ctx becomes invalid after this line. */
  16785. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16786. }
  16787. /* Threads have different return types on Windows and Unix. */
  16788. #if defined(_WIN32)
  16789. static unsigned __stdcall master_thread(void *thread_func_param)
  16790. {
  16791. master_thread_run((struct mg_context *)thread_func_param);
  16792. return 0;
  16793. }
  16794. #else
  16795. static void *
  16796. master_thread(void *thread_func_param)
  16797. {
  16798. #if !defined(__ZEPHYR__)
  16799. struct sigaction sa;
  16800. /* Ignore SIGPIPE */
  16801. memset(&sa, 0, sizeof(sa));
  16802. sa.sa_handler = SIG_IGN;
  16803. sigaction(SIGPIPE, &sa, NULL);
  16804. #endif
  16805. master_thread_run((struct mg_context *)thread_func_param);
  16806. return NULL;
  16807. }
  16808. #endif /* _WIN32 */
  16809. static void
  16810. free_context(struct mg_context *ctx)
  16811. {
  16812. int i;
  16813. struct mg_handler_info *tmp_rh;
  16814. if (ctx == NULL) {
  16815. return;
  16816. }
  16817. /* Call user callback */
  16818. if (ctx->callbacks.exit_context) {
  16819. ctx->callbacks.exit_context(ctx);
  16820. }
  16821. /* All threads exited, no sync is needed. Destroy thread mutex and
  16822. * condvars
  16823. */
  16824. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16825. #if defined(ALTERNATIVE_QUEUE)
  16826. mg_free(ctx->client_socks);
  16827. if (ctx->client_wait_events != NULL) {
  16828. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16829. event_destroy(ctx->client_wait_events[i]);
  16830. }
  16831. mg_free(ctx->client_wait_events);
  16832. }
  16833. #else
  16834. (void)pthread_cond_destroy(&ctx->sq_empty);
  16835. (void)pthread_cond_destroy(&ctx->sq_full);
  16836. mg_free(ctx->squeue);
  16837. #endif
  16838. /* Destroy other context global data structures mutex */
  16839. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16840. #if defined(USE_LUA)
  16841. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  16842. #endif
  16843. /* Deallocate config parameters */
  16844. for (i = 0; i < NUM_OPTIONS; i++) {
  16845. if (ctx->dd.config[i] != NULL) {
  16846. #if defined(_MSC_VER)
  16847. #pragma warning(suppress : 6001)
  16848. #endif
  16849. mg_free(ctx->dd.config[i]);
  16850. }
  16851. }
  16852. /* Deallocate request handlers */
  16853. while (ctx->dd.handlers) {
  16854. tmp_rh = ctx->dd.handlers;
  16855. ctx->dd.handlers = tmp_rh->next;
  16856. mg_free(tmp_rh->uri);
  16857. mg_free(tmp_rh);
  16858. }
  16859. #if defined(USE_MBEDTLS)
  16860. if (ctx->dd.ssl_ctx != NULL) {
  16861. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16862. mg_free(ctx->dd.ssl_ctx);
  16863. ctx->dd.ssl_ctx = NULL;
  16864. }
  16865. #elif !defined(NO_SSL)
  16866. /* Deallocate SSL context */
  16867. if (ctx->dd.ssl_ctx != NULL) {
  16868. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16869. int callback_ret =
  16870. (ctx->callbacks.external_ssl_ctx == NULL)
  16871. ? 0
  16872. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16873. if (callback_ret == 0) {
  16874. SSL_CTX_free(ctx->dd.ssl_ctx);
  16875. }
  16876. /* else: ignore error and ommit SSL_CTX_free in case
  16877. * callback_ret is 1 */
  16878. }
  16879. #endif /* !NO_SSL */
  16880. /* Deallocate worker thread ID array */
  16881. mg_free(ctx->worker_threadids);
  16882. /* Deallocate worker thread ID array */
  16883. mg_free(ctx->worker_connections);
  16884. /* deallocate system name string */
  16885. mg_free(ctx->systemName);
  16886. /* Deallocate context itself */
  16887. mg_free(ctx);
  16888. }
  16889. void
  16890. mg_stop(struct mg_context *ctx)
  16891. {
  16892. pthread_t mt;
  16893. if (!ctx) {
  16894. return;
  16895. }
  16896. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16897. * two threads is not allowed. */
  16898. mt = ctx->masterthreadid;
  16899. if (mt == 0) {
  16900. return;
  16901. }
  16902. ctx->masterthreadid = 0;
  16903. /* Set stop flag, so all threads know they have to exit. */
  16904. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16905. /* Join timer thread */
  16906. #if defined(USE_TIMERS)
  16907. timers_exit(ctx);
  16908. #endif
  16909. /* Wait until everything has stopped. */
  16910. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16911. (void)mg_sleep(10);
  16912. }
  16913. /* Wait to stop master thread */
  16914. mg_join_thread(mt);
  16915. /* Close remaining Lua states */
  16916. #if defined(USE_LUA)
  16917. lua_ctx_exit(ctx);
  16918. #endif
  16919. /* Free memory */
  16920. free_context(ctx);
  16921. }
  16922. static void
  16923. get_system_name(char **sysName)
  16924. {
  16925. #if defined(_WIN32)
  16926. char name[128];
  16927. DWORD dwVersion = 0;
  16928. DWORD dwMajorVersion = 0;
  16929. DWORD dwMinorVersion = 0;
  16930. DWORD dwBuild = 0;
  16931. BOOL wowRet, isWoW = FALSE;
  16932. #if defined(_MSC_VER)
  16933. #pragma warning(push)
  16934. /* GetVersion was declared deprecated */
  16935. #pragma warning(disable : 4996)
  16936. #endif
  16937. dwVersion = GetVersion();
  16938. #if defined(_MSC_VER)
  16939. #pragma warning(pop)
  16940. #endif
  16941. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16942. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16943. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16944. (void)dwBuild;
  16945. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16946. sprintf(name,
  16947. "Windows %u.%u%s",
  16948. (unsigned)dwMajorVersion,
  16949. (unsigned)dwMinorVersion,
  16950. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16951. *sysName = mg_strdup(name);
  16952. #elif defined(__ZEPHYR__)
  16953. *sysName = mg_strdup("Zephyr OS");
  16954. #else
  16955. struct utsname name;
  16956. memset(&name, 0, sizeof(name));
  16957. uname(&name);
  16958. *sysName = mg_strdup(name.sysname);
  16959. #endif
  16960. }
  16961. static void
  16962. legacy_init(const char **options)
  16963. {
  16964. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16965. if (options) {
  16966. const char **run_options = options;
  16967. const char *optname = config_options[LISTENING_PORTS].name;
  16968. /* Try to find the "listening_ports" option */
  16969. while (*run_options) {
  16970. if (!strcmp(*run_options, optname)) {
  16971. ports_option = run_options[1];
  16972. }
  16973. run_options += 2;
  16974. }
  16975. }
  16976. if (is_ssl_port_used(ports_option)) {
  16977. /* Initialize with SSL support */
  16978. mg_init_library(MG_FEATURES_TLS);
  16979. } else {
  16980. /* Initialize without SSL support */
  16981. mg_init_library(MG_FEATURES_DEFAULT);
  16982. }
  16983. }
  16984. struct mg_context *
  16985. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16986. {
  16987. struct mg_context *ctx;
  16988. const char *name, *value, *default_value;
  16989. int idx, ok, workerthreadcount;
  16990. unsigned int i;
  16991. int itmp;
  16992. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16993. const char **options =
  16994. ((init != NULL) ? (init->configuration_options) : (NULL));
  16995. struct mg_workerTLS tls;
  16996. if (error != NULL) {
  16997. error->code = 0;
  16998. if (error->text_buffer_size > 0) {
  16999. *error->text = 0;
  17000. }
  17001. }
  17002. if (mg_init_library_called == 0) {
  17003. /* Legacy INIT, if mg_start is called without mg_init_library.
  17004. * Note: This will cause a memory leak when unloading the library.
  17005. */
  17006. legacy_init(options);
  17007. }
  17008. if (mg_init_library_called == 0) {
  17009. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17010. mg_snprintf(NULL,
  17011. NULL, /* No truncation check for error buffers */
  17012. error->text,
  17013. error->text_buffer_size,
  17014. "%s",
  17015. "Library uninitialized");
  17016. }
  17017. return NULL;
  17018. }
  17019. /* Allocate context and initialize reasonable general case defaults. */
  17020. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17021. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17022. mg_snprintf(NULL,
  17023. NULL, /* No truncation check for error buffers */
  17024. error->text,
  17025. error->text_buffer_size,
  17026. "%s",
  17027. "Out of memory");
  17028. }
  17029. return NULL;
  17030. }
  17031. /* Random number generator will initialize at the first call */
  17032. ctx->dd.auth_nonce_mask =
  17033. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17034. /* Save started thread index to reuse in other external API calls
  17035. * For the sake of thread synchronization all non-civetweb threads
  17036. * can be considered as single external thread */
  17037. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17038. tls.is_master = -1; /* Thread calling mg_start */
  17039. tls.thread_idx = ctx->starter_thread_idx;
  17040. #if defined(_WIN32)
  17041. tls.pthread_cond_helper_mutex = NULL;
  17042. #endif
  17043. pthread_setspecific(sTlsKey, &tls);
  17044. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17045. #if !defined(ALTERNATIVE_QUEUE)
  17046. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17047. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17048. ctx->sq_blocked = 0;
  17049. #endif
  17050. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17051. #if defined(USE_LUA)
  17052. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17053. #endif
  17054. if (!ok) {
  17055. const char *err_msg =
  17056. "Cannot initialize thread synchronization objects";
  17057. /* Fatal error - abort start. However, this situation should never
  17058. * occur in practice. */
  17059. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17060. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17061. mg_snprintf(NULL,
  17062. NULL, /* No truncation check for error buffers */
  17063. error->text,
  17064. error->text_buffer_size,
  17065. "%s",
  17066. err_msg);
  17067. }
  17068. mg_free(ctx);
  17069. pthread_setspecific(sTlsKey, NULL);
  17070. return NULL;
  17071. }
  17072. if ((init != NULL) && (init->callbacks != NULL)) {
  17073. /* Set all callbacks except exit_context. */
  17074. ctx->callbacks = *init->callbacks;
  17075. exit_callback = init->callbacks->exit_context;
  17076. /* The exit callback is activated once the context is successfully
  17077. * created. It should not be called, if an incomplete context object
  17078. * is deleted during a failed initialization. */
  17079. ctx->callbacks.exit_context = 0;
  17080. }
  17081. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17082. ctx->dd.handlers = NULL;
  17083. ctx->dd.next = NULL;
  17084. #if defined(USE_LUA)
  17085. lua_ctx_init(ctx);
  17086. #endif
  17087. /* Store options */
  17088. while (options && (name = *options++) != NULL) {
  17089. if ((idx = get_option_index(name)) == -1) {
  17090. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17091. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17092. mg_snprintf(NULL,
  17093. NULL, /* No truncation check for error buffers */
  17094. error->text,
  17095. error->text_buffer_size,
  17096. "Invalid configuration option: %s",
  17097. name);
  17098. }
  17099. free_context(ctx);
  17100. pthread_setspecific(sTlsKey, NULL);
  17101. return NULL;
  17102. } else if ((value = *options++) == NULL) {
  17103. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17104. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17105. mg_snprintf(NULL,
  17106. NULL, /* No truncation check for error buffers */
  17107. error->text,
  17108. error->text_buffer_size,
  17109. "Invalid configuration option value: %s",
  17110. name);
  17111. }
  17112. free_context(ctx);
  17113. pthread_setspecific(sTlsKey, NULL);
  17114. return NULL;
  17115. }
  17116. if (ctx->dd.config[idx] != NULL) {
  17117. /* A duplicate configuration option is not an error - the last
  17118. * option value will be used. */
  17119. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17120. mg_free(ctx->dd.config[idx]);
  17121. }
  17122. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17123. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17124. }
  17125. /* Set default value if needed */
  17126. for (i = 0; config_options[i].name != NULL; i++) {
  17127. default_value = config_options[i].default_value;
  17128. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17129. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17130. }
  17131. }
  17132. /* Request size option */
  17133. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17134. if (itmp < 1024) {
  17135. mg_cry_ctx_internal(ctx,
  17136. "%s too small",
  17137. config_options[MAX_REQUEST_SIZE].name);
  17138. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17139. mg_snprintf(NULL,
  17140. NULL, /* No truncation check for error buffers */
  17141. error->text,
  17142. error->text_buffer_size,
  17143. "Invalid configuration option value: %s",
  17144. config_options[MAX_REQUEST_SIZE].name);
  17145. }
  17146. free_context(ctx);
  17147. pthread_setspecific(sTlsKey, NULL);
  17148. return NULL;
  17149. }
  17150. ctx->max_request_size = (unsigned)itmp;
  17151. /* Queue length */
  17152. #if !defined(ALTERNATIVE_QUEUE)
  17153. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17154. if (itmp < 1) {
  17155. mg_cry_ctx_internal(ctx,
  17156. "%s too small",
  17157. config_options[CONNECTION_QUEUE_SIZE].name);
  17158. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17159. mg_snprintf(NULL,
  17160. NULL, /* No truncation check for error buffers */
  17161. error->text,
  17162. error->text_buffer_size,
  17163. "Invalid configuration option value: %s",
  17164. config_options[CONNECTION_QUEUE_SIZE].name);
  17165. }
  17166. free_context(ctx);
  17167. pthread_setspecific(sTlsKey, NULL);
  17168. return NULL;
  17169. }
  17170. ctx->squeue =
  17171. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17172. if (ctx->squeue == NULL) {
  17173. mg_cry_ctx_internal(ctx,
  17174. "Out of memory: Cannot allocate %s",
  17175. config_options[CONNECTION_QUEUE_SIZE].name);
  17176. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17177. mg_snprintf(NULL,
  17178. NULL, /* No truncation check for error buffers */
  17179. error->text,
  17180. error->text_buffer_size,
  17181. "Out of memory: Cannot allocate %s",
  17182. config_options[CONNECTION_QUEUE_SIZE].name);
  17183. }
  17184. free_context(ctx);
  17185. pthread_setspecific(sTlsKey, NULL);
  17186. return NULL;
  17187. }
  17188. ctx->sq_size = itmp;
  17189. #endif
  17190. /* Worker thread count option */
  17191. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17192. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17193. if (workerthreadcount <= 0) {
  17194. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17195. } else {
  17196. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17197. }
  17198. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17199. mg_snprintf(NULL,
  17200. NULL, /* No truncation check for error buffers */
  17201. error->text,
  17202. error->text_buffer_size,
  17203. "Invalid configuration option value: %s",
  17204. config_options[NUM_THREADS].name);
  17205. }
  17206. free_context(ctx);
  17207. pthread_setspecific(sTlsKey, NULL);
  17208. return NULL;
  17209. }
  17210. /* Document root */
  17211. #if defined(NO_FILES)
  17212. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17213. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17214. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17215. mg_snprintf(NULL,
  17216. NULL, /* No truncation check for error buffers */
  17217. error->text,
  17218. error->text_buffer_size,
  17219. "Invalid configuration option value: %s",
  17220. config_options[DOCUMENT_ROOT].name);
  17221. }
  17222. free_context(ctx);
  17223. pthread_setspecific(sTlsKey, NULL);
  17224. return NULL;
  17225. }
  17226. #endif
  17227. get_system_name(&ctx->systemName);
  17228. #if defined(USE_LUA)
  17229. /* If a Lua background script has been configured, start it. */
  17230. ctx->lua_bg_log_available = 0;
  17231. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17232. char ebuf[256];
  17233. struct vec opt_vec;
  17234. struct vec eq_vec;
  17235. const char *sparams;
  17236. memset(ebuf, 0, sizeof(ebuf));
  17237. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17238. /* Create a Lua state, load all standard libraries and the mg table */
  17239. lua_State *state = mg_lua_context_script_prepare(
  17240. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17241. if (!state) {
  17242. mg_cry_ctx_internal(ctx,
  17243. "lua_background_script load error: %s",
  17244. ebuf);
  17245. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17246. mg_snprintf(NULL,
  17247. NULL, /* No truncation check for error buffers */
  17248. error->text,
  17249. error->text_buffer_size,
  17250. "Error in script %s: %s",
  17251. config_options[LUA_BACKGROUND_SCRIPT].name,
  17252. ebuf);
  17253. }
  17254. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17255. free_context(ctx);
  17256. pthread_setspecific(sTlsKey, NULL);
  17257. return NULL;
  17258. }
  17259. /* Add a table with parameters into mg.params */
  17260. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17261. if (sparams && sparams[0]) {
  17262. lua_getglobal(state, "mg");
  17263. lua_pushstring(state, "params");
  17264. lua_newtable(state);
  17265. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17266. != NULL) {
  17267. reg_llstring(
  17268. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17269. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17270. break;
  17271. }
  17272. lua_rawset(state, -3);
  17273. lua_pop(state, 1);
  17274. }
  17275. /* Call script */
  17276. state = mg_lua_context_script_run(state,
  17277. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17278. ctx,
  17279. ebuf,
  17280. sizeof(ebuf));
  17281. if (!state) {
  17282. mg_cry_ctx_internal(ctx,
  17283. "lua_background_script start error: %s",
  17284. ebuf);
  17285. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17286. mg_snprintf(NULL,
  17287. NULL, /* No truncation check for error buffers */
  17288. error->text,
  17289. error->text_buffer_size,
  17290. "Error in script %s: %s",
  17291. config_options[DOCUMENT_ROOT].name,
  17292. ebuf);
  17293. }
  17294. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17295. free_context(ctx);
  17296. pthread_setspecific(sTlsKey, NULL);
  17297. return NULL;
  17298. }
  17299. /* state remains valid */
  17300. ctx->lua_background_state = (void *)state;
  17301. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17302. } else {
  17303. ctx->lua_background_state = 0;
  17304. }
  17305. #endif
  17306. /* Step by step initialization of ctx - depending on build options */
  17307. #if !defined(NO_FILESYSTEMS)
  17308. if (!set_gpass_option(ctx, NULL)) {
  17309. const char *err_msg = "Invalid global password file";
  17310. /* Fatal error - abort start. */
  17311. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17312. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17313. mg_snprintf(NULL,
  17314. NULL, /* No truncation check for error buffers */
  17315. error->text,
  17316. error->text_buffer_size,
  17317. "%s",
  17318. err_msg);
  17319. }
  17320. free_context(ctx);
  17321. pthread_setspecific(sTlsKey, NULL);
  17322. return NULL;
  17323. }
  17324. #endif
  17325. #if defined(USE_MBEDTLS)
  17326. if (!mg_sslctx_init(ctx, NULL)) {
  17327. const char *err_msg = "Error initializing SSL context";
  17328. /* Fatal error - abort start. */
  17329. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17330. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17331. mg_snprintf(NULL,
  17332. NULL, /* No truncation check for error buffers */
  17333. error->text,
  17334. error->text_buffer_size,
  17335. "%s",
  17336. err_msg);
  17337. }
  17338. free_context(ctx);
  17339. pthread_setspecific(sTlsKey, NULL);
  17340. return NULL;
  17341. }
  17342. #elif !defined(NO_SSL)
  17343. if (!init_ssl_ctx(ctx, NULL)) {
  17344. const char *err_msg = "Error initializing SSL context";
  17345. /* Fatal error - abort start. */
  17346. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17347. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17348. mg_snprintf(NULL,
  17349. NULL, /* No truncation check for error buffers */
  17350. error->text,
  17351. error->text_buffer_size,
  17352. "%s",
  17353. err_msg);
  17354. }
  17355. free_context(ctx);
  17356. pthread_setspecific(sTlsKey, NULL);
  17357. return NULL;
  17358. }
  17359. #endif
  17360. if (!set_ports_option(ctx)) {
  17361. const char *err_msg = "Failed to setup server ports";
  17362. /* Fatal error - abort start. */
  17363. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17364. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17365. mg_snprintf(NULL,
  17366. NULL, /* No truncation check for error buffers */
  17367. error->text,
  17368. error->text_buffer_size,
  17369. "%s",
  17370. err_msg);
  17371. }
  17372. free_context(ctx);
  17373. pthread_setspecific(sTlsKey, NULL);
  17374. return NULL;
  17375. }
  17376. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17377. if (!set_uid_option(ctx)) {
  17378. const char *err_msg = "Failed to run as configured user";
  17379. /* Fatal error - abort start. */
  17380. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17381. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17382. mg_snprintf(NULL,
  17383. NULL, /* No truncation check for error buffers */
  17384. error->text,
  17385. error->text_buffer_size,
  17386. "%s",
  17387. err_msg);
  17388. }
  17389. free_context(ctx);
  17390. pthread_setspecific(sTlsKey, NULL);
  17391. return NULL;
  17392. }
  17393. #endif
  17394. if (!set_acl_option(ctx)) {
  17395. const char *err_msg = "Failed to setup access control list";
  17396. /* Fatal error - abort start. */
  17397. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17398. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17399. mg_snprintf(NULL,
  17400. NULL, /* No truncation check for error buffers */
  17401. error->text,
  17402. error->text_buffer_size,
  17403. "%s",
  17404. err_msg);
  17405. }
  17406. free_context(ctx);
  17407. pthread_setspecific(sTlsKey, NULL);
  17408. return NULL;
  17409. }
  17410. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17411. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17412. sizeof(pthread_t),
  17413. ctx);
  17414. if (ctx->worker_threadids == NULL) {
  17415. const char *err_msg = "Not enough memory for worker thread ID array";
  17416. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17417. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17418. mg_snprintf(NULL,
  17419. NULL, /* No truncation check for error buffers */
  17420. error->text,
  17421. error->text_buffer_size,
  17422. "%s",
  17423. err_msg);
  17424. }
  17425. free_context(ctx);
  17426. pthread_setspecific(sTlsKey, NULL);
  17427. return NULL;
  17428. }
  17429. ctx->worker_connections =
  17430. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17431. sizeof(struct mg_connection),
  17432. ctx);
  17433. if (ctx->worker_connections == NULL) {
  17434. const char *err_msg =
  17435. "Not enough memory for worker thread connection array";
  17436. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17437. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17438. mg_snprintf(NULL,
  17439. NULL, /* No truncation check for error buffers */
  17440. error->text,
  17441. error->text_buffer_size,
  17442. "%s",
  17443. err_msg);
  17444. }
  17445. free_context(ctx);
  17446. pthread_setspecific(sTlsKey, NULL);
  17447. return NULL;
  17448. }
  17449. #if defined(ALTERNATIVE_QUEUE)
  17450. ctx->client_wait_events =
  17451. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17452. sizeof(ctx->client_wait_events[0]),
  17453. ctx);
  17454. if (ctx->client_wait_events == NULL) {
  17455. const char *err_msg = "Not enough memory for worker event array";
  17456. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17457. mg_free(ctx->worker_threadids);
  17458. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17459. mg_snprintf(NULL,
  17460. NULL, /* No truncation check for error buffers */
  17461. error->text,
  17462. error->text_buffer_size,
  17463. "%s",
  17464. err_msg);
  17465. }
  17466. free_context(ctx);
  17467. pthread_setspecific(sTlsKey, NULL);
  17468. return NULL;
  17469. }
  17470. ctx->client_socks =
  17471. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17472. sizeof(ctx->client_socks[0]),
  17473. ctx);
  17474. if (ctx->client_socks == NULL) {
  17475. const char *err_msg = "Not enough memory for worker socket array";
  17476. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17477. mg_free(ctx->client_wait_events);
  17478. mg_free(ctx->worker_threadids);
  17479. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17480. mg_snprintf(NULL,
  17481. NULL, /* No truncation check for error buffers */
  17482. error->text,
  17483. error->text_buffer_size,
  17484. "%s",
  17485. err_msg);
  17486. }
  17487. free_context(ctx);
  17488. pthread_setspecific(sTlsKey, NULL);
  17489. return NULL;
  17490. }
  17491. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17492. ctx->client_wait_events[i] = event_create();
  17493. if (ctx->client_wait_events[i] == 0) {
  17494. const char *err_msg = "Error creating worker event %i";
  17495. mg_cry_ctx_internal(ctx, err_msg, i);
  17496. while (i > 0) {
  17497. i--;
  17498. event_destroy(ctx->client_wait_events[i]);
  17499. }
  17500. mg_free(ctx->client_socks);
  17501. mg_free(ctx->client_wait_events);
  17502. mg_free(ctx->worker_threadids);
  17503. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17504. mg_snprintf(NULL,
  17505. NULL, /* No truncation check for error buffers */
  17506. error->text,
  17507. error->text_buffer_size,
  17508. err_msg,
  17509. i);
  17510. }
  17511. free_context(ctx);
  17512. pthread_setspecific(sTlsKey, NULL);
  17513. return NULL;
  17514. }
  17515. }
  17516. #endif
  17517. #if defined(USE_TIMERS)
  17518. if (timers_init(ctx) != 0) {
  17519. const char *err_msg = "Error creating timers";
  17520. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17521. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17522. mg_snprintf(NULL,
  17523. NULL, /* No truncation check for error buffers */
  17524. error->text,
  17525. error->text_buffer_size,
  17526. "%s",
  17527. err_msg);
  17528. }
  17529. free_context(ctx);
  17530. pthread_setspecific(sTlsKey, NULL);
  17531. return NULL;
  17532. }
  17533. #endif
  17534. /* Context has been created - init user libraries */
  17535. if (ctx->callbacks.init_context) {
  17536. ctx->callbacks.init_context(ctx);
  17537. }
  17538. /* From now, the context is successfully created.
  17539. * When it is destroyed, the exit callback should be called. */
  17540. ctx->callbacks.exit_context = exit_callback;
  17541. ctx->context_type = CONTEXT_SERVER; /* server context */
  17542. /* Start worker threads */
  17543. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17544. /* worker_thread sets up the other fields */
  17545. ctx->worker_connections[i].phys_ctx = ctx;
  17546. if (mg_start_thread_with_id(worker_thread,
  17547. &ctx->worker_connections[i],
  17548. &ctx->worker_threadids[i])
  17549. != 0) {
  17550. long error_no = (long)ERRNO;
  17551. /* thread was not created */
  17552. if (i > 0) {
  17553. /* If the second, third, ... thread cannot be created, set a
  17554. * warning, but keep running. */
  17555. mg_cry_ctx_internal(ctx,
  17556. "Cannot start worker thread %i: error %ld",
  17557. i + 1,
  17558. error_no);
  17559. /* If the server initialization should stop here, all
  17560. * threads that have already been created must be stopped
  17561. * first, before any free_context(ctx) call.
  17562. */
  17563. } else {
  17564. /* If the first worker thread cannot be created, stop
  17565. * initialization and free the entire server context. */
  17566. mg_cry_ctx_internal(ctx,
  17567. "Cannot create threads: error %ld",
  17568. error_no);
  17569. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17570. mg_snprintf(
  17571. NULL,
  17572. NULL, /* No truncation check for error buffers */
  17573. error->text,
  17574. error->text_buffer_size,
  17575. "Cannot create first worker thread: error %ld",
  17576. error_no);
  17577. }
  17578. free_context(ctx);
  17579. pthread_setspecific(sTlsKey, NULL);
  17580. return NULL;
  17581. }
  17582. break;
  17583. }
  17584. }
  17585. /* Start master (listening) thread */
  17586. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17587. pthread_setspecific(sTlsKey, NULL);
  17588. return ctx;
  17589. }
  17590. struct mg_context *
  17591. mg_start(const struct mg_callbacks *callbacks,
  17592. void *user_data,
  17593. const char **options)
  17594. {
  17595. struct mg_init_data init = {0};
  17596. init.callbacks = callbacks;
  17597. init.user_data = user_data;
  17598. init.configuration_options = options;
  17599. return mg_start2(&init, NULL);
  17600. }
  17601. /* Add an additional domain to an already running web server. */
  17602. int
  17603. mg_start_domain2(struct mg_context *ctx,
  17604. const char **options,
  17605. struct mg_error_data *error)
  17606. {
  17607. const char *name;
  17608. const char *value;
  17609. const char *default_value;
  17610. struct mg_domain_context *new_dom;
  17611. struct mg_domain_context *dom;
  17612. int idx, i;
  17613. if (error != NULL) {
  17614. error->code = 0;
  17615. if (error->text_buffer_size > 0) {
  17616. *error->text = 0;
  17617. }
  17618. }
  17619. if ((ctx == NULL) || (options == NULL)) {
  17620. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17621. mg_snprintf(NULL,
  17622. NULL, /* No truncation check for error buffers */
  17623. error->text,
  17624. error->text_buffer_size,
  17625. "%s",
  17626. "Invalid parameters");
  17627. }
  17628. return -1;
  17629. }
  17630. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17631. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17632. mg_snprintf(NULL,
  17633. NULL, /* No truncation check for error buffers */
  17634. error->text,
  17635. error->text_buffer_size,
  17636. "%s",
  17637. "Server already stopped");
  17638. }
  17639. return -1;
  17640. }
  17641. new_dom = (struct mg_domain_context *)
  17642. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17643. if (!new_dom) {
  17644. /* Out of memory */
  17645. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17646. mg_snprintf(NULL,
  17647. NULL, /* No truncation check for error buffers */
  17648. error->text,
  17649. error->text_buffer_size,
  17650. "%s",
  17651. "Out or memory");
  17652. }
  17653. return -6;
  17654. }
  17655. /* Store options - TODO: unite duplicate code */
  17656. while (options && (name = *options++) != NULL) {
  17657. if ((idx = get_option_index(name)) == -1) {
  17658. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17659. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17660. mg_snprintf(NULL,
  17661. NULL, /* No truncation check for error buffers */
  17662. error->text,
  17663. error->text_buffer_size,
  17664. "Invalid option: %s",
  17665. name);
  17666. }
  17667. mg_free(new_dom);
  17668. return -2;
  17669. } else if ((value = *options++) == NULL) {
  17670. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17671. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17672. mg_snprintf(NULL,
  17673. NULL, /* No truncation check for error buffers */
  17674. error->text,
  17675. error->text_buffer_size,
  17676. "Invalid option value: %s",
  17677. name);
  17678. }
  17679. mg_free(new_dom);
  17680. return -2;
  17681. }
  17682. if (new_dom->config[idx] != NULL) {
  17683. /* Duplicate option: Later values overwrite earlier ones. */
  17684. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17685. mg_free(new_dom->config[idx]);
  17686. }
  17687. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17688. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17689. }
  17690. /* Authentication domain is mandatory */
  17691. /* TODO: Maybe use a new option hostname? */
  17692. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17693. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17694. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17695. mg_snprintf(NULL,
  17696. NULL, /* No truncation check for error buffers */
  17697. error->text,
  17698. error->text_buffer_size,
  17699. "Mandatory option %s missing",
  17700. config_options[AUTHENTICATION_DOMAIN].name);
  17701. }
  17702. mg_free(new_dom);
  17703. return -4;
  17704. }
  17705. /* Set default value if needed. Take the config value from
  17706. * ctx as a default value. */
  17707. for (i = 0; config_options[i].name != NULL; i++) {
  17708. default_value = ctx->dd.config[i];
  17709. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17710. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17711. }
  17712. }
  17713. new_dom->handlers = NULL;
  17714. new_dom->next = NULL;
  17715. new_dom->nonce_count = 0;
  17716. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  17717. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17718. new_dom->shared_lua_websockets = NULL;
  17719. #endif
  17720. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  17721. if (!init_ssl_ctx(ctx, new_dom)) {
  17722. /* Init SSL failed */
  17723. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17724. mg_snprintf(NULL,
  17725. NULL, /* No truncation check for error buffers */
  17726. error->text,
  17727. error->text_buffer_size,
  17728. "%s",
  17729. "Initializing SSL context failed");
  17730. }
  17731. mg_free(new_dom);
  17732. return -3;
  17733. }
  17734. #endif
  17735. /* Add element to linked list. */
  17736. mg_lock_context(ctx);
  17737. idx = 0;
  17738. dom = &(ctx->dd);
  17739. for (;;) {
  17740. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17741. dom->config[AUTHENTICATION_DOMAIN])) {
  17742. /* Domain collision */
  17743. mg_cry_ctx_internal(ctx,
  17744. "domain %s already in use",
  17745. new_dom->config[AUTHENTICATION_DOMAIN]);
  17746. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17747. mg_snprintf(NULL,
  17748. NULL, /* No truncation check for error buffers */
  17749. error->text,
  17750. error->text_buffer_size,
  17751. "Domain %s specified by %s is already in use",
  17752. new_dom->config[AUTHENTICATION_DOMAIN],
  17753. config_options[AUTHENTICATION_DOMAIN].name);
  17754. }
  17755. mg_free(new_dom);
  17756. mg_unlock_context(ctx);
  17757. return -5;
  17758. }
  17759. /* Count number of domains */
  17760. idx++;
  17761. if (dom->next == NULL) {
  17762. dom->next = new_dom;
  17763. break;
  17764. }
  17765. dom = dom->next;
  17766. }
  17767. mg_unlock_context(ctx);
  17768. /* Return domain number */
  17769. return idx;
  17770. }
  17771. int
  17772. mg_start_domain(struct mg_context *ctx, const char **options)
  17773. {
  17774. return mg_start_domain2(ctx, options, NULL);
  17775. }
  17776. /* Feature check API function */
  17777. unsigned
  17778. mg_check_feature(unsigned feature)
  17779. {
  17780. static const unsigned feature_set = 0
  17781. /* Set bits for available features according to API documentation.
  17782. * This bit mask is created at compile time, according to the active
  17783. * preprocessor defines. It is a single const value at runtime. */
  17784. #if !defined(NO_FILES)
  17785. | MG_FEATURES_FILES
  17786. #endif
  17787. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17788. | MG_FEATURES_SSL
  17789. #endif
  17790. #if !defined(NO_CGI)
  17791. | MG_FEATURES_CGI
  17792. #endif
  17793. #if defined(USE_IPV6)
  17794. | MG_FEATURES_IPV6
  17795. #endif
  17796. #if defined(USE_WEBSOCKET)
  17797. | MG_FEATURES_WEBSOCKET
  17798. #endif
  17799. #if defined(USE_LUA)
  17800. | MG_FEATURES_LUA
  17801. #endif
  17802. #if defined(USE_DUKTAPE)
  17803. | MG_FEATURES_SSJS
  17804. #endif
  17805. #if !defined(NO_CACHING)
  17806. | MG_FEATURES_CACHE
  17807. #endif
  17808. #if defined(USE_SERVER_STATS)
  17809. | MG_FEATURES_STATS
  17810. #endif
  17811. #if defined(USE_ZLIB)
  17812. | MG_FEATURES_COMPRESSION
  17813. #endif
  17814. #if defined(USE_HTTP2)
  17815. | MG_FEATURES_HTTP2
  17816. #endif
  17817. #if defined(USE_X_DOM_SOCKET)
  17818. | MG_FEATURES_X_DOMAIN_SOCKET
  17819. #endif
  17820. /* Set some extra bits not defined in the API documentation.
  17821. * These bits may change without further notice. */
  17822. #if defined(MG_LEGACY_INTERFACE)
  17823. | 0x80000000u
  17824. #endif
  17825. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17826. | 0x40000000u
  17827. #endif
  17828. #if !defined(NO_RESPONSE_BUFFERING)
  17829. | 0x20000000u
  17830. #endif
  17831. #if defined(MEMORY_DEBUGGING)
  17832. | 0x10000000u
  17833. #endif
  17834. ;
  17835. return (feature & feature_set);
  17836. }
  17837. static size_t
  17838. mg_str_append(char **dst, char *end, const char *src)
  17839. {
  17840. size_t len = strlen(src);
  17841. if (*dst != end) {
  17842. /* Append src if enough space, or close dst. */
  17843. if ((size_t)(end - *dst) > len) {
  17844. strcpy(*dst, src);
  17845. *dst += len;
  17846. } else {
  17847. *dst = end;
  17848. }
  17849. }
  17850. return len;
  17851. }
  17852. /* Get system information. It can be printed or stored by the caller.
  17853. * Return the size of available information. */
  17854. int
  17855. mg_get_system_info(char *buffer, int buflen)
  17856. {
  17857. char *end, *append_eoobj = NULL, block[256];
  17858. size_t system_info_length = 0;
  17859. #if defined(_WIN32)
  17860. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17861. #else
  17862. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17863. #endif
  17864. if ((buffer == NULL) || (buflen < 1)) {
  17865. buflen = 0;
  17866. end = buffer;
  17867. } else {
  17868. *buffer = 0;
  17869. end = buffer + buflen;
  17870. }
  17871. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17872. /* has enough space to append eoobj */
  17873. append_eoobj = buffer;
  17874. if (end) {
  17875. end -= sizeof(eoobj) - 1;
  17876. }
  17877. }
  17878. system_info_length += mg_str_append(&buffer, end, "{");
  17879. /* Server version */
  17880. {
  17881. const char *version = mg_version();
  17882. mg_snprintf(NULL,
  17883. NULL,
  17884. block,
  17885. sizeof(block),
  17886. "%s\"version\" : \"%s\"",
  17887. eol,
  17888. version);
  17889. system_info_length += mg_str_append(&buffer, end, block);
  17890. }
  17891. /* System info */
  17892. {
  17893. #if defined(_WIN32)
  17894. DWORD dwVersion = 0;
  17895. DWORD dwMajorVersion = 0;
  17896. DWORD dwMinorVersion = 0;
  17897. SYSTEM_INFO si;
  17898. GetSystemInfo(&si);
  17899. #if defined(_MSC_VER)
  17900. #pragma warning(push)
  17901. /* GetVersion was declared deprecated */
  17902. #pragma warning(disable : 4996)
  17903. #endif
  17904. dwVersion = GetVersion();
  17905. #if defined(_MSC_VER)
  17906. #pragma warning(pop)
  17907. #endif
  17908. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17909. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17910. mg_snprintf(NULL,
  17911. NULL,
  17912. block,
  17913. sizeof(block),
  17914. ",%s\"os\" : \"Windows %u.%u\"",
  17915. eol,
  17916. (unsigned)dwMajorVersion,
  17917. (unsigned)dwMinorVersion);
  17918. system_info_length += mg_str_append(&buffer, end, block);
  17919. mg_snprintf(NULL,
  17920. NULL,
  17921. block,
  17922. sizeof(block),
  17923. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17924. eol,
  17925. (unsigned)si.wProcessorArchitecture,
  17926. (unsigned)si.dwNumberOfProcessors,
  17927. (unsigned)si.dwActiveProcessorMask);
  17928. system_info_length += mg_str_append(&buffer, end, block);
  17929. #elif defined(__ZEPHYR__)
  17930. mg_snprintf(NULL,
  17931. NULL,
  17932. block,
  17933. sizeof(block),
  17934. ",%s\"os\" : \"%s %s\"",
  17935. eol,
  17936. "Zephyr OS",
  17937. ZEPHYR_VERSION);
  17938. system_info_length += mg_str_append(&buffer, end, block);
  17939. #else
  17940. struct utsname name;
  17941. memset(&name, 0, sizeof(name));
  17942. uname(&name);
  17943. mg_snprintf(NULL,
  17944. NULL,
  17945. block,
  17946. sizeof(block),
  17947. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17948. eol,
  17949. name.sysname,
  17950. name.version,
  17951. name.release,
  17952. name.machine);
  17953. system_info_length += mg_str_append(&buffer, end, block);
  17954. #endif
  17955. }
  17956. /* Features */
  17957. {
  17958. mg_snprintf(NULL,
  17959. NULL,
  17960. block,
  17961. sizeof(block),
  17962. ",%s\"features\" : %lu"
  17963. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17964. eol,
  17965. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17966. eol,
  17967. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17968. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17969. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17970. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17971. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17972. : "",
  17973. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17974. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17975. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17976. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17977. system_info_length += mg_str_append(&buffer, end, block);
  17978. #if defined(USE_LUA)
  17979. mg_snprintf(NULL,
  17980. NULL,
  17981. block,
  17982. sizeof(block),
  17983. ",%s\"lua_version\" : \"%u (%s)\"",
  17984. eol,
  17985. (unsigned)LUA_VERSION_NUM,
  17986. LUA_RELEASE);
  17987. system_info_length += mg_str_append(&buffer, end, block);
  17988. #endif
  17989. #if defined(USE_DUKTAPE)
  17990. mg_snprintf(NULL,
  17991. NULL,
  17992. block,
  17993. sizeof(block),
  17994. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17995. eol,
  17996. (unsigned)DUK_VERSION / 10000,
  17997. ((unsigned)DUK_VERSION / 100) % 100,
  17998. (unsigned)DUK_VERSION % 100);
  17999. system_info_length += mg_str_append(&buffer, end, block);
  18000. #endif
  18001. }
  18002. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18003. {
  18004. #if defined(BUILD_DATE)
  18005. const char *bd = BUILD_DATE;
  18006. #else
  18007. #if defined(GCC_DIAGNOSTIC)
  18008. #if GCC_VERSION >= 40900
  18009. #pragma GCC diagnostic push
  18010. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18011. * does not work in some versions. If "BUILD_DATE" is defined to some
  18012. * string, it is used instead of __DATE__. */
  18013. #pragma GCC diagnostic ignored "-Wdate-time"
  18014. #endif
  18015. #endif
  18016. const char *bd = __DATE__;
  18017. #if defined(GCC_DIAGNOSTIC)
  18018. #if GCC_VERSION >= 40900
  18019. #pragma GCC diagnostic pop
  18020. #endif
  18021. #endif
  18022. #endif
  18023. mg_snprintf(
  18024. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18025. system_info_length += mg_str_append(&buffer, end, block);
  18026. }
  18027. /* Compiler information */
  18028. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18029. {
  18030. #if defined(_MSC_VER)
  18031. mg_snprintf(NULL,
  18032. NULL,
  18033. block,
  18034. sizeof(block),
  18035. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18036. eol,
  18037. (unsigned)_MSC_VER,
  18038. (unsigned)_MSC_FULL_VER);
  18039. system_info_length += mg_str_append(&buffer, end, block);
  18040. #elif defined(__MINGW64__)
  18041. mg_snprintf(NULL,
  18042. NULL,
  18043. block,
  18044. sizeof(block),
  18045. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18046. eol,
  18047. (unsigned)__MINGW64_VERSION_MAJOR,
  18048. (unsigned)__MINGW64_VERSION_MINOR);
  18049. system_info_length += mg_str_append(&buffer, end, block);
  18050. mg_snprintf(NULL,
  18051. NULL,
  18052. block,
  18053. sizeof(block),
  18054. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18055. eol,
  18056. (unsigned)__MINGW32_MAJOR_VERSION,
  18057. (unsigned)__MINGW32_MINOR_VERSION);
  18058. system_info_length += mg_str_append(&buffer, end, block);
  18059. #elif defined(__MINGW32__)
  18060. mg_snprintf(NULL,
  18061. NULL,
  18062. block,
  18063. sizeof(block),
  18064. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18065. eol,
  18066. (unsigned)__MINGW32_MAJOR_VERSION,
  18067. (unsigned)__MINGW32_MINOR_VERSION);
  18068. system_info_length += mg_str_append(&buffer, end, block);
  18069. #elif defined(__clang__)
  18070. mg_snprintf(NULL,
  18071. NULL,
  18072. block,
  18073. sizeof(block),
  18074. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18075. eol,
  18076. __clang_major__,
  18077. __clang_minor__,
  18078. __clang_patchlevel__,
  18079. __clang_version__);
  18080. system_info_length += mg_str_append(&buffer, end, block);
  18081. #elif defined(__GNUC__)
  18082. mg_snprintf(NULL,
  18083. NULL,
  18084. block,
  18085. sizeof(block),
  18086. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18087. eol,
  18088. (unsigned)__GNUC__,
  18089. (unsigned)__GNUC_MINOR__,
  18090. (unsigned)__GNUC_PATCHLEVEL__);
  18091. system_info_length += mg_str_append(&buffer, end, block);
  18092. #elif defined(__INTEL_COMPILER)
  18093. mg_snprintf(NULL,
  18094. NULL,
  18095. block,
  18096. sizeof(block),
  18097. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18098. eol,
  18099. (unsigned)__INTEL_COMPILER);
  18100. system_info_length += mg_str_append(&buffer, end, block);
  18101. #elif defined(__BORLANDC__)
  18102. mg_snprintf(NULL,
  18103. NULL,
  18104. block,
  18105. sizeof(block),
  18106. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18107. eol,
  18108. (unsigned)__BORLANDC__);
  18109. system_info_length += mg_str_append(&buffer, end, block);
  18110. #elif defined(__SUNPRO_C)
  18111. mg_snprintf(NULL,
  18112. NULL,
  18113. block,
  18114. sizeof(block),
  18115. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18116. eol,
  18117. (unsigned)__SUNPRO_C);
  18118. system_info_length += mg_str_append(&buffer, end, block);
  18119. #else
  18120. mg_snprintf(NULL,
  18121. NULL,
  18122. block,
  18123. sizeof(block),
  18124. ",%s\"compiler\" : \"other\"",
  18125. eol);
  18126. system_info_length += mg_str_append(&buffer, end, block);
  18127. #endif
  18128. }
  18129. /* Determine 32/64 bit data mode.
  18130. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18131. {
  18132. mg_snprintf(NULL,
  18133. NULL,
  18134. block,
  18135. sizeof(block),
  18136. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18137. "char:%u/%u, "
  18138. "ptr:%u, size:%u, time:%u\"",
  18139. eol,
  18140. (unsigned)sizeof(short),
  18141. (unsigned)sizeof(int),
  18142. (unsigned)sizeof(long),
  18143. (unsigned)sizeof(long long),
  18144. (unsigned)sizeof(float),
  18145. (unsigned)sizeof(double),
  18146. (unsigned)sizeof(long double),
  18147. (unsigned)sizeof(char),
  18148. (unsigned)sizeof(wchar_t),
  18149. (unsigned)sizeof(void *),
  18150. (unsigned)sizeof(size_t),
  18151. (unsigned)sizeof(time_t));
  18152. system_info_length += mg_str_append(&buffer, end, block);
  18153. }
  18154. /* Terminate string */
  18155. if (append_eoobj) {
  18156. strcat(append_eoobj, eoobj);
  18157. }
  18158. system_info_length += sizeof(eoobj) - 1;
  18159. return (int)system_info_length;
  18160. }
  18161. /* Get context information. It can be printed or stored by the caller.
  18162. * Return the size of available information. */
  18163. int
  18164. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18165. {
  18166. #if defined(USE_SERVER_STATS)
  18167. char *end, *append_eoobj = NULL, block[256];
  18168. size_t context_info_length = 0;
  18169. #if defined(_WIN32)
  18170. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18171. #else
  18172. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18173. #endif
  18174. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18175. if ((buffer == NULL) || (buflen < 1)) {
  18176. buflen = 0;
  18177. end = buffer;
  18178. } else {
  18179. *buffer = 0;
  18180. end = buffer + buflen;
  18181. }
  18182. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18183. /* has enough space to append eoobj */
  18184. append_eoobj = buffer;
  18185. end -= sizeof(eoobj) - 1;
  18186. }
  18187. context_info_length += mg_str_append(&buffer, end, "{");
  18188. if (ms) { /* <-- should be always true */
  18189. /* Memory information */
  18190. int blockCount = (int)ms->blockCount;
  18191. int64_t totalMemUsed = ms->totalMemUsed;
  18192. int64_t maxMemUsed = ms->maxMemUsed;
  18193. if (totalMemUsed > maxMemUsed) {
  18194. maxMemUsed = totalMemUsed;
  18195. }
  18196. mg_snprintf(NULL,
  18197. NULL,
  18198. block,
  18199. sizeof(block),
  18200. "%s\"memory\" : {%s"
  18201. "\"blocks\" : %i,%s"
  18202. "\"used\" : %" INT64_FMT ",%s"
  18203. "\"maxUsed\" : %" INT64_FMT "%s"
  18204. "}",
  18205. eol,
  18206. eol,
  18207. blockCount,
  18208. eol,
  18209. totalMemUsed,
  18210. eol,
  18211. maxMemUsed,
  18212. eol);
  18213. context_info_length += mg_str_append(&buffer, end, block);
  18214. }
  18215. if (ctx) {
  18216. /* Declare all variables at begin of the block, to comply
  18217. * with old C standards. */
  18218. char start_time_str[64] = {0};
  18219. char now_str[64] = {0};
  18220. time_t start_time = ctx->start_time;
  18221. time_t now = time(NULL);
  18222. int64_t total_data_read, total_data_written;
  18223. int active_connections = (int)ctx->active_connections;
  18224. int max_active_connections = (int)ctx->max_active_connections;
  18225. int total_connections = (int)ctx->total_connections;
  18226. if (active_connections > max_active_connections) {
  18227. max_active_connections = active_connections;
  18228. }
  18229. if (active_connections > total_connections) {
  18230. total_connections = active_connections;
  18231. }
  18232. /* Connections information */
  18233. mg_snprintf(NULL,
  18234. NULL,
  18235. block,
  18236. sizeof(block),
  18237. ",%s\"connections\" : {%s"
  18238. "\"active\" : %i,%s"
  18239. "\"maxActive\" : %i,%s"
  18240. "\"total\" : %i%s"
  18241. "}",
  18242. eol,
  18243. eol,
  18244. active_connections,
  18245. eol,
  18246. max_active_connections,
  18247. eol,
  18248. total_connections,
  18249. eol);
  18250. context_info_length += mg_str_append(&buffer, end, block);
  18251. /* Queue information */
  18252. #if !defined(ALTERNATIVE_QUEUE)
  18253. mg_snprintf(NULL,
  18254. NULL,
  18255. block,
  18256. sizeof(block),
  18257. ",%s\"queue\" : {%s"
  18258. "\"length\" : %i,%s"
  18259. "\"filled\" : %i,%s"
  18260. "\"maxFilled\" : %i,%s"
  18261. "\"full\" : %s%s"
  18262. "}",
  18263. eol,
  18264. eol,
  18265. ctx->sq_size,
  18266. eol,
  18267. ctx->sq_head - ctx->sq_tail,
  18268. eol,
  18269. ctx->sq_max_fill,
  18270. eol,
  18271. (ctx->sq_blocked ? "true" : "false"),
  18272. eol);
  18273. context_info_length += mg_str_append(&buffer, end, block);
  18274. #endif
  18275. /* Requests information */
  18276. mg_snprintf(NULL,
  18277. NULL,
  18278. block,
  18279. sizeof(block),
  18280. ",%s\"requests\" : {%s"
  18281. "\"total\" : %lu%s"
  18282. "}",
  18283. eol,
  18284. eol,
  18285. (unsigned long)ctx->total_requests,
  18286. eol);
  18287. context_info_length += mg_str_append(&buffer, end, block);
  18288. /* Data information */
  18289. total_data_read =
  18290. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18291. total_data_written =
  18292. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18293. mg_snprintf(NULL,
  18294. NULL,
  18295. block,
  18296. sizeof(block),
  18297. ",%s\"data\" : {%s"
  18298. "\"read\" : %" INT64_FMT ",%s"
  18299. "\"written\" : %" INT64_FMT "%s"
  18300. "}",
  18301. eol,
  18302. eol,
  18303. total_data_read,
  18304. eol,
  18305. total_data_written,
  18306. eol);
  18307. context_info_length += mg_str_append(&buffer, end, block);
  18308. /* Execution time information */
  18309. gmt_time_string(start_time_str,
  18310. sizeof(start_time_str) - 1,
  18311. &start_time);
  18312. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18313. mg_snprintf(NULL,
  18314. NULL,
  18315. block,
  18316. sizeof(block),
  18317. ",%s\"time\" : {%s"
  18318. "\"uptime\" : %.0f,%s"
  18319. "\"start\" : \"%s\",%s"
  18320. "\"now\" : \"%s\"%s"
  18321. "}",
  18322. eol,
  18323. eol,
  18324. difftime(now, start_time),
  18325. eol,
  18326. start_time_str,
  18327. eol,
  18328. now_str,
  18329. eol);
  18330. context_info_length += mg_str_append(&buffer, end, block);
  18331. }
  18332. /* Terminate string */
  18333. if (append_eoobj) {
  18334. strcat(append_eoobj, eoobj);
  18335. }
  18336. context_info_length += sizeof(eoobj) - 1;
  18337. return (int)context_info_length;
  18338. #else
  18339. (void)ctx;
  18340. if ((buffer != NULL) && (buflen > 0)) {
  18341. *buffer = 0;
  18342. }
  18343. return 0;
  18344. #endif
  18345. }
  18346. void
  18347. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18348. {
  18349. /* https://github.com/civetweb/civetweb/issues/727 */
  18350. if (conn != NULL) {
  18351. conn->must_close = 1;
  18352. }
  18353. }
  18354. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18355. /* Get connection information. It can be printed or stored by the caller.
  18356. * Return the size of available information. */
  18357. int
  18358. mg_get_connection_info(const struct mg_context *ctx,
  18359. int idx,
  18360. char *buffer,
  18361. int buflen)
  18362. {
  18363. const struct mg_connection *conn;
  18364. const struct mg_request_info *ri;
  18365. char *end, *append_eoobj = NULL, block[256];
  18366. size_t connection_info_length = 0;
  18367. int state = 0;
  18368. const char *state_str = "unknown";
  18369. #if defined(_WIN32)
  18370. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18371. #else
  18372. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18373. #endif
  18374. if ((buffer == NULL) || (buflen < 1)) {
  18375. buflen = 0;
  18376. end = buffer;
  18377. } else {
  18378. *buffer = 0;
  18379. end = buffer + buflen;
  18380. }
  18381. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18382. /* has enough space to append eoobj */
  18383. append_eoobj = buffer;
  18384. end -= sizeof(eoobj) - 1;
  18385. }
  18386. if ((ctx == NULL) || (idx < 0)) {
  18387. /* Parameter error */
  18388. return 0;
  18389. }
  18390. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18391. /* Out of range */
  18392. return 0;
  18393. }
  18394. /* Take connection [idx]. This connection is not locked in
  18395. * any way, so some other thread might use it. */
  18396. conn = (ctx->worker_connections) + idx;
  18397. /* Initialize output string */
  18398. connection_info_length += mg_str_append(&buffer, end, "{");
  18399. /* Init variables */
  18400. ri = &(conn->request_info);
  18401. #if defined(USE_SERVER_STATS)
  18402. state = conn->conn_state;
  18403. /* State as string */
  18404. switch (state) {
  18405. case 0:
  18406. state_str = "undefined";
  18407. break;
  18408. case 1:
  18409. state_str = "not used";
  18410. break;
  18411. case 2:
  18412. state_str = "init";
  18413. break;
  18414. case 3:
  18415. state_str = "ready";
  18416. break;
  18417. case 4:
  18418. state_str = "processing";
  18419. break;
  18420. case 5:
  18421. state_str = "processed";
  18422. break;
  18423. case 6:
  18424. state_str = "to close";
  18425. break;
  18426. case 7:
  18427. state_str = "closing";
  18428. break;
  18429. case 8:
  18430. state_str = "closed";
  18431. break;
  18432. case 9:
  18433. state_str = "done";
  18434. break;
  18435. }
  18436. #endif
  18437. /* Connection info */
  18438. if ((state >= 3) && (state < 9)) {
  18439. mg_snprintf(NULL,
  18440. NULL,
  18441. block,
  18442. sizeof(block),
  18443. "%s\"connection\" : {%s"
  18444. "\"remote\" : {%s"
  18445. "\"protocol\" : \"%s\",%s"
  18446. "\"addr\" : \"%s\",%s"
  18447. "\"port\" : %u%s"
  18448. "},%s"
  18449. "\"handled_requests\" : %u%s"
  18450. "}",
  18451. eol,
  18452. eol,
  18453. eol,
  18454. get_proto_name(conn),
  18455. eol,
  18456. ri->remote_addr,
  18457. eol,
  18458. ri->remote_port,
  18459. eol,
  18460. eol,
  18461. conn->handled_requests,
  18462. eol);
  18463. connection_info_length += mg_str_append(&buffer, end, block);
  18464. }
  18465. /* Request info */
  18466. if ((state >= 4) && (state < 6)) {
  18467. mg_snprintf(NULL,
  18468. NULL,
  18469. block,
  18470. sizeof(block),
  18471. "%s%s\"request_info\" : {%s"
  18472. "\"method\" : \"%s\",%s"
  18473. "\"uri\" : \"%s\",%s"
  18474. "\"query\" : %s%s%s%s"
  18475. "}",
  18476. (connection_info_length > 1 ? "," : ""),
  18477. eol,
  18478. eol,
  18479. ri->request_method,
  18480. eol,
  18481. ri->request_uri,
  18482. eol,
  18483. ri->query_string ? "\"" : "",
  18484. ri->query_string ? ri->query_string : "null",
  18485. ri->query_string ? "\"" : "",
  18486. eol);
  18487. connection_info_length += mg_str_append(&buffer, end, block);
  18488. }
  18489. /* Execution time information */
  18490. if ((state >= 2) && (state < 9)) {
  18491. char start_time_str[64] = {0};
  18492. char close_time_str[64] = {0};
  18493. time_t start_time = conn->conn_birth_time;
  18494. time_t close_time = 0;
  18495. double time_diff;
  18496. gmt_time_string(start_time_str,
  18497. sizeof(start_time_str) - 1,
  18498. &start_time);
  18499. #if defined(USE_SERVER_STATS)
  18500. close_time = conn->conn_close_time;
  18501. #endif
  18502. if (close_time != 0) {
  18503. time_diff = difftime(close_time, start_time);
  18504. gmt_time_string(close_time_str,
  18505. sizeof(close_time_str) - 1,
  18506. &close_time);
  18507. } else {
  18508. time_t now = time(NULL);
  18509. time_diff = difftime(now, start_time);
  18510. close_time_str[0] = 0; /* or use "now" ? */
  18511. }
  18512. mg_snprintf(NULL,
  18513. NULL,
  18514. block,
  18515. sizeof(block),
  18516. "%s%s\"time\" : {%s"
  18517. "\"uptime\" : %.0f,%s"
  18518. "\"start\" : \"%s\",%s"
  18519. "\"closed\" : \"%s\"%s"
  18520. "}",
  18521. (connection_info_length > 1 ? "," : ""),
  18522. eol,
  18523. eol,
  18524. time_diff,
  18525. eol,
  18526. start_time_str,
  18527. eol,
  18528. close_time_str,
  18529. eol);
  18530. connection_info_length += mg_str_append(&buffer, end, block);
  18531. }
  18532. /* Remote user name */
  18533. if ((ri->remote_user) && (state < 9)) {
  18534. mg_snprintf(NULL,
  18535. NULL,
  18536. block,
  18537. sizeof(block),
  18538. "%s%s\"user\" : {%s"
  18539. "\"name\" : \"%s\",%s"
  18540. "}",
  18541. (connection_info_length > 1 ? "," : ""),
  18542. eol,
  18543. eol,
  18544. ri->remote_user,
  18545. eol);
  18546. connection_info_length += mg_str_append(&buffer, end, block);
  18547. }
  18548. /* Data block */
  18549. if (state >= 3) {
  18550. mg_snprintf(NULL,
  18551. NULL,
  18552. block,
  18553. sizeof(block),
  18554. "%s%s\"data\" : {%s"
  18555. "\"read\" : %" INT64_FMT ",%s"
  18556. "\"written\" : %" INT64_FMT "%s"
  18557. "}",
  18558. (connection_info_length > 1 ? "," : ""),
  18559. eol,
  18560. eol,
  18561. conn->consumed_content,
  18562. eol,
  18563. conn->num_bytes_sent,
  18564. eol);
  18565. connection_info_length += mg_str_append(&buffer, end, block);
  18566. }
  18567. /* State */
  18568. mg_snprintf(NULL,
  18569. NULL,
  18570. block,
  18571. sizeof(block),
  18572. "%s%s\"state\" : \"%s\"",
  18573. (connection_info_length > 1 ? "," : ""),
  18574. eol,
  18575. state_str);
  18576. connection_info_length += mg_str_append(&buffer, end, block);
  18577. /* Terminate string */
  18578. if (append_eoobj) {
  18579. strcat(append_eoobj, eoobj);
  18580. }
  18581. connection_info_length += sizeof(eoobj) - 1;
  18582. return (int)connection_info_length;
  18583. }
  18584. #endif
  18585. /* Initialize this library. This function does not need to be thread safe.
  18586. */
  18587. unsigned
  18588. mg_init_library(unsigned features)
  18589. {
  18590. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18591. unsigned features_inited = features_to_init;
  18592. if (mg_init_library_called <= 0) {
  18593. /* Not initialized yet */
  18594. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18595. return 0;
  18596. }
  18597. }
  18598. mg_global_lock();
  18599. if (mg_init_library_called <= 0) {
  18600. #if defined(_WIN32)
  18601. int file_mutex_init = 1;
  18602. int wsa = 1;
  18603. #else
  18604. int mutexattr_init = 1;
  18605. #endif
  18606. int failed = 1;
  18607. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18608. if (key_create == 0) {
  18609. #if defined(_WIN32)
  18610. file_mutex_init =
  18611. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18612. if (file_mutex_init == 0) {
  18613. /* Start WinSock */
  18614. WSADATA data;
  18615. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18616. }
  18617. #else
  18618. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18619. if (mutexattr_init == 0) {
  18620. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18621. PTHREAD_MUTEX_RECURSIVE);
  18622. }
  18623. #endif
  18624. }
  18625. if (failed) {
  18626. #if defined(_WIN32)
  18627. if (wsa == 0) {
  18628. (void)WSACleanup();
  18629. }
  18630. if (file_mutex_init == 0) {
  18631. (void)pthread_mutex_destroy(&global_log_file_lock);
  18632. }
  18633. #else
  18634. if (mutexattr_init == 0) {
  18635. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18636. }
  18637. #endif
  18638. if (key_create == 0) {
  18639. (void)pthread_key_delete(sTlsKey);
  18640. }
  18641. mg_global_unlock();
  18642. (void)pthread_mutex_destroy(&global_lock_mutex);
  18643. return 0;
  18644. }
  18645. #if defined(USE_LUA)
  18646. lua_init_optional_libraries();
  18647. #endif
  18648. }
  18649. mg_global_unlock();
  18650. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  18651. || defined(OPENSSL_API_3_0)) \
  18652. && !defined(NO_SSL)
  18653. if (features_to_init & MG_FEATURES_SSL) {
  18654. if (!mg_openssl_initialized) {
  18655. char ebuf[128];
  18656. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  18657. mg_openssl_initialized = 1;
  18658. } else {
  18659. (void)ebuf;
  18660. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18661. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18662. }
  18663. } else {
  18664. /* ssl already initialized */
  18665. }
  18666. }
  18667. #endif
  18668. mg_global_lock();
  18669. if (mg_init_library_called <= 0) {
  18670. mg_init_library_called = 1;
  18671. } else {
  18672. mg_init_library_called++;
  18673. }
  18674. mg_global_unlock();
  18675. return features_inited;
  18676. }
  18677. /* Un-initialize this library. */
  18678. unsigned
  18679. mg_exit_library(void)
  18680. {
  18681. if (mg_init_library_called <= 0) {
  18682. return 0;
  18683. }
  18684. mg_global_lock();
  18685. mg_init_library_called--;
  18686. if (mg_init_library_called == 0) {
  18687. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  18688. if (mg_openssl_initialized) {
  18689. uninitialize_openssl();
  18690. mg_openssl_initialized = 0;
  18691. }
  18692. #endif
  18693. #if defined(_WIN32)
  18694. (void)WSACleanup();
  18695. (void)pthread_mutex_destroy(&global_log_file_lock);
  18696. #else
  18697. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18698. #endif
  18699. (void)pthread_key_delete(sTlsKey);
  18700. #if defined(USE_LUA)
  18701. lua_exit_optional_libraries();
  18702. #endif
  18703. mg_global_unlock();
  18704. (void)pthread_mutex_destroy(&global_lock_mutex);
  18705. return 1;
  18706. }
  18707. mg_global_unlock();
  18708. return 1;
  18709. }
  18710. /* End of civetweb.c */