civetweb.c 566 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356
  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. #define CLOCK_MONOTONIC (1)
  311. #define CLOCK_REALTIME (2)
  312. #include <mach/clock.h>
  313. #include <mach/mach.h>
  314. #include <mach/mach_time.h>
  315. #include <sys/errno.h>
  316. #include <sys/time.h>
  317. /* clock_gettime is not implemented on OSX prior to 10.12 */
  318. static int
  319. _civet_clock_gettime(int clk_id, struct timespec *t)
  320. {
  321. memset(t, 0, sizeof(*t));
  322. if (clk_id == CLOCK_REALTIME) {
  323. struct timeval now;
  324. int rv = gettimeofday(&now, NULL);
  325. if (rv) {
  326. return rv;
  327. }
  328. t->tv_sec = now.tv_sec;
  329. t->tv_nsec = now.tv_usec * 1000;
  330. return 0;
  331. } else if (clk_id == CLOCK_MONOTONIC) {
  332. static uint64_t clock_start_time = 0;
  333. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  334. uint64_t now = mach_absolute_time();
  335. if (clock_start_time == 0) {
  336. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  337. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  338. /* appease "unused variable" warning for release builds */
  339. (void)mach_status;
  340. clock_start_time = now;
  341. }
  342. now = (uint64_t)((double)(now - clock_start_time)
  343. * (double)timebase_ifo.numer
  344. / (double)timebase_ifo.denom);
  345. t->tv_sec = now / 1000000000;
  346. t->tv_nsec = now % 1000000000;
  347. return 0;
  348. }
  349. return -1; /* EINVAL - Clock ID is unknown */
  350. }
  351. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  352. #if defined(__CLOCK_AVAILABILITY)
  353. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  354. * declared but it may be NULL at runtime. So we need to check before using
  355. * it. */
  356. static int
  357. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  358. {
  359. if (clock_gettime) {
  360. return clock_gettime(clk_id, t);
  361. }
  362. return _civet_clock_gettime(clk_id, t);
  363. }
  364. #define clock_gettime _civet_safe_clock_gettime
  365. #else
  366. #define clock_gettime _civet_clock_gettime
  367. #endif
  368. #endif
  369. #if !defined(_WIN32)
  370. /* Unix might return different error codes indicating to try again.
  371. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  372. * decades ago, but better check both and let the compile optimize it. */
  373. #define ERROR_TRY_AGAIN(err) \
  374. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  375. #endif
  376. #if defined(USE_ZLIB)
  377. #include "zconf.h"
  378. #include "zlib.h"
  379. #endif
  380. /********************************************************************/
  381. /* CivetWeb configuration defines */
  382. /********************************************************************/
  383. /* Maximum number of threads that can be configured.
  384. * The number of threads actually created depends on the "num_threads"
  385. * configuration parameter, but this is the upper limit. */
  386. #if !defined(MAX_WORKER_THREADS)
  387. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  388. #endif
  389. /* Timeout interval for select/poll calls.
  390. * The timeouts depend on "*_timeout_ms" configuration values, but long
  391. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  392. * This reduces the time required to stop the server. */
  393. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  394. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  395. #endif
  396. /* Do not try to compress files smaller than this limit. */
  397. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  398. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  399. #endif
  400. #if !defined(PASSWORDS_FILE_NAME)
  401. #define PASSWORDS_FILE_NAME ".htpasswd"
  402. #endif
  403. /* Initial buffer size for all CGI environment variables. In case there is
  404. * not enough space, another block is allocated. */
  405. #if !defined(CGI_ENVIRONMENT_SIZE)
  406. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  407. #endif
  408. /* Maximum number of environment variables. */
  409. #if !defined(MAX_CGI_ENVIR_VARS)
  410. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  411. #endif
  412. /* General purpose buffer size. */
  413. #if !defined(MG_BUF_LEN) /* in bytes */
  414. #define MG_BUF_LEN (1024 * 8)
  415. #endif
  416. /********************************************************************/
  417. /* Helper makros */
  418. #if !defined(ARRAY_SIZE)
  419. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  420. #endif
  421. #include <stdint.h>
  422. /* Standard defines */
  423. #if !defined(INT64_MAX)
  424. #define INT64_MAX (9223372036854775807)
  425. #endif
  426. #define SHUTDOWN_RD (0)
  427. #define SHUTDOWN_WR (1)
  428. #define SHUTDOWN_BOTH (2)
  429. mg_static_assert(MAX_WORKER_THREADS >= 1,
  430. "worker threads must be a positive number");
  431. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  432. "size_t data type size check");
  433. #if defined(_WIN32) /* WINDOWS include block */
  434. #include <malloc.h> /* *alloc( */
  435. #include <stdlib.h> /* *alloc( */
  436. #include <time.h> /* struct timespec */
  437. #include <windows.h>
  438. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  439. #include <ws2tcpip.h>
  440. typedef const char *SOCK_OPT_TYPE;
  441. /* For a detailed description of these *_PATH_MAX defines, see
  442. * https://github.com/civetweb/civetweb/issues/937. */
  443. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  444. * null termination, rounded up to the next 4 bytes boundary */
  445. #define UTF8_PATH_MAX (3 * 260)
  446. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  447. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  448. #define UTF16_PATH_MAX (260)
  449. #if !defined(_IN_PORT_T)
  450. #if !defined(in_port_t)
  451. #define in_port_t u_short
  452. #endif
  453. #endif
  454. #if defined(_WIN32_WCE)
  455. #error "WinCE support has ended"
  456. #endif
  457. #include <direct.h>
  458. #include <io.h>
  459. #include <process.h>
  460. #define MAKEUQUAD(lo, hi) \
  461. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  462. #define RATE_DIFF (10000000) /* 100 nsecs */
  463. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  464. #define SYS2UNIX_TIME(lo, hi) \
  465. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  466. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  467. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  468. * Also use _strtoui64 on modern M$ compilers */
  469. #if defined(_MSC_VER)
  470. #if (_MSC_VER < 1300)
  471. #define STRX(x) #x
  472. #define STR(x) STRX(x)
  473. #define __func__ __FILE__ ":" STR(__LINE__)
  474. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  475. #define strtoll(x, y, z) (_atoi64(x))
  476. #else
  477. #define __func__ __FUNCTION__
  478. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  479. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  480. #endif
  481. #endif /* _MSC_VER */
  482. #define ERRNO ((int)(GetLastError()))
  483. #define NO_SOCKLEN_T
  484. #if defined(_WIN64) || defined(__MINGW64__)
  485. #if !defined(SSL_LIB)
  486. #if defined(OPENSSL_API_3_0)
  487. #define SSL_LIB "libssl-3-x64.dll"
  488. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  489. #endif
  490. #if defined(OPENSSL_API_1_1)
  491. #define SSL_LIB "libssl-1_1-x64.dll"
  492. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  493. #endif /* OPENSSL_API_1_1 */
  494. #if defined(OPENSSL_API_1_0)
  495. #define SSL_LIB "ssleay64.dll"
  496. #define CRYPTO_LIB "libeay64.dll"
  497. #endif /* OPENSSL_API_1_0 */
  498. #endif
  499. #else /* defined(_WIN64) || defined(__MINGW64__) */
  500. #if !defined(SSL_LIB)
  501. #if defined(OPENSSL_API_3_0)
  502. #define SSL_LIB "libssl-3.dll"
  503. #define CRYPTO_LIB "libcrypto-3.dll"
  504. #endif
  505. #if defined(OPENSSL_API_1_1)
  506. #define SSL_LIB "libssl-1_1.dll"
  507. #define CRYPTO_LIB "libcrypto-1_1.dll"
  508. #endif /* OPENSSL_API_1_1 */
  509. #if defined(OPENSSL_API_1_0)
  510. #define SSL_LIB "ssleay32.dll"
  511. #define CRYPTO_LIB "libeay32.dll"
  512. #endif /* OPENSSL_API_1_0 */
  513. #endif /* SSL_LIB */
  514. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  515. #define O_NONBLOCK (0)
  516. #if !defined(W_OK)
  517. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  518. #endif
  519. #define _POSIX_
  520. #define INT64_FMT "I64d"
  521. #define UINT64_FMT "I64u"
  522. #define WINCDECL __cdecl
  523. #define vsnprintf_impl _vsnprintf
  524. #define access _access
  525. #define mg_sleep(x) (Sleep(x))
  526. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  527. #if !defined(popen)
  528. #define popen(x, y) (_popen(x, y))
  529. #endif
  530. #if !defined(pclose)
  531. #define pclose(x) (_pclose(x))
  532. #endif
  533. #define close(x) (_close(x))
  534. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  535. #define RTLD_LAZY (0)
  536. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  537. #define fdopen(x, y) (_fdopen((x), (y)))
  538. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  539. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  540. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  541. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  542. #define sleep(x) (Sleep((x)*1000))
  543. #define rmdir(x) (_rmdir(x))
  544. #if defined(_WIN64) || !defined(__MINGW32__)
  545. /* Only MinGW 32 bit is missing this function */
  546. #define timegm(x) (_mkgmtime(x))
  547. #else
  548. time_t timegm(struct tm *tm);
  549. #define NEED_TIMEGM
  550. #endif
  551. #if !defined(fileno)
  552. #define fileno(x) (_fileno(x))
  553. #endif /* !fileno MINGW #defines fileno */
  554. typedef struct {
  555. CRITICAL_SECTION sec; /* Immovable */
  556. } pthread_mutex_t;
  557. typedef DWORD pthread_key_t;
  558. typedef HANDLE pthread_t;
  559. typedef struct {
  560. pthread_mutex_t threadIdSec;
  561. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  562. } pthread_cond_t;
  563. #if !defined(__clockid_t_defined)
  564. typedef DWORD clockid_t;
  565. #endif
  566. #if !defined(CLOCK_MONOTONIC)
  567. #define CLOCK_MONOTONIC (1)
  568. #endif
  569. #if !defined(CLOCK_REALTIME)
  570. #define CLOCK_REALTIME (2)
  571. #endif
  572. #if !defined(CLOCK_THREAD)
  573. #define CLOCK_THREAD (3)
  574. #endif
  575. #if !defined(CLOCK_PROCESS)
  576. #define CLOCK_PROCESS (4)
  577. #endif
  578. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  579. #define _TIMESPEC_DEFINED
  580. #endif
  581. #if !defined(_TIMESPEC_DEFINED)
  582. struct timespec {
  583. time_t tv_sec; /* seconds */
  584. long tv_nsec; /* nanoseconds */
  585. };
  586. #endif
  587. #if !defined(WIN_PTHREADS_TIME_H)
  588. #define MUST_IMPLEMENT_CLOCK_GETTIME
  589. #endif
  590. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  591. #define clock_gettime mg_clock_gettime
  592. static int
  593. clock_gettime(clockid_t clk_id, struct timespec *tp)
  594. {
  595. FILETIME ft;
  596. ULARGE_INTEGER li, li2;
  597. BOOL ok = FALSE;
  598. double d;
  599. static double perfcnt_per_sec = 0.0;
  600. static BOOL initialized = FALSE;
  601. if (!initialized) {
  602. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  603. perfcnt_per_sec = 1.0 / li.QuadPart;
  604. initialized = TRUE;
  605. }
  606. if (tp) {
  607. memset(tp, 0, sizeof(*tp));
  608. if (clk_id == CLOCK_REALTIME) {
  609. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  610. GetSystemTimeAsFileTime(&ft);
  611. li.LowPart = ft.dwLowDateTime;
  612. li.HighPart = ft.dwHighDateTime;
  613. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  614. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  615. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  616. ok = TRUE;
  617. /* END: CLOCK_REALTIME */
  618. } else if (clk_id == CLOCK_MONOTONIC) {
  619. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  620. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  621. d = li.QuadPart * perfcnt_per_sec;
  622. tp->tv_sec = (time_t)d;
  623. d -= (double)tp->tv_sec;
  624. tp->tv_nsec = (long)(d * 1.0E9);
  625. ok = TRUE;
  626. /* END: CLOCK_MONOTONIC */
  627. } else if (clk_id == CLOCK_THREAD) {
  628. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  629. FILETIME t_create, t_exit, t_kernel, t_user;
  630. if (GetThreadTimes(GetCurrentThread(),
  631. &t_create,
  632. &t_exit,
  633. &t_kernel,
  634. &t_user)) {
  635. li.LowPart = t_user.dwLowDateTime;
  636. li.HighPart = t_user.dwHighDateTime;
  637. li2.LowPart = t_kernel.dwLowDateTime;
  638. li2.HighPart = t_kernel.dwHighDateTime;
  639. li.QuadPart += li2.QuadPart;
  640. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  641. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  642. ok = TRUE;
  643. }
  644. /* END: CLOCK_THREAD */
  645. } else if (clk_id == CLOCK_PROCESS) {
  646. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  647. FILETIME t_create, t_exit, t_kernel, t_user;
  648. if (GetProcessTimes(GetCurrentProcess(),
  649. &t_create,
  650. &t_exit,
  651. &t_kernel,
  652. &t_user)) {
  653. li.LowPart = t_user.dwLowDateTime;
  654. li.HighPart = t_user.dwHighDateTime;
  655. li2.LowPart = t_kernel.dwLowDateTime;
  656. li2.HighPart = t_kernel.dwHighDateTime;
  657. li.QuadPart += li2.QuadPart;
  658. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  659. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  660. ok = TRUE;
  661. }
  662. /* END: CLOCK_PROCESS */
  663. } else {
  664. /* BEGIN: unknown clock */
  665. /* ok = FALSE; already set by init */
  666. /* END: unknown clock */
  667. }
  668. }
  669. return ok ? 0 : -1;
  670. }
  671. #endif
  672. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  673. static int pthread_mutex_lock(pthread_mutex_t *);
  674. static int pthread_mutex_unlock(pthread_mutex_t *);
  675. static void path_to_unicode(const struct mg_connection *conn,
  676. const char *path,
  677. wchar_t *wbuf,
  678. size_t wbuf_len);
  679. /* All file operations need to be rewritten to solve #246. */
  680. struct mg_file;
  681. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  682. /* POSIX dirent interface */
  683. struct dirent {
  684. char d_name[UTF8_PATH_MAX];
  685. };
  686. typedef struct DIR {
  687. HANDLE handle;
  688. WIN32_FIND_DATAW info;
  689. struct dirent result;
  690. } DIR;
  691. #if defined(HAVE_POLL)
  692. #define mg_pollfd pollfd
  693. #else
  694. struct mg_pollfd {
  695. SOCKET fd;
  696. short events;
  697. short revents;
  698. };
  699. #endif
  700. /* Mark required libraries */
  701. #if defined(_MSC_VER)
  702. #pragma comment(lib, "Ws2_32.lib")
  703. #endif
  704. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  705. #include <inttypes.h>
  706. /* Linux & co. internally use UTF8 */
  707. #define UTF8_PATH_MAX (PATH_MAX)
  708. typedef const void *SOCK_OPT_TYPE;
  709. #if defined(ANDROID)
  710. typedef unsigned short int in_port_t;
  711. #endif
  712. #if !defined(__ZEPHYR__)
  713. #include <arpa/inet.h>
  714. #include <ctype.h>
  715. #include <dirent.h>
  716. #include <grp.h>
  717. #include <limits.h>
  718. #include <netdb.h>
  719. #include <netinet/in.h>
  720. #include <netinet/tcp.h>
  721. #include <pthread.h>
  722. #include <pwd.h>
  723. #include <stdarg.h>
  724. #include <stddef.h>
  725. #include <stdio.h>
  726. #include <stdlib.h>
  727. #include <string.h>
  728. #include <sys/poll.h>
  729. #include <sys/socket.h>
  730. #include <sys/time.h>
  731. #include <sys/utsname.h>
  732. #include <sys/wait.h>
  733. #include <time.h>
  734. #include <unistd.h>
  735. #if defined(USE_X_DOM_SOCKET)
  736. #include <sys/un.h>
  737. #endif
  738. #endif
  739. #define vsnprintf_impl vsnprintf
  740. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  741. #include <dlfcn.h>
  742. #endif
  743. #if defined(__MACH__)
  744. #define SSL_LIB "libssl.dylib"
  745. #define CRYPTO_LIB "libcrypto.dylib"
  746. #else
  747. #if !defined(SSL_LIB)
  748. #define SSL_LIB "libssl.so"
  749. #endif
  750. #if !defined(CRYPTO_LIB)
  751. #define CRYPTO_LIB "libcrypto.so"
  752. #endif
  753. #endif
  754. #if !defined(O_BINARY)
  755. #define O_BINARY (0)
  756. #endif /* O_BINARY */
  757. #define closesocket(a) (close(a))
  758. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  759. #define mg_remove(conn, x) (remove(x))
  760. #define mg_sleep(x) (usleep((x)*1000))
  761. #define mg_opendir(conn, x) (opendir(x))
  762. #define mg_closedir(x) (closedir(x))
  763. #define mg_readdir(x) (readdir(x))
  764. #define ERRNO (errno)
  765. #define INVALID_SOCKET (-1)
  766. #define INT64_FMT PRId64
  767. #define UINT64_FMT PRIu64
  768. typedef int SOCKET;
  769. #define WINCDECL
  770. #if defined(__hpux)
  771. /* HPUX 11 does not have monotonic, fall back to realtime */
  772. #if !defined(CLOCK_MONOTONIC)
  773. #define CLOCK_MONOTONIC CLOCK_REALTIME
  774. #endif
  775. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  776. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  777. * the prototypes use int* rather than socklen_t* which matches the
  778. * actual library expectation. When called with the wrong size arg
  779. * accept() returns a zero client inet addr and check_acl() always
  780. * fails. Since socklen_t is widely used below, just force replace
  781. * their typedef with int. - DTL
  782. */
  783. #define socklen_t int
  784. #endif /* hpux */
  785. #define mg_pollfd pollfd
  786. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  787. /* In case our C library is missing "timegm", provide an implementation */
  788. #if defined(NEED_TIMEGM)
  789. static inline int
  790. is_leap(int y)
  791. {
  792. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  793. }
  794. static inline int
  795. count_leap(int y)
  796. {
  797. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  798. }
  799. time_t
  800. timegm(struct tm *tm)
  801. {
  802. static const unsigned short ydays[] = {
  803. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  804. int year = tm->tm_year + 1900;
  805. int mon = tm->tm_mon;
  806. int mday = tm->tm_mday - 1;
  807. int hour = tm->tm_hour;
  808. int min = tm->tm_min;
  809. int sec = tm->tm_sec;
  810. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  811. || (mday >= ydays[mon + 1] - ydays[mon]
  812. + (mon == 1 && is_leap(year) ? 1 : 0))
  813. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  814. return -1;
  815. time_t res = year - 1970;
  816. res *= 365;
  817. res += mday;
  818. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  819. res += count_leap(year);
  820. res *= 24;
  821. res += hour;
  822. res *= 60;
  823. res += min;
  824. res *= 60;
  825. res += sec;
  826. return res;
  827. }
  828. #endif /* NEED_TIMEGM */
  829. /* va_copy should always be a macro, C99 and C++11 - DTL */
  830. #if !defined(va_copy)
  831. #define va_copy(x, y) ((x) = (y))
  832. #endif
  833. #if defined(_WIN32)
  834. /* Create substitutes for POSIX functions in Win32. */
  835. #if defined(GCC_DIAGNOSTIC)
  836. /* Show no warning in case system functions are not used. */
  837. #pragma GCC diagnostic push
  838. #pragma GCC diagnostic ignored "-Wunused-function"
  839. #endif
  840. static pthread_mutex_t global_log_file_lock;
  841. FUNCTION_MAY_BE_UNUSED
  842. static DWORD
  843. pthread_self(void)
  844. {
  845. return GetCurrentThreadId();
  846. }
  847. FUNCTION_MAY_BE_UNUSED
  848. static int
  849. pthread_key_create(
  850. pthread_key_t *key,
  851. void (*_ignored)(void *) /* destructor not supported for Windows */
  852. )
  853. {
  854. (void)_ignored;
  855. if ((key != 0)) {
  856. *key = TlsAlloc();
  857. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  858. }
  859. return -2;
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static int
  863. pthread_key_delete(pthread_key_t key)
  864. {
  865. return TlsFree(key) ? 0 : 1;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static int
  869. pthread_setspecific(pthread_key_t key, void *value)
  870. {
  871. return TlsSetValue(key, value) ? 0 : 1;
  872. }
  873. FUNCTION_MAY_BE_UNUSED
  874. static void *
  875. pthread_getspecific(pthread_key_t key)
  876. {
  877. return TlsGetValue(key);
  878. }
  879. #if defined(GCC_DIAGNOSTIC)
  880. /* Enable unused function warning again */
  881. #pragma GCC diagnostic pop
  882. #endif
  883. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  884. #else
  885. static pthread_mutexattr_t pthread_mutex_attr;
  886. #endif /* _WIN32 */
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Show no warning in case system functions are not used. */
  889. #pragma GCC diagnostic push
  890. #pragma GCC diagnostic ignored "-Wunused-function"
  891. #endif /* defined(GCC_DIAGNOSTIC) */
  892. #if defined(__clang__)
  893. /* Show no warning in case system functions are not used. */
  894. #pragma clang diagnostic push
  895. #pragma clang diagnostic ignored "-Wunused-function"
  896. #endif
  897. static pthread_mutex_t global_lock_mutex;
  898. FUNCTION_MAY_BE_UNUSED
  899. static void
  900. mg_global_lock(void)
  901. {
  902. (void)pthread_mutex_lock(&global_lock_mutex);
  903. }
  904. FUNCTION_MAY_BE_UNUSED
  905. static void
  906. mg_global_unlock(void)
  907. {
  908. (void)pthread_mutex_unlock(&global_lock_mutex);
  909. }
  910. #if defined(_WIN64)
  911. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  912. #elif defined(_WIN32)
  913. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  914. #endif
  915. /* Atomic functions working on ptrdiff_t ("signed size_t").
  916. * Operations: Increment, Decrement, Add, Maximum.
  917. * Up to size_t, they do not an atomic "load" operation.
  918. */
  919. FUNCTION_MAY_BE_UNUSED
  920. static ptrdiff_t
  921. mg_atomic_inc(volatile ptrdiff_t *addr)
  922. {
  923. ptrdiff_t ret;
  924. #if defined(_WIN64) && !defined(NO_ATOMICS)
  925. ret = InterlockedIncrement64(addr);
  926. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  927. ret = InterlockedIncrement(addr);
  928. #elif defined(__GNUC__) \
  929. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  930. && !defined(NO_ATOMICS)
  931. ret = __sync_add_and_fetch(addr, 1);
  932. #else
  933. mg_global_lock();
  934. ret = (++(*addr));
  935. mg_global_unlock();
  936. #endif
  937. return ret;
  938. }
  939. FUNCTION_MAY_BE_UNUSED
  940. static ptrdiff_t
  941. mg_atomic_dec(volatile ptrdiff_t *addr)
  942. {
  943. ptrdiff_t ret;
  944. #if defined(_WIN64) && !defined(NO_ATOMICS)
  945. ret = InterlockedDecrement64(addr);
  946. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  947. ret = InterlockedDecrement(addr);
  948. #elif defined(__GNUC__) \
  949. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  950. && !defined(NO_ATOMICS)
  951. ret = __sync_sub_and_fetch(addr, 1);
  952. #else
  953. mg_global_lock();
  954. ret = (--(*addr));
  955. mg_global_unlock();
  956. #endif
  957. return ret;
  958. }
  959. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  960. static ptrdiff_t
  961. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  962. {
  963. ptrdiff_t ret;
  964. #if defined(_WIN64) && !defined(NO_ATOMICS)
  965. ret = InterlockedAdd64(addr, value);
  966. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  967. ret = InterlockedExchangeAdd(addr, value) + value;
  968. #elif defined(__GNUC__) \
  969. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  970. && !defined(NO_ATOMICS)
  971. ret = __sync_add_and_fetch(addr, value);
  972. #else
  973. mg_global_lock();
  974. *addr += value;
  975. ret = (*addr);
  976. mg_global_unlock();
  977. #endif
  978. return ret;
  979. }
  980. FUNCTION_MAY_BE_UNUSED
  981. static ptrdiff_t
  982. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  983. ptrdiff_t oldval,
  984. ptrdiff_t newval)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedCompareExchange64(addr, newval, oldval);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedCompareExchange(addr, newval, oldval);
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  995. #else
  996. mg_global_lock();
  997. ret = *addr;
  998. if ((ret != newval) && (ret == oldval)) {
  999. *addr = newval;
  1000. }
  1001. mg_global_unlock();
  1002. #endif
  1003. return ret;
  1004. }
  1005. static void
  1006. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1007. {
  1008. register ptrdiff_t tmp = *addr;
  1009. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1010. while (tmp < value) {
  1011. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1012. }
  1013. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1014. while (tmp < value) {
  1015. tmp = InterlockedCompareExchange(addr, value, tmp);
  1016. }
  1017. #elif defined(__GNUC__) \
  1018. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1019. && !defined(NO_ATOMICS)
  1020. while (tmp < value) {
  1021. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1022. }
  1023. #else
  1024. mg_global_lock();
  1025. if (*addr < value) {
  1026. *addr = value;
  1027. }
  1028. mg_global_unlock();
  1029. #endif
  1030. }
  1031. static int64_t
  1032. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1033. {
  1034. int64_t ret;
  1035. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1036. ret = InterlockedAdd64(addr, value);
  1037. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1038. ret = InterlockedExchangeAdd64(addr, value) + value;
  1039. #elif defined(__GNUC__) \
  1040. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1041. && !defined(NO_ATOMICS)
  1042. ret = __sync_add_and_fetch(addr, value);
  1043. #else
  1044. mg_global_lock();
  1045. *addr += value;
  1046. ret = (*addr);
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. #endif
  1052. #if defined(GCC_DIAGNOSTIC)
  1053. /* Show no warning in case system functions are not used. */
  1054. #pragma GCC diagnostic pop
  1055. #endif /* defined(GCC_DIAGNOSTIC) */
  1056. #if defined(__clang__)
  1057. /* Show no warning in case system functions are not used. */
  1058. #pragma clang diagnostic pop
  1059. #endif
  1060. #if defined(USE_SERVER_STATS)
  1061. struct mg_memory_stat {
  1062. volatile ptrdiff_t totalMemUsed;
  1063. volatile ptrdiff_t maxMemUsed;
  1064. volatile ptrdiff_t blockCount;
  1065. };
  1066. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1067. static void *
  1068. mg_malloc_ex(size_t size,
  1069. struct mg_context *ctx,
  1070. const char *file,
  1071. unsigned line)
  1072. {
  1073. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1074. void *memory = 0;
  1075. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1076. #if defined(MEMORY_DEBUGGING)
  1077. char mallocStr[256];
  1078. #else
  1079. (void)file;
  1080. (void)line;
  1081. #endif
  1082. if (data) {
  1083. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1084. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1085. mg_atomic_inc(&mstat->blockCount);
  1086. ((uintptr_t *)data)[0] = size;
  1087. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1088. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1089. }
  1090. #if defined(MEMORY_DEBUGGING)
  1091. sprintf(mallocStr,
  1092. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1093. memory,
  1094. (unsigned long)size,
  1095. (unsigned long)mstat->totalMemUsed,
  1096. (unsigned long)mstat->blockCount,
  1097. file,
  1098. line);
  1099. DEBUG_TRACE("%s", mallocStr);
  1100. #endif
  1101. return memory;
  1102. }
  1103. static void *
  1104. mg_calloc_ex(size_t count,
  1105. size_t size,
  1106. struct mg_context *ctx,
  1107. const char *file,
  1108. unsigned line)
  1109. {
  1110. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1111. if (data) {
  1112. memset(data, 0, size * count);
  1113. }
  1114. return data;
  1115. }
  1116. static void
  1117. mg_free_ex(void *memory, const char *file, unsigned line)
  1118. {
  1119. #if defined(MEMORY_DEBUGGING)
  1120. char mallocStr[256];
  1121. #else
  1122. (void)file;
  1123. (void)line;
  1124. #endif
  1125. if (memory) {
  1126. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1127. uintptr_t size = ((uintptr_t *)data)[0];
  1128. struct mg_memory_stat *mstat =
  1129. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1130. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1131. mg_atomic_dec(&mstat->blockCount);
  1132. #if defined(MEMORY_DEBUGGING)
  1133. sprintf(mallocStr,
  1134. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1135. memory,
  1136. (unsigned long)size,
  1137. (unsigned long)mstat->totalMemUsed,
  1138. (unsigned long)mstat->blockCount,
  1139. file,
  1140. line);
  1141. DEBUG_TRACE("%s", mallocStr);
  1142. #endif
  1143. free(data);
  1144. }
  1145. }
  1146. static void *
  1147. mg_realloc_ex(void *memory,
  1148. size_t newsize,
  1149. struct mg_context *ctx,
  1150. const char *file,
  1151. unsigned line)
  1152. {
  1153. void *data;
  1154. void *_realloc;
  1155. uintptr_t oldsize;
  1156. #if defined(MEMORY_DEBUGGING)
  1157. char mallocStr[256];
  1158. #else
  1159. (void)file;
  1160. (void)line;
  1161. #endif
  1162. if (newsize) {
  1163. if (memory) {
  1164. /* Reallocate existing block */
  1165. struct mg_memory_stat *mstat;
  1166. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1167. oldsize = ((uintptr_t *)data)[0];
  1168. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1169. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1170. if (_realloc) {
  1171. data = _realloc;
  1172. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1173. #if defined(MEMORY_DEBUGGING)
  1174. sprintf(mallocStr,
  1175. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1176. memory,
  1177. (unsigned long)oldsize,
  1178. (unsigned long)mstat->totalMemUsed,
  1179. (unsigned long)mstat->blockCount,
  1180. file,
  1181. line);
  1182. DEBUG_TRACE("%s", mallocStr);
  1183. #endif
  1184. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1185. #if defined(MEMORY_DEBUGGING)
  1186. sprintf(mallocStr,
  1187. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1188. memory,
  1189. (unsigned long)newsize,
  1190. (unsigned long)mstat->totalMemUsed,
  1191. (unsigned long)mstat->blockCount,
  1192. file,
  1193. line);
  1194. DEBUG_TRACE("%s", mallocStr);
  1195. #endif
  1196. *(uintptr_t *)data = newsize;
  1197. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1198. } else {
  1199. #if defined(MEMORY_DEBUGGING)
  1200. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1201. #endif
  1202. return _realloc;
  1203. }
  1204. } else {
  1205. /* Allocate new block */
  1206. data = mg_malloc_ex(newsize, ctx, file, line);
  1207. }
  1208. } else {
  1209. /* Free existing block */
  1210. data = 0;
  1211. mg_free_ex(memory, file, line);
  1212. }
  1213. return data;
  1214. }
  1215. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1216. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1217. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1218. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1219. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1220. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1221. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1222. #else /* USE_SERVER_STATS */
  1223. static __inline void *
  1224. mg_malloc(size_t a)
  1225. {
  1226. return malloc(a);
  1227. }
  1228. static __inline void *
  1229. mg_calloc(size_t a, size_t b)
  1230. {
  1231. return calloc(a, b);
  1232. }
  1233. static __inline void *
  1234. mg_realloc(void *a, size_t b)
  1235. {
  1236. return realloc(a, b);
  1237. }
  1238. static __inline void
  1239. mg_free(void *a)
  1240. {
  1241. free(a);
  1242. }
  1243. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1246. #define mg_free_ctx(a, c) mg_free(a)
  1247. #endif /* USE_SERVER_STATS */
  1248. static void mg_vsnprintf(const struct mg_connection *conn,
  1249. int *truncated,
  1250. char *buf,
  1251. size_t buflen,
  1252. const char *fmt,
  1253. va_list ap);
  1254. static void mg_snprintf(const struct mg_connection *conn,
  1255. int *truncated,
  1256. char *buf,
  1257. size_t buflen,
  1258. PRINTF_FORMAT_STRING(const char *fmt),
  1259. ...) PRINTF_ARGS(5, 6);
  1260. /* This following lines are just meant as a reminder to use the mg-functions
  1261. * for memory management */
  1262. #if defined(malloc)
  1263. #undef malloc
  1264. #endif
  1265. #if defined(calloc)
  1266. #undef calloc
  1267. #endif
  1268. #if defined(realloc)
  1269. #undef realloc
  1270. #endif
  1271. #if defined(free)
  1272. #undef free
  1273. #endif
  1274. #if defined(snprintf)
  1275. #undef snprintf
  1276. #endif
  1277. #if defined(vsnprintf)
  1278. #undef vsnprintf
  1279. #endif
  1280. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1281. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1282. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1283. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1284. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1285. #if defined(_WIN32)
  1286. /* vsnprintf must not be used in any system,
  1287. * but this define only works well for Windows. */
  1288. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1289. #endif
  1290. /* mg_init_library counter */
  1291. static int mg_init_library_called = 0;
  1292. #if !defined(NO_SSL)
  1293. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  1294. static int mg_openssl_initialized = 0;
  1295. #endif
  1296. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1297. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1298. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1299. #endif
  1300. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1301. #error "Multiple OPENSSL_API versions defined"
  1302. #endif
  1303. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1304. || defined(OPENSSL_API_3_0)) && defined(USE_MBEDTLS)
  1305. #error "Multiple SSL libraries defined"
  1306. #endif
  1307. #endif
  1308. static pthread_key_t sTlsKey; /* Thread local storage index */
  1309. static volatile ptrdiff_t thread_idx_max = 0;
  1310. #if defined(MG_LEGACY_INTERFACE)
  1311. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1312. #endif
  1313. struct mg_workerTLS {
  1314. int is_master;
  1315. unsigned long thread_idx;
  1316. void *user_ptr;
  1317. #if defined(_WIN32)
  1318. HANDLE pthread_cond_helper_mutex;
  1319. struct mg_workerTLS *next_waiting_thread;
  1320. #endif
  1321. const char *alpn_proto;
  1322. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1323. char txtbuf[4];
  1324. #endif
  1325. };
  1326. #if defined(GCC_DIAGNOSTIC)
  1327. /* Show no warning in case system functions are not used. */
  1328. #pragma GCC diagnostic push
  1329. #pragma GCC diagnostic ignored "-Wunused-function"
  1330. #endif /* defined(GCC_DIAGNOSTIC) */
  1331. #if defined(__clang__)
  1332. /* Show no warning in case system functions are not used. */
  1333. #pragma clang diagnostic push
  1334. #pragma clang diagnostic ignored "-Wunused-function"
  1335. #endif
  1336. /* Get a unique thread ID as unsigned long, independent from the data type
  1337. * of thread IDs defined by the operating system API.
  1338. * If two calls to mg_current_thread_id return the same value, they calls
  1339. * are done from the same thread. If they return different values, they are
  1340. * done from different threads. (Provided this function is used in the same
  1341. * process context and threads are not repeatedly created and deleted, but
  1342. * CivetWeb does not do that).
  1343. * This function must match the signature required for SSL id callbacks:
  1344. * CRYPTO_set_id_callback
  1345. */
  1346. FUNCTION_MAY_BE_UNUSED
  1347. static unsigned long
  1348. mg_current_thread_id(void)
  1349. {
  1350. #if defined(_WIN32)
  1351. return GetCurrentThreadId();
  1352. #else
  1353. #if defined(__clang__)
  1354. #pragma clang diagnostic push
  1355. #pragma clang diagnostic ignored "-Wunreachable-code"
  1356. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1357. * or not, so one of the two conditions will be unreachable by construction.
  1358. * Unfortunately the C standard does not define a way to check this at
  1359. * compile time, since the #if preprocessor conditions can not use the
  1360. * sizeof operator as an argument. */
  1361. #endif
  1362. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1363. /* This is the problematic case for CRYPTO_set_id_callback:
  1364. * The OS pthread_t can not be cast to unsigned long. */
  1365. struct mg_workerTLS *tls =
  1366. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1367. if (tls == NULL) {
  1368. /* SSL called from an unknown thread: Create some thread index.
  1369. */
  1370. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1371. tls->is_master = -2; /* -2 means "3rd party thread" */
  1372. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1373. pthread_setspecific(sTlsKey, tls);
  1374. }
  1375. return tls->thread_idx;
  1376. } else {
  1377. /* pthread_t may be any data type, so a simple cast to unsigned long
  1378. * can rise a warning/error, depending on the platform.
  1379. * Here memcpy is used as an anything-to-anything cast. */
  1380. unsigned long ret = 0;
  1381. pthread_t t = pthread_self();
  1382. memcpy(&ret, &t, sizeof(pthread_t));
  1383. return ret;
  1384. }
  1385. #if defined(__clang__)
  1386. #pragma clang diagnostic pop
  1387. #endif
  1388. #endif
  1389. }
  1390. FUNCTION_MAY_BE_UNUSED
  1391. static uint64_t
  1392. mg_get_current_time_ns(void)
  1393. {
  1394. struct timespec tsnow;
  1395. clock_gettime(CLOCK_REALTIME, &tsnow);
  1396. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1397. }
  1398. #if defined(GCC_DIAGNOSTIC)
  1399. /* Show no warning in case system functions are not used. */
  1400. #pragma GCC diagnostic pop
  1401. #endif /* defined(GCC_DIAGNOSTIC) */
  1402. #if defined(__clang__)
  1403. /* Show no warning in case system functions are not used. */
  1404. #pragma clang diagnostic pop
  1405. #endif
  1406. #if defined(NEED_DEBUG_TRACE_FUNC)
  1407. static void
  1408. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1409. {
  1410. va_list args;
  1411. struct timespec tsnow;
  1412. /* Get some operating system independent thread id */
  1413. unsigned long thread_id = mg_current_thread_id();
  1414. clock_gettime(CLOCK_REALTIME, &tsnow);
  1415. flockfile(DEBUG_TRACE_STREAM);
  1416. fprintf(DEBUG_TRACE_STREAM,
  1417. "*** %lu.%09lu %lu %s:%u: ",
  1418. (unsigned long)tsnow.tv_sec,
  1419. (unsigned long)tsnow.tv_nsec,
  1420. thread_id,
  1421. func,
  1422. line);
  1423. va_start(args, fmt);
  1424. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1425. va_end(args);
  1426. putc('\n', DEBUG_TRACE_STREAM);
  1427. fflush(DEBUG_TRACE_STREAM);
  1428. funlockfile(DEBUG_TRACE_STREAM);
  1429. }
  1430. #endif /* NEED_DEBUG_TRACE_FUNC */
  1431. #define MD5_STATIC static
  1432. #include "md5.inl"
  1433. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1434. #if defined(NO_SOCKLEN_T)
  1435. typedef int socklen_t;
  1436. #endif /* NO_SOCKLEN_T */
  1437. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1438. #if !defined(MSG_NOSIGNAL)
  1439. #define MSG_NOSIGNAL (0)
  1440. #endif
  1441. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1442. #if defined(USE_MBEDTLS)
  1443. /* mbedTLS */
  1444. #include "mod_mbedtls.inl"
  1445. #elif defined(NO_SSL)
  1446. /* no SSL */
  1447. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1448. typedef struct SSL_CTX SSL_CTX;
  1449. #elif defined(NO_SSL_DL)
  1450. /* OpenSSL without dynamic loading */
  1451. #include <openssl/bn.h>
  1452. #include <openssl/conf.h>
  1453. #include <openssl/crypto.h>
  1454. #include <openssl/dh.h>
  1455. #include <openssl/engine.h>
  1456. #include <openssl/err.h>
  1457. #include <openssl/opensslv.h>
  1458. #include <openssl/pem.h>
  1459. #include <openssl/ssl.h>
  1460. #include <openssl/tls1.h>
  1461. #include <openssl/x509.h>
  1462. #if defined(WOLFSSL_VERSION)
  1463. /* Additional defines for WolfSSL, see
  1464. * https://github.com/civetweb/civetweb/issues/583 */
  1465. #include "wolfssl_extras.inl"
  1466. #endif
  1467. #if defined(OPENSSL_IS_BORINGSSL)
  1468. /* From boringssl/src/include/openssl/mem.h:
  1469. *
  1470. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1471. * However, that was written in a time before Valgrind and ASAN. Since we now
  1472. * have those tools, the OpenSSL allocation functions are simply macros around
  1473. * the standard memory functions.
  1474. *
  1475. * #define OPENSSL_free free */
  1476. #define free free
  1477. // disable for boringssl
  1478. #define CONF_modules_unload(a) ((void)0)
  1479. #define ENGINE_cleanup() ((void)0)
  1480. #endif
  1481. /* If OpenSSL headers are included, automatically select the API version */
  1482. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1483. #if !defined(OPENSSL_API_3_0)
  1484. #define OPENSSL_API_3_0
  1485. #endif
  1486. #else
  1487. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1488. #if !defined(OPENSSL_API_1_1)
  1489. #define OPENSSL_API_1_1
  1490. #endif
  1491. #define OPENSSL_REMOVE_THREAD_STATE()
  1492. #else
  1493. #if !defined(OPENSSL_API_1_0)
  1494. #define OPENSSL_API_1_0
  1495. #endif
  1496. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1497. #endif
  1498. #endif
  1499. #else
  1500. /* SSL loaded dynamically from DLL / shared object */
  1501. /* Add all prototypes here, to be independent from OpenSSL source
  1502. * installation. */
  1503. #include "openssl_dl.inl"
  1504. #endif /* Various SSL bindings */
  1505. #if !defined(NO_CACHING)
  1506. static const char month_names[][4] = {"Jan",
  1507. "Feb",
  1508. "Mar",
  1509. "Apr",
  1510. "May",
  1511. "Jun",
  1512. "Jul",
  1513. "Aug",
  1514. "Sep",
  1515. "Oct",
  1516. "Nov",
  1517. "Dec"};
  1518. #endif /* !NO_CACHING */
  1519. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1520. * the union u. */
  1521. union usa {
  1522. struct sockaddr sa;
  1523. struct sockaddr_in sin;
  1524. #if defined(USE_IPV6)
  1525. struct sockaddr_in6 sin6;
  1526. #endif
  1527. #if defined(USE_X_DOM_SOCKET)
  1528. struct sockaddr_un sun;
  1529. #endif
  1530. };
  1531. #if defined(USE_X_DOM_SOCKET)
  1532. static unsigned short
  1533. USA_IN_PORT_UNSAFE(union usa *s)
  1534. {
  1535. if (s->sa.sa_family == AF_INET)
  1536. return s->sin.sin_port;
  1537. #if defined(USE_IPV6)
  1538. if (s->sa.sa_family == AF_INET6)
  1539. return s->sin6.sin6_port;
  1540. #endif
  1541. return 0;
  1542. }
  1543. #endif
  1544. #if defined(USE_IPV6)
  1545. #define USA_IN_PORT_UNSAFE(s) \
  1546. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1547. #else
  1548. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1549. #endif
  1550. /* Describes a string (chunk of memory). */
  1551. struct vec {
  1552. const char *ptr;
  1553. size_t len;
  1554. };
  1555. struct mg_file_stat {
  1556. /* File properties filled by mg_stat: */
  1557. uint64_t size;
  1558. time_t last_modified;
  1559. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1560. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1561. * case we need a "Content-Eencoding: gzip" header */
  1562. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1563. };
  1564. struct mg_file_access {
  1565. /* File properties filled by mg_fopen: */
  1566. FILE *fp;
  1567. };
  1568. struct mg_file {
  1569. struct mg_file_stat stat;
  1570. struct mg_file_access access;
  1571. };
  1572. #define STRUCT_FILE_INITIALIZER \
  1573. { \
  1574. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1575. { \
  1576. (FILE *)NULL \
  1577. } \
  1578. }
  1579. /* Describes listening socket, or socket which was accept()-ed by the master
  1580. * thread and queued for future handling by the worker thread. */
  1581. struct socket {
  1582. SOCKET sock; /* Listening socket */
  1583. union usa lsa; /* Local socket address */
  1584. union usa rsa; /* Remote socket address */
  1585. unsigned char is_ssl; /* Is port SSL-ed */
  1586. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1587. * port */
  1588. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1589. };
  1590. /* Enum const for all options must be in sync with
  1591. * static struct mg_option config_options[]
  1592. * This is tested in the unit test (test/private.c)
  1593. * "Private Config Options"
  1594. */
  1595. enum {
  1596. /* Once for each server */
  1597. LISTENING_PORTS,
  1598. NUM_THREADS,
  1599. RUN_AS_USER,
  1600. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1601. * socket option typedef TCP_NODELAY. */
  1602. MAX_REQUEST_SIZE,
  1603. LINGER_TIMEOUT,
  1604. CONNECTION_QUEUE_SIZE,
  1605. LISTEN_BACKLOG_SIZE,
  1606. #if defined(__linux__)
  1607. ALLOW_SENDFILE_CALL,
  1608. #endif
  1609. #if defined(_WIN32)
  1610. CASE_SENSITIVE_FILES,
  1611. #endif
  1612. THROTTLE,
  1613. ENABLE_KEEP_ALIVE,
  1614. REQUEST_TIMEOUT,
  1615. KEEP_ALIVE_TIMEOUT,
  1616. #if defined(USE_WEBSOCKET)
  1617. WEBSOCKET_TIMEOUT,
  1618. ENABLE_WEBSOCKET_PING_PONG,
  1619. #endif
  1620. DECODE_URL,
  1621. #if defined(USE_LUA)
  1622. LUA_BACKGROUND_SCRIPT,
  1623. LUA_BACKGROUND_SCRIPT_PARAMS,
  1624. #endif
  1625. #if defined(USE_HTTP2)
  1626. ENABLE_HTTP2,
  1627. #endif
  1628. /* Once for each domain */
  1629. DOCUMENT_ROOT,
  1630. ACCESS_LOG_FILE,
  1631. ERROR_LOG_FILE,
  1632. CGI_EXTENSIONS,
  1633. CGI_ENVIRONMENT,
  1634. CGI_INTERPRETER,
  1635. CGI_INTERPRETER_ARGS,
  1636. #if defined(USE_TIMERS)
  1637. CGI_TIMEOUT,
  1638. #endif
  1639. CGI2_EXTENSIONS,
  1640. CGI2_ENVIRONMENT,
  1641. CGI2_INTERPRETER,
  1642. CGI2_INTERPRETER_ARGS,
  1643. #if defined(USE_TIMERS)
  1644. CGI2_TIMEOUT,
  1645. #endif
  1646. #if defined(USE_4_CGI)
  1647. CGI3_EXTENSIONS,
  1648. CGI3_ENVIRONMENT,
  1649. CGI3_INTERPRETER,
  1650. CGI3_INTERPRETER_ARGS,
  1651. #if defined(USE_TIMERS)
  1652. CGI3_TIMEOUT,
  1653. #endif
  1654. CGI4_EXTENSIONS,
  1655. CGI4_ENVIRONMENT,
  1656. CGI4_INTERPRETER,
  1657. CGI4_INTERPRETER_ARGS,
  1658. #if defined(USE_TIMERS)
  1659. CGI4_TIMEOUT,
  1660. #endif
  1661. #endif
  1662. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1663. PROTECT_URI,
  1664. AUTHENTICATION_DOMAIN,
  1665. ENABLE_AUTH_DOMAIN_CHECK,
  1666. SSI_EXTENSIONS,
  1667. ENABLE_DIRECTORY_LISTING,
  1668. GLOBAL_PASSWORDS_FILE,
  1669. INDEX_FILES,
  1670. ACCESS_CONTROL_LIST,
  1671. EXTRA_MIME_TYPES,
  1672. SSL_CERTIFICATE,
  1673. SSL_CERTIFICATE_CHAIN,
  1674. URL_REWRITE_PATTERN,
  1675. HIDE_FILES,
  1676. SSL_DO_VERIFY_PEER,
  1677. SSL_CACHE_TIMEOUT,
  1678. SSL_CA_PATH,
  1679. SSL_CA_FILE,
  1680. SSL_VERIFY_DEPTH,
  1681. SSL_DEFAULT_VERIFY_PATHS,
  1682. SSL_CIPHER_LIST,
  1683. SSL_PROTOCOL_VERSION,
  1684. SSL_SHORT_TRUST,
  1685. #if defined(USE_LUA)
  1686. LUA_PRELOAD_FILE,
  1687. LUA_SCRIPT_EXTENSIONS,
  1688. LUA_SERVER_PAGE_EXTENSIONS,
  1689. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1690. LUA_DEBUG_PARAMS,
  1691. #endif
  1692. #endif
  1693. #if defined(USE_DUKTAPE)
  1694. DUKTAPE_SCRIPT_EXTENSIONS,
  1695. #endif
  1696. #if defined(USE_WEBSOCKET)
  1697. WEBSOCKET_ROOT,
  1698. #endif
  1699. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1700. LUA_WEBSOCKET_EXTENSIONS,
  1701. #endif
  1702. ACCESS_CONTROL_ALLOW_ORIGIN,
  1703. ACCESS_CONTROL_ALLOW_METHODS,
  1704. ACCESS_CONTROL_ALLOW_HEADERS,
  1705. ERROR_PAGES,
  1706. #if !defined(NO_CACHING)
  1707. STATIC_FILE_MAX_AGE,
  1708. STATIC_FILE_CACHE_CONTROL,
  1709. #endif
  1710. #if !defined(NO_SSL)
  1711. STRICT_HTTPS_MAX_AGE,
  1712. #endif
  1713. ADDITIONAL_HEADER,
  1714. ALLOW_INDEX_SCRIPT_SUB_RES,
  1715. NUM_OPTIONS
  1716. };
  1717. /* Config option name, config types, default value.
  1718. * Must be in the same order as the enum const above.
  1719. */
  1720. static const struct mg_option config_options[] = {
  1721. /* Once for each server */
  1722. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1723. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1724. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1725. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1726. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1727. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1728. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1729. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1730. #if defined(__linux__)
  1731. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1732. #endif
  1733. #if defined(_WIN32)
  1734. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1735. #endif
  1736. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1737. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1738. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1739. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1740. #if defined(USE_WEBSOCKET)
  1741. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1742. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1743. #endif
  1744. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1745. #if defined(USE_LUA)
  1746. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1747. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1748. #endif
  1749. #if defined(USE_HTTP2)
  1750. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1751. #endif
  1752. /* Once for each domain */
  1753. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1754. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1755. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1756. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1757. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1758. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1759. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1760. #if defined(USE_TIMERS)
  1761. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1762. #endif
  1763. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1764. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1765. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1766. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1767. #if defined(USE_TIMERS)
  1768. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1769. #endif
  1770. #if defined(USE_4_CGI)
  1771. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1772. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1773. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1774. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1775. #if defined(USE_TIMERS)
  1776. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1777. #endif
  1778. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1779. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1780. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1781. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1782. #if defined(USE_TIMERS)
  1783. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1784. #endif
  1785. #endif
  1786. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1787. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1788. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1789. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1790. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1791. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1792. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1793. {"index_files",
  1794. MG_CONFIG_TYPE_STRING_LIST,
  1795. #if defined(USE_LUA)
  1796. "index.xhtml,index.html,index.htm,"
  1797. "index.lp,index.lsp,index.lua,index.cgi,"
  1798. "index.shtml,index.php"},
  1799. #else
  1800. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1801. #endif
  1802. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1803. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1804. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1805. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1806. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1808. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1809. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1810. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1811. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1812. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1813. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1814. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1815. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1816. * as a minimum in 2020 */
  1817. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1818. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1819. #if defined(USE_LUA)
  1820. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1821. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1822. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1823. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1824. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1825. #endif
  1826. #endif
  1827. #if defined(USE_DUKTAPE)
  1828. /* The support for duktape is still in alpha version state.
  1829. * The name of this config option might change. */
  1830. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1831. #endif
  1832. #if defined(USE_WEBSOCKET)
  1833. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1834. #endif
  1835. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1836. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1837. #endif
  1838. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1839. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1840. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1841. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1842. #if !defined(NO_CACHING)
  1843. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1844. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1845. #endif
  1846. #if !defined(NO_SSL)
  1847. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1848. #endif
  1849. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1850. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1851. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1852. /* Check if the config_options and the corresponding enum have compatible
  1853. * sizes. */
  1854. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1855. == (NUM_OPTIONS + 1),
  1856. "config_options and enum not sync");
  1857. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1858. struct mg_handler_info {
  1859. /* Name/Pattern of the URI. */
  1860. char *uri;
  1861. size_t uri_len;
  1862. /* handler type */
  1863. int handler_type;
  1864. /* Handler for http/https or authorization requests. */
  1865. mg_request_handler handler;
  1866. unsigned int refcount;
  1867. int removing;
  1868. /* Handler for ws/wss (websocket) requests. */
  1869. mg_websocket_connect_handler connect_handler;
  1870. mg_websocket_ready_handler ready_handler;
  1871. mg_websocket_data_handler data_handler;
  1872. mg_websocket_close_handler close_handler;
  1873. /* accepted subprotocols for ws/wss requests. */
  1874. struct mg_websocket_subprotocols *subprotocols;
  1875. /* Handler for authorization requests */
  1876. mg_authorization_handler auth_handler;
  1877. /* User supplied argument for the handler function. */
  1878. void *cbdata;
  1879. /* next handler in a linked list */
  1880. struct mg_handler_info *next;
  1881. };
  1882. enum {
  1883. CONTEXT_INVALID,
  1884. CONTEXT_SERVER,
  1885. CONTEXT_HTTP_CLIENT,
  1886. CONTEXT_WS_CLIENT
  1887. };
  1888. struct mg_domain_context {
  1889. SSL_CTX *ssl_ctx; /* SSL context */
  1890. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1891. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1892. int64_t ssl_cert_last_mtime;
  1893. /* Server nonce */
  1894. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1895. unsigned long nonce_count; /* Used nonces, used for authentication */
  1896. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1897. /* linked list of shared lua websockets */
  1898. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1899. #endif
  1900. /* Linked list of domains */
  1901. struct mg_domain_context *next;
  1902. };
  1903. /* Stop flag can be "volatile" or require a lock.
  1904. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1905. * states a read operation for int is always atomic. */
  1906. #if defined(STOP_FLAG_NEEDS_LOCK)
  1907. typedef ptrdiff_t volatile stop_flag_t;
  1908. static int
  1909. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  1910. {
  1911. stop_flag_t sf = mg_atomic_add(f, 0);
  1912. return (sf == 0);
  1913. }
  1914. static int
  1915. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1916. {
  1917. stop_flag_t sf = mg_atomic_add(f, 0);
  1918. return (sf == 2);
  1919. }
  1920. static void
  1921. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1922. {
  1923. stop_flag_t sf;
  1924. do {
  1925. sf = mg_atomic_compare_and_swap(f, *f, v);
  1926. } while (sf != v);
  1927. }
  1928. #else /* STOP_FLAG_NEEDS_LOCK */
  1929. typedef int volatile stop_flag_t;
  1930. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1931. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1932. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1933. #endif /* STOP_FLAG_NEEDS_LOCK */
  1934. struct mg_context {
  1935. /* Part 1 - Physical context:
  1936. * This holds threads, ports, timeouts, ...
  1937. * set for the entire server, independent from the
  1938. * addressed hostname.
  1939. */
  1940. /* Connection related */
  1941. int context_type; /* See CONTEXT_* above */
  1942. struct socket *listening_sockets;
  1943. struct mg_pollfd *listening_socket_fds;
  1944. unsigned int num_listening_sockets;
  1945. struct mg_connection *worker_connections; /* The connection struct, pre-
  1946. * allocated for each worker */
  1947. #if defined(USE_SERVER_STATS)
  1948. volatile ptrdiff_t active_connections;
  1949. volatile ptrdiff_t max_active_connections;
  1950. volatile ptrdiff_t total_connections;
  1951. volatile ptrdiff_t total_requests;
  1952. volatile int64_t total_data_read;
  1953. volatile int64_t total_data_written;
  1954. #endif
  1955. /* Thread related */
  1956. stop_flag_t stop_flag; /* Should we stop event loop */
  1957. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1958. pthread_t masterthreadid; /* The master thread ID */
  1959. unsigned int
  1960. cfg_worker_threads; /* The number of configured worker threads. */
  1961. pthread_t *worker_threadids; /* The worker thread IDs */
  1962. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1963. /* Connection to thread dispatching */
  1964. #if defined(ALTERNATIVE_QUEUE)
  1965. struct socket *client_socks;
  1966. void **client_wait_events;
  1967. #else
  1968. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  1969. worker thread */
  1970. volatile int sq_head; /* Head of the socket queue */
  1971. volatile int sq_tail; /* Tail of the socket queue */
  1972. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1973. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1974. volatile int sq_blocked; /* Status information: sq is full */
  1975. int sq_size; /* No of elements in socket queue */
  1976. #if defined(USE_SERVER_STATS)
  1977. int sq_max_fill;
  1978. #endif /* USE_SERVER_STATS */
  1979. #endif /* ALTERNATIVE_QUEUE */
  1980. /* Memory related */
  1981. unsigned int max_request_size; /* The max request size */
  1982. #if defined(USE_SERVER_STATS)
  1983. struct mg_memory_stat ctx_memory;
  1984. #endif
  1985. /* Operating system related */
  1986. char *systemName; /* What operating system is running */
  1987. time_t start_time; /* Server start time, used for authentication
  1988. * and for diagnstics. */
  1989. #if defined(USE_TIMERS)
  1990. struct ttimers *timers;
  1991. #endif
  1992. /* Lua specific: Background operations and shared websockets */
  1993. #if defined(USE_LUA)
  1994. void *lua_background_state; /* lua_State (here as void *) */
  1995. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  1996. int lua_bg_log_available; /* Use Lua background state for access log */
  1997. #endif
  1998. /* Server nonce */
  1999. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2000. * ssl_cert_last_mtime, nonce_count, and
  2001. * next (linked list) */
  2002. /* Server callbacks */
  2003. struct mg_callbacks callbacks; /* User-defined callback function */
  2004. void *user_data; /* User-defined data */
  2005. /* Part 2 - Logical domain:
  2006. * This holds hostname, TLS certificate, document root, ...
  2007. * set for a domain hosted at the server.
  2008. * There may be multiple domains hosted at one physical server.
  2009. * The default domain "dd" is the first element of a list of
  2010. * domains.
  2011. */
  2012. struct mg_domain_context dd; /* default domain */
  2013. };
  2014. #if defined(USE_SERVER_STATS)
  2015. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2016. static struct mg_memory_stat *
  2017. get_memory_stat(struct mg_context *ctx)
  2018. {
  2019. if (ctx) {
  2020. return &(ctx->ctx_memory);
  2021. }
  2022. return &mg_common_memory;
  2023. }
  2024. #endif
  2025. enum {
  2026. CONNECTION_TYPE_INVALID = 0,
  2027. CONNECTION_TYPE_REQUEST = 1,
  2028. CONNECTION_TYPE_RESPONSE = 2
  2029. };
  2030. enum {
  2031. PROTOCOL_TYPE_HTTP1 = 0,
  2032. PROTOCOL_TYPE_WEBSOCKET = 1,
  2033. PROTOCOL_TYPE_HTTP2 = 2
  2034. };
  2035. #if defined(USE_HTTP2)
  2036. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2037. #define HTTP2_DYN_TABLE_SIZE (256)
  2038. #endif
  2039. struct mg_http2_connection {
  2040. uint32_t stream_id;
  2041. uint32_t dyn_table_size;
  2042. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2043. };
  2044. #endif
  2045. struct mg_connection {
  2046. int connection_type; /* see CONNECTION_TYPE_* above */
  2047. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2048. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2049. fully sent */
  2050. #if defined(USE_HTTP2)
  2051. struct mg_http2_connection http2;
  2052. #endif
  2053. struct mg_request_info request_info;
  2054. struct mg_response_info response_info;
  2055. struct mg_context *phys_ctx;
  2056. struct mg_domain_context *dom_ctx;
  2057. #if defined(USE_SERVER_STATS)
  2058. int conn_state; /* 0 = undef, numerical value may change in different
  2059. * versions. For the current definition, see
  2060. * mg_get_connection_info_impl */
  2061. #endif
  2062. SSL *ssl; /* SSL descriptor */
  2063. struct socket client; /* Connected client */
  2064. time_t conn_birth_time; /* Time (wall clock) when connection was
  2065. * established */
  2066. #if defined(USE_SERVER_STATS)
  2067. time_t conn_close_time; /* Time (wall clock) when connection was
  2068. * closed (or 0 if still open) */
  2069. double processing_time; /* Procesing time for one request. */
  2070. #endif
  2071. struct timespec req_time; /* Time (since system start) when the request
  2072. * was received */
  2073. int64_t num_bytes_sent; /* Total bytes sent to client */
  2074. int64_t content_len; /* How many bytes of content can be read
  2075. * !is_chunked: Content-Length header value
  2076. * or -1 (until connection closed,
  2077. * not allowed for a request)
  2078. * is_chunked: >= 0, appended gradually
  2079. */
  2080. int64_t consumed_content; /* How many bytes of content have been read */
  2081. int is_chunked; /* Transfer-Encoding is chunked:
  2082. * 0 = not chunked,
  2083. * 1 = chunked, not yet, or some data read,
  2084. * 2 = chunked, has error,
  2085. * 3 = chunked, all data read except trailer,
  2086. * 4 = chunked, all data read
  2087. */
  2088. char *buf; /* Buffer for received data */
  2089. char *path_info; /* PATH_INFO part of the URL */
  2090. int must_close; /* 1 if connection must be closed */
  2091. int accept_gzip; /* 1 if gzip encoding is accepted */
  2092. int in_error_handler; /* 1 if in handler for user defined error
  2093. * pages */
  2094. #if defined(USE_WEBSOCKET)
  2095. int in_websocket_handling; /* 1 if in read_websocket */
  2096. #endif
  2097. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2098. && defined(MG_EXPERIMENTAL_INTERFACES)
  2099. /* Parameters for websocket data compression according to rfc7692 */
  2100. int websocket_deflate_server_max_windows_bits;
  2101. int websocket_deflate_client_max_windows_bits;
  2102. int websocket_deflate_server_no_context_takeover;
  2103. int websocket_deflate_client_no_context_takeover;
  2104. int websocket_deflate_initialized;
  2105. int websocket_deflate_flush;
  2106. z_stream websocket_deflate_state;
  2107. z_stream websocket_inflate_state;
  2108. #endif
  2109. int handled_requests; /* Number of requests handled by this connection
  2110. */
  2111. int buf_size; /* Buffer size */
  2112. int request_len; /* Size of the request + headers in a buffer */
  2113. int data_len; /* Total size of data in a buffer */
  2114. int status_code; /* HTTP reply status code, e.g. 200 */
  2115. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2116. * throttle */
  2117. time_t last_throttle_time; /* Last time throttled data was sent */
  2118. int last_throttle_bytes; /* Bytes sent this second */
  2119. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2120. * atomic transmissions for websockets */
  2121. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2122. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2123. #endif
  2124. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2125. * for quick access */
  2126. };
  2127. /* Directory entry */
  2128. struct de {
  2129. struct mg_connection *conn;
  2130. char *file_name;
  2131. struct mg_file_stat file;
  2132. };
  2133. #define mg_cry_internal(conn, fmt, ...) \
  2134. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2135. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2136. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2137. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2138. struct mg_context *ctx,
  2139. const char *func,
  2140. unsigned line,
  2141. const char *fmt,
  2142. ...) PRINTF_ARGS(5, 6);
  2143. #if !defined(NO_THREAD_NAME)
  2144. #if defined(_WIN32) && defined(_MSC_VER)
  2145. /* Set the thread name for debugging purposes in Visual Studio
  2146. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2147. */
  2148. #pragma pack(push, 8)
  2149. typedef struct tagTHREADNAME_INFO {
  2150. DWORD dwType; /* Must be 0x1000. */
  2151. LPCSTR szName; /* Pointer to name (in user addr space). */
  2152. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2153. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2154. } THREADNAME_INFO;
  2155. #pragma pack(pop)
  2156. #elif defined(__linux__)
  2157. #include <sys/prctl.h>
  2158. #include <sys/sendfile.h>
  2159. #if defined(ALTERNATIVE_QUEUE)
  2160. #include <sys/eventfd.h>
  2161. #endif /* ALTERNATIVE_QUEUE */
  2162. #if defined(ALTERNATIVE_QUEUE)
  2163. static void *
  2164. event_create(void)
  2165. {
  2166. int evhdl = eventfd(0, EFD_CLOEXEC);
  2167. int *ret;
  2168. if (evhdl == -1) {
  2169. /* Linux uses -1 on error, Windows NULL. */
  2170. /* However, Linux does not return 0 on success either. */
  2171. return 0;
  2172. }
  2173. ret = (int *)mg_malloc(sizeof(int));
  2174. if (ret) {
  2175. *ret = evhdl;
  2176. } else {
  2177. (void)close(evhdl);
  2178. }
  2179. return (void *)ret;
  2180. }
  2181. static int
  2182. event_wait(void *eventhdl)
  2183. {
  2184. uint64_t u;
  2185. int evhdl, s;
  2186. if (!eventhdl) {
  2187. /* error */
  2188. return 0;
  2189. }
  2190. evhdl = *(int *)eventhdl;
  2191. s = (int)read(evhdl, &u, sizeof(u));
  2192. if (s != sizeof(u)) {
  2193. /* error */
  2194. return 0;
  2195. }
  2196. (void)u; /* the value is not required */
  2197. return 1;
  2198. }
  2199. static int
  2200. event_signal(void *eventhdl)
  2201. {
  2202. uint64_t u = 1;
  2203. int evhdl, s;
  2204. if (!eventhdl) {
  2205. /* error */
  2206. return 0;
  2207. }
  2208. evhdl = *(int *)eventhdl;
  2209. s = (int)write(evhdl, &u, sizeof(u));
  2210. if (s != sizeof(u)) {
  2211. /* error */
  2212. return 0;
  2213. }
  2214. return 1;
  2215. }
  2216. static void
  2217. event_destroy(void *eventhdl)
  2218. {
  2219. int evhdl;
  2220. if (!eventhdl) {
  2221. /* error */
  2222. return;
  2223. }
  2224. evhdl = *(int *)eventhdl;
  2225. close(evhdl);
  2226. mg_free(eventhdl);
  2227. }
  2228. #endif
  2229. #endif
  2230. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2231. struct posix_event {
  2232. pthread_mutex_t mutex;
  2233. pthread_cond_t cond;
  2234. int signaled;
  2235. };
  2236. static void *
  2237. event_create(void)
  2238. {
  2239. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2240. if (ret == 0) {
  2241. /* out of memory */
  2242. return 0;
  2243. }
  2244. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2245. /* pthread mutex not available */
  2246. mg_free(ret);
  2247. return 0;
  2248. }
  2249. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2250. /* pthread cond not available */
  2251. pthread_mutex_destroy(&(ret->mutex));
  2252. mg_free(ret);
  2253. return 0;
  2254. }
  2255. ret->signaled = 0;
  2256. return (void *)ret;
  2257. }
  2258. static int
  2259. event_wait(void *eventhdl)
  2260. {
  2261. struct posix_event *ev = (struct posix_event *)eventhdl;
  2262. pthread_mutex_lock(&(ev->mutex));
  2263. while (!ev->signaled) {
  2264. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2265. }
  2266. ev->signaled = 0;
  2267. pthread_mutex_unlock(&(ev->mutex));
  2268. return 1;
  2269. }
  2270. static int
  2271. event_signal(void *eventhdl)
  2272. {
  2273. struct posix_event *ev = (struct posix_event *)eventhdl;
  2274. pthread_mutex_lock(&(ev->mutex));
  2275. pthread_cond_signal(&(ev->cond));
  2276. ev->signaled = 1;
  2277. pthread_mutex_unlock(&(ev->mutex));
  2278. return 1;
  2279. }
  2280. static void
  2281. event_destroy(void *eventhdl)
  2282. {
  2283. struct posix_event *ev = (struct posix_event *)eventhdl;
  2284. pthread_cond_destroy(&(ev->cond));
  2285. pthread_mutex_destroy(&(ev->mutex));
  2286. mg_free(ev);
  2287. }
  2288. #endif
  2289. static void
  2290. mg_set_thread_name(const char *name)
  2291. {
  2292. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2293. mg_snprintf(
  2294. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2295. #if defined(_WIN32)
  2296. #if defined(_MSC_VER)
  2297. /* Windows and Visual Studio Compiler */
  2298. __try {
  2299. THREADNAME_INFO info;
  2300. info.dwType = 0x1000;
  2301. info.szName = threadName;
  2302. info.dwThreadID = ~0U;
  2303. info.dwFlags = 0;
  2304. RaiseException(0x406D1388,
  2305. 0,
  2306. sizeof(info) / sizeof(ULONG_PTR),
  2307. (ULONG_PTR *)&info);
  2308. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2309. }
  2310. #elif defined(__MINGW32__)
  2311. /* No option known to set thread name for MinGW known */
  2312. #endif
  2313. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2314. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2315. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2316. #if defined(__MACH__)
  2317. /* OS X only current thread name can be changed */
  2318. (void)pthread_setname_np(threadName);
  2319. #else
  2320. (void)pthread_setname_np(pthread_self(), threadName);
  2321. #endif
  2322. #elif defined(__linux__)
  2323. /* On Linux we can use the prctl function.
  2324. * When building for Linux Standard Base (LSB) use
  2325. * NO_THREAD_NAME. However, thread names are a big
  2326. * help for debugging, so the stadard is to set them.
  2327. */
  2328. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2329. #endif
  2330. }
  2331. #else /* !defined(NO_THREAD_NAME) */
  2332. void
  2333. mg_set_thread_name(const char *threadName)
  2334. {
  2335. }
  2336. #endif
  2337. const struct mg_option *
  2338. mg_get_valid_options(void)
  2339. {
  2340. return config_options;
  2341. }
  2342. /* Do not open file (unused) */
  2343. #define MG_FOPEN_MODE_NONE (0)
  2344. /* Open file for read only access */
  2345. #define MG_FOPEN_MODE_READ (1)
  2346. /* Open file for writing, create and overwrite */
  2347. #define MG_FOPEN_MODE_WRITE (2)
  2348. /* Open file for writing, create and append */
  2349. #define MG_FOPEN_MODE_APPEND (4)
  2350. static int
  2351. is_file_opened(const struct mg_file_access *fileacc)
  2352. {
  2353. if (!fileacc) {
  2354. return 0;
  2355. }
  2356. return (fileacc->fp != NULL);
  2357. }
  2358. #if !defined(NO_FILESYSTEMS)
  2359. static int mg_stat(const struct mg_connection *conn,
  2360. const char *path,
  2361. struct mg_file_stat *filep);
  2362. /* Reject files with special characters (for Windows) */
  2363. static int
  2364. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2365. {
  2366. const uint8_t *c = (const uint8_t *)path;
  2367. (void)conn; /* not used */
  2368. if ((c == NULL) || (c[0] == 0)) {
  2369. /* Null pointer or empty path --> suspicious */
  2370. return 1;
  2371. }
  2372. #if defined(_WIN32)
  2373. while (*c) {
  2374. if (*c < 32) {
  2375. /* Control character */
  2376. return 1;
  2377. }
  2378. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2379. /* stdin/stdout redirection character */
  2380. return 1;
  2381. }
  2382. if ((*c == '*') || (*c == '?')) {
  2383. /* Wildcard character */
  2384. return 1;
  2385. }
  2386. if (*c == '"') {
  2387. /* Windows quotation */
  2388. return 1;
  2389. }
  2390. c++;
  2391. }
  2392. #endif
  2393. /* Nothing suspicious found */
  2394. return 0;
  2395. }
  2396. /* mg_fopen will open a file either in memory or on the disk.
  2397. * The input parameter path is a string in UTF-8 encoding.
  2398. * The input parameter mode is MG_FOPEN_MODE_*
  2399. * On success, fp will be set in the output struct mg_file.
  2400. * All status members will also be set.
  2401. * The function returns 1 on success, 0 on error. */
  2402. static int
  2403. mg_fopen(const struct mg_connection *conn,
  2404. const char *path,
  2405. int mode,
  2406. struct mg_file *filep)
  2407. {
  2408. int found;
  2409. if (!filep) {
  2410. return 0;
  2411. }
  2412. filep->access.fp = NULL;
  2413. if (mg_path_suspicious(conn, path)) {
  2414. return 0;
  2415. }
  2416. /* filep is initialized in mg_stat: all fields with memset to,
  2417. * some fields like size and modification date with values */
  2418. found = mg_stat(conn, path, &(filep->stat));
  2419. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2420. /* file does not exist and will not be created */
  2421. return 0;
  2422. }
  2423. #if defined(_WIN32)
  2424. {
  2425. wchar_t wbuf[UTF16_PATH_MAX];
  2426. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2427. switch (mode) {
  2428. case MG_FOPEN_MODE_READ:
  2429. filep->access.fp = _wfopen(wbuf, L"rb");
  2430. break;
  2431. case MG_FOPEN_MODE_WRITE:
  2432. filep->access.fp = _wfopen(wbuf, L"wb");
  2433. break;
  2434. case MG_FOPEN_MODE_APPEND:
  2435. filep->access.fp = _wfopen(wbuf, L"ab");
  2436. break;
  2437. }
  2438. }
  2439. #else
  2440. /* Linux et al already use unicode. No need to convert. */
  2441. switch (mode) {
  2442. case MG_FOPEN_MODE_READ:
  2443. filep->access.fp = fopen(path, "r");
  2444. break;
  2445. case MG_FOPEN_MODE_WRITE:
  2446. filep->access.fp = fopen(path, "w");
  2447. break;
  2448. case MG_FOPEN_MODE_APPEND:
  2449. filep->access.fp = fopen(path, "a");
  2450. break;
  2451. }
  2452. #endif
  2453. if (!found) {
  2454. /* File did not exist before fopen was called.
  2455. * Maybe it has been created now. Get stat info
  2456. * like creation time now. */
  2457. found = mg_stat(conn, path, &(filep->stat));
  2458. (void)found;
  2459. }
  2460. /* return OK if file is opened */
  2461. return (filep->access.fp != NULL);
  2462. }
  2463. /* return 0 on success, just like fclose */
  2464. static int
  2465. mg_fclose(struct mg_file_access *fileacc)
  2466. {
  2467. int ret = -1;
  2468. if (fileacc != NULL) {
  2469. if (fileacc->fp != NULL) {
  2470. ret = fclose(fileacc->fp);
  2471. }
  2472. /* reset all members of fileacc */
  2473. memset(fileacc, 0, sizeof(*fileacc));
  2474. }
  2475. return ret;
  2476. }
  2477. #endif /* NO_FILESYSTEMS */
  2478. static void
  2479. mg_strlcpy(char *dst, const char *src, size_t n)
  2480. {
  2481. for (; *src != '\0' && n > 1; n--) {
  2482. *dst++ = *src++;
  2483. }
  2484. *dst = '\0';
  2485. }
  2486. static int
  2487. lowercase(const char *s)
  2488. {
  2489. return tolower((unsigned char)*s);
  2490. }
  2491. int
  2492. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2493. {
  2494. int diff = 0;
  2495. if (len > 0) {
  2496. do {
  2497. diff = lowercase(s1++) - lowercase(s2++);
  2498. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2499. }
  2500. return diff;
  2501. }
  2502. int
  2503. mg_strcasecmp(const char *s1, const char *s2)
  2504. {
  2505. int diff;
  2506. do {
  2507. diff = lowercase(s1++) - lowercase(s2++);
  2508. } while (diff == 0 && s1[-1] != '\0');
  2509. return diff;
  2510. }
  2511. static char *
  2512. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2513. {
  2514. char *p;
  2515. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2516. * defined */
  2517. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2518. mg_strlcpy(p, ptr, len + 1);
  2519. }
  2520. return p;
  2521. }
  2522. static char *
  2523. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2524. {
  2525. return mg_strndup_ctx(str, strlen(str), ctx);
  2526. }
  2527. static char *
  2528. mg_strdup(const char *str)
  2529. {
  2530. return mg_strndup_ctx(str, strlen(str), NULL);
  2531. }
  2532. static const char *
  2533. mg_strcasestr(const char *big_str, const char *small_str)
  2534. {
  2535. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2536. if (big_len >= small_len) {
  2537. for (i = 0; i <= (big_len - small_len); i++) {
  2538. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2539. return big_str + i;
  2540. }
  2541. }
  2542. }
  2543. return NULL;
  2544. }
  2545. /* Return null terminated string of given maximum length.
  2546. * Report errors if length is exceeded. */
  2547. static void
  2548. mg_vsnprintf(const struct mg_connection *conn,
  2549. int *truncated,
  2550. char *buf,
  2551. size_t buflen,
  2552. const char *fmt,
  2553. va_list ap)
  2554. {
  2555. int n, ok;
  2556. if (buflen == 0) {
  2557. if (truncated) {
  2558. *truncated = 1;
  2559. }
  2560. return;
  2561. }
  2562. #if defined(__clang__)
  2563. #pragma clang diagnostic push
  2564. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2565. /* Using fmt as a non-literal is intended here, since it is mostly called
  2566. * indirectly by mg_snprintf */
  2567. #endif
  2568. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2569. ok = (n >= 0) && ((size_t)n < buflen);
  2570. #if defined(__clang__)
  2571. #pragma clang diagnostic pop
  2572. #endif
  2573. if (ok) {
  2574. if (truncated) {
  2575. *truncated = 0;
  2576. }
  2577. } else {
  2578. if (truncated) {
  2579. *truncated = 1;
  2580. }
  2581. mg_cry_internal(conn,
  2582. "truncating vsnprintf buffer: [%.*s]",
  2583. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2584. buf);
  2585. n = (int)buflen - 1;
  2586. }
  2587. buf[n] = '\0';
  2588. }
  2589. static void
  2590. mg_snprintf(const struct mg_connection *conn,
  2591. int *truncated,
  2592. char *buf,
  2593. size_t buflen,
  2594. const char *fmt,
  2595. ...)
  2596. {
  2597. va_list ap;
  2598. va_start(ap, fmt);
  2599. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2600. va_end(ap);
  2601. }
  2602. static int
  2603. get_option_index(const char *name)
  2604. {
  2605. int i;
  2606. for (i = 0; config_options[i].name != NULL; i++) {
  2607. if (strcmp(config_options[i].name, name) == 0) {
  2608. return i;
  2609. }
  2610. }
  2611. return -1;
  2612. }
  2613. const char *
  2614. mg_get_option(const struct mg_context *ctx, const char *name)
  2615. {
  2616. int i;
  2617. if ((i = get_option_index(name)) == -1) {
  2618. return NULL;
  2619. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2620. return "";
  2621. } else {
  2622. return ctx->dd.config[i];
  2623. }
  2624. }
  2625. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2626. struct mg_context *
  2627. mg_get_context(const struct mg_connection *conn)
  2628. {
  2629. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2630. }
  2631. void *
  2632. mg_get_user_data(const struct mg_context *ctx)
  2633. {
  2634. return (ctx == NULL) ? NULL : ctx->user_data;
  2635. }
  2636. void *
  2637. mg_get_user_context_data(const struct mg_connection *conn)
  2638. {
  2639. return mg_get_user_data(mg_get_context(conn));
  2640. }
  2641. void *
  2642. mg_get_thread_pointer(const struct mg_connection *conn)
  2643. {
  2644. /* both methods should return the same pointer */
  2645. if (conn) {
  2646. /* quick access, in case conn is known */
  2647. return conn->tls_user_ptr;
  2648. } else {
  2649. /* otherwise get pointer from thread local storage (TLS) */
  2650. struct mg_workerTLS *tls =
  2651. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2652. return tls->user_ptr;
  2653. }
  2654. }
  2655. void
  2656. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2657. {
  2658. if (const_conn != NULL) {
  2659. /* Const cast, since "const struct mg_connection *" does not mean
  2660. * the connection object is not modified. Here "const" is used,
  2661. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2662. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2663. conn->request_info.conn_data = data;
  2664. }
  2665. }
  2666. void *
  2667. mg_get_user_connection_data(const struct mg_connection *conn)
  2668. {
  2669. if (conn != NULL) {
  2670. return conn->request_info.conn_data;
  2671. }
  2672. return NULL;
  2673. }
  2674. #if defined(MG_LEGACY_INTERFACE)
  2675. /* Deprecated: Use mg_get_server_ports instead. */
  2676. size_t
  2677. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2678. {
  2679. size_t i;
  2680. if (!ctx) {
  2681. return 0;
  2682. }
  2683. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2684. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2685. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2686. }
  2687. return i;
  2688. }
  2689. #endif
  2690. int
  2691. mg_get_server_ports(const struct mg_context *ctx,
  2692. int size,
  2693. struct mg_server_port *ports)
  2694. {
  2695. int i, cnt = 0;
  2696. if (size <= 0) {
  2697. return -1;
  2698. }
  2699. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2700. if (!ctx) {
  2701. return -1;
  2702. }
  2703. if (!ctx->listening_sockets) {
  2704. return -1;
  2705. }
  2706. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2707. ports[cnt].port =
  2708. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2709. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2710. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2711. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2712. /* IPv4 */
  2713. ports[cnt].protocol = 1;
  2714. cnt++;
  2715. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2716. /* IPv6 */
  2717. ports[cnt].protocol = 3;
  2718. cnt++;
  2719. }
  2720. }
  2721. return cnt;
  2722. }
  2723. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2724. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2725. #endif
  2726. static void
  2727. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2728. {
  2729. buf[0] = '\0';
  2730. if (!usa) {
  2731. return;
  2732. }
  2733. if (usa->sa.sa_family == AF_INET) {
  2734. getnameinfo(&usa->sa,
  2735. sizeof(usa->sin),
  2736. buf,
  2737. (unsigned)len,
  2738. NULL,
  2739. 0,
  2740. NI_NUMERICHOST);
  2741. }
  2742. #if defined(USE_IPV6)
  2743. else if (usa->sa.sa_family == AF_INET6) {
  2744. getnameinfo(&usa->sa,
  2745. sizeof(usa->sin6),
  2746. buf,
  2747. (unsigned)len,
  2748. NULL,
  2749. 0,
  2750. NI_NUMERICHOST);
  2751. }
  2752. #endif
  2753. #if defined(USE_X_DOM_SOCKET)
  2754. else if (usa->sa.sa_family == AF_UNIX) {
  2755. /* TODO: Define a remote address for unix domain sockets.
  2756. * This code will always return "localhost", identical to http+tcp:
  2757. getnameinfo(&usa->sa,
  2758. sizeof(usa->sun),
  2759. buf,
  2760. (unsigned)len,
  2761. NULL,
  2762. 0,
  2763. NI_NUMERICHOST);
  2764. */
  2765. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2766. buf[len] = 0;
  2767. }
  2768. #endif
  2769. }
  2770. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2771. * included in all responses other than 100, 101, 5xx. */
  2772. static void
  2773. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2774. {
  2775. #if !defined(REENTRANT_TIME)
  2776. struct tm *tm;
  2777. tm = ((t != NULL) ? gmtime(t) : NULL);
  2778. if (tm != NULL) {
  2779. #else
  2780. struct tm _tm;
  2781. struct tm *tm = &_tm;
  2782. if (t != NULL) {
  2783. gmtime_r(t, tm);
  2784. #endif
  2785. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2786. } else {
  2787. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2788. buf[buf_len - 1] = '\0';
  2789. }
  2790. }
  2791. /* difftime for struct timespec. Return value is in seconds. */
  2792. static double
  2793. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2794. {
  2795. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2796. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2797. }
  2798. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2799. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2800. const char *func,
  2801. unsigned line,
  2802. const char *fmt,
  2803. va_list ap);
  2804. #include "external_mg_cry_internal_impl.inl"
  2805. #elif !defined(NO_FILESYSTEMS)
  2806. /* Print error message to the opened error log stream. */
  2807. static void
  2808. mg_cry_internal_impl(const struct mg_connection *conn,
  2809. const char *func,
  2810. unsigned line,
  2811. const char *fmt,
  2812. va_list ap)
  2813. {
  2814. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2815. struct mg_file fi;
  2816. time_t timestamp;
  2817. /* Unused, in the RELEASE build */
  2818. (void)func;
  2819. (void)line;
  2820. #if defined(GCC_DIAGNOSTIC)
  2821. #pragma GCC diagnostic push
  2822. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2823. #endif
  2824. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2825. #if defined(GCC_DIAGNOSTIC)
  2826. #pragma GCC diagnostic pop
  2827. #endif
  2828. buf[sizeof(buf) - 1] = 0;
  2829. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2830. if (!conn) {
  2831. puts(buf);
  2832. return;
  2833. }
  2834. /* Do not lock when getting the callback value, here and below.
  2835. * I suppose this is fine, since function cannot disappear in the
  2836. * same way string option can. */
  2837. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2838. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2839. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2840. if (mg_fopen(conn,
  2841. conn->dom_ctx->config[ERROR_LOG_FILE],
  2842. MG_FOPEN_MODE_APPEND,
  2843. &fi)
  2844. == 0) {
  2845. fi.access.fp = NULL;
  2846. }
  2847. } else {
  2848. fi.access.fp = NULL;
  2849. }
  2850. if (fi.access.fp != NULL) {
  2851. flockfile(fi.access.fp);
  2852. timestamp = time(NULL);
  2853. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2854. fprintf(fi.access.fp,
  2855. "[%010lu] [error] [client %s] ",
  2856. (unsigned long)timestamp,
  2857. src_addr);
  2858. if (conn->request_info.request_method != NULL) {
  2859. fprintf(fi.access.fp,
  2860. "%s %s: ",
  2861. conn->request_info.request_method,
  2862. conn->request_info.request_uri
  2863. ? conn->request_info.request_uri
  2864. : "");
  2865. }
  2866. fprintf(fi.access.fp, "%s", buf);
  2867. fputc('\n', fi.access.fp);
  2868. fflush(fi.access.fp);
  2869. funlockfile(fi.access.fp);
  2870. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2871. * mg_cry here anyway ;-) */
  2872. }
  2873. }
  2874. }
  2875. #else
  2876. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2877. #endif /* Externally provided function */
  2878. /* Construct fake connection structure. Used for logging, if connection
  2879. * is not applicable at the moment of logging. */
  2880. static struct mg_connection *
  2881. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2882. {
  2883. static const struct mg_connection conn_zero = {0};
  2884. *fc = conn_zero;
  2885. fc->phys_ctx = ctx;
  2886. fc->dom_ctx = &(ctx->dd);
  2887. return fc;
  2888. }
  2889. static void
  2890. mg_cry_internal_wrap(const struct mg_connection *conn,
  2891. struct mg_context *ctx,
  2892. const char *func,
  2893. unsigned line,
  2894. const char *fmt,
  2895. ...)
  2896. {
  2897. va_list ap;
  2898. va_start(ap, fmt);
  2899. if (!conn && ctx) {
  2900. struct mg_connection fc;
  2901. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2902. } else {
  2903. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2904. }
  2905. va_end(ap);
  2906. }
  2907. void
  2908. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2909. {
  2910. va_list ap;
  2911. va_start(ap, fmt);
  2912. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2913. va_end(ap);
  2914. }
  2915. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2916. const char *
  2917. mg_version(void)
  2918. {
  2919. return CIVETWEB_VERSION;
  2920. }
  2921. const struct mg_request_info *
  2922. mg_get_request_info(const struct mg_connection *conn)
  2923. {
  2924. if (!conn) {
  2925. return NULL;
  2926. }
  2927. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2928. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2929. char txt[16];
  2930. struct mg_workerTLS *tls =
  2931. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2932. sprintf(txt, "%03i", conn->response_info.status_code);
  2933. if (strlen(txt) == 3) {
  2934. memcpy(tls->txtbuf, txt, 4);
  2935. } else {
  2936. strcpy(tls->txtbuf, "ERR");
  2937. }
  2938. ((struct mg_connection *)conn)->request_info.local_uri =
  2939. tls->txtbuf; /* use thread safe buffer */
  2940. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2941. tls->txtbuf; /* use the same thread safe buffer */
  2942. ((struct mg_connection *)conn)->request_info.request_uri =
  2943. tls->txtbuf; /* use the same thread safe buffer */
  2944. ((struct mg_connection *)conn)->request_info.num_headers =
  2945. conn->response_info.num_headers;
  2946. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2947. conn->response_info.http_headers,
  2948. sizeof(conn->response_info.http_headers));
  2949. } else
  2950. #endif
  2951. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2952. return NULL;
  2953. }
  2954. return &conn->request_info;
  2955. }
  2956. const struct mg_response_info *
  2957. mg_get_response_info(const struct mg_connection *conn)
  2958. {
  2959. if (!conn) {
  2960. return NULL;
  2961. }
  2962. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2963. return NULL;
  2964. }
  2965. return &conn->response_info;
  2966. }
  2967. static const char *
  2968. get_proto_name(const struct mg_connection *conn)
  2969. {
  2970. #if defined(__clang__)
  2971. #pragma clang diagnostic push
  2972. #pragma clang diagnostic ignored "-Wunreachable-code"
  2973. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2974. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2975. * unreachable, but splitting into four different #ifdef clauses here is
  2976. * more complicated.
  2977. */
  2978. #endif
  2979. const struct mg_request_info *ri = &conn->request_info;
  2980. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2981. ? (ri->is_ssl ? "wss" : "ws")
  2982. : (ri->is_ssl ? "https" : "http"));
  2983. return proto;
  2984. #if defined(__clang__)
  2985. #pragma clang diagnostic pop
  2986. #endif
  2987. }
  2988. static int
  2989. mg_construct_local_link(const struct mg_connection *conn,
  2990. char *buf,
  2991. size_t buflen,
  2992. const char *define_proto,
  2993. int define_port,
  2994. const char *define_uri)
  2995. {
  2996. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2997. return -1;
  2998. } else {
  2999. int truncated = 0;
  3000. const struct mg_request_info *ri = &conn->request_info;
  3001. const char *proto =
  3002. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3003. const char *uri =
  3004. (define_uri != NULL)
  3005. ? define_uri
  3006. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3007. int port = (define_port > 0) ? define_port : ri->server_port;
  3008. int default_port = 80;
  3009. if (uri == NULL) {
  3010. return -1;
  3011. }
  3012. #if defined(USE_X_DOM_SOCKET)
  3013. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3014. /* TODO: Define and document a link for UNIX domain sockets. */
  3015. /* There seems to be no official standard for this.
  3016. * Common uses seem to be "httpunix://", "http.unix://" or
  3017. * "http+unix://" as a protocol definition string, followed by
  3018. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3019. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3020. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3021. * "" (completely skipping the server name part). In any case, the
  3022. * last part is the server local path. */
  3023. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3024. mg_snprintf(conn,
  3025. &truncated,
  3026. buf,
  3027. buflen,
  3028. "%s.unix://%s%s",
  3029. proto,
  3030. server_name,
  3031. ri->local_uri);
  3032. default_port = 0;
  3033. return 0;
  3034. }
  3035. #endif
  3036. if (define_proto) {
  3037. /* If we got a protocol name, use the default port accordingly. */
  3038. if ((0 == strcmp(define_proto, "https"))
  3039. || (0 == strcmp(define_proto, "wss"))) {
  3040. default_port = 443;
  3041. }
  3042. } else if (ri->is_ssl) {
  3043. /* If we did not get a protocol name, use TLS as default if it is
  3044. * already used. */
  3045. default_port = 443;
  3046. }
  3047. {
  3048. #if defined(USE_IPV6)
  3049. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3050. #endif
  3051. int auth_domain_check_enabled =
  3052. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3053. && (!mg_strcasecmp(
  3054. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3055. const char *server_domain =
  3056. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3057. char portstr[16];
  3058. char server_ip[48];
  3059. if (port != default_port) {
  3060. sprintf(portstr, ":%u", (unsigned)port);
  3061. } else {
  3062. portstr[0] = 0;
  3063. }
  3064. if (!auth_domain_check_enabled || !server_domain) {
  3065. sockaddr_to_string(server_ip,
  3066. sizeof(server_ip),
  3067. &conn->client.lsa);
  3068. server_domain = server_ip;
  3069. }
  3070. mg_snprintf(conn,
  3071. &truncated,
  3072. buf,
  3073. buflen,
  3074. #if defined(USE_IPV6)
  3075. "%s://%s%s%s%s%s",
  3076. proto,
  3077. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3078. server_domain,
  3079. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3080. #else
  3081. "%s://%s%s%s",
  3082. proto,
  3083. server_domain,
  3084. #endif
  3085. portstr,
  3086. ri->local_uri);
  3087. if (truncated) {
  3088. return -1;
  3089. }
  3090. return 0;
  3091. }
  3092. }
  3093. }
  3094. int
  3095. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3096. {
  3097. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3098. }
  3099. /* Skip the characters until one of the delimiters characters found.
  3100. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3101. * Advance pointer to buffer to the next word. Return found 0-terminated
  3102. * word.
  3103. * Delimiters can be quoted with quotechar. */
  3104. static char *
  3105. skip_quoted(char **buf,
  3106. const char *delimiters,
  3107. const char *whitespace,
  3108. char quotechar)
  3109. {
  3110. char *p, *begin_word, *end_word, *end_whitespace;
  3111. begin_word = *buf;
  3112. end_word = begin_word + strcspn(begin_word, delimiters);
  3113. /* Check for quotechar */
  3114. if (end_word > begin_word) {
  3115. p = end_word - 1;
  3116. while (*p == quotechar) {
  3117. /* While the delimiter is quoted, look for the next delimiter.
  3118. */
  3119. /* This happens, e.g., in calls from parse_auth_header,
  3120. * if the user name contains a " character. */
  3121. /* If there is anything beyond end_word, copy it. */
  3122. if (*end_word != '\0') {
  3123. size_t end_off = strcspn(end_word + 1, delimiters);
  3124. memmove(p, end_word, end_off + 1);
  3125. p += end_off; /* p must correspond to end_word - 1 */
  3126. end_word += end_off + 1;
  3127. } else {
  3128. *p = '\0';
  3129. break;
  3130. }
  3131. }
  3132. for (p++; p < end_word; p++) {
  3133. *p = '\0';
  3134. }
  3135. }
  3136. if (*end_word == '\0') {
  3137. *buf = end_word;
  3138. } else {
  3139. #if defined(GCC_DIAGNOSTIC)
  3140. /* Disable spurious conversion warning for GCC */
  3141. #pragma GCC diagnostic push
  3142. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3143. #endif /* defined(GCC_DIAGNOSTIC) */
  3144. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3145. #if defined(GCC_DIAGNOSTIC)
  3146. #pragma GCC diagnostic pop
  3147. #endif /* defined(GCC_DIAGNOSTIC) */
  3148. for (p = end_word; p < end_whitespace; p++) {
  3149. *p = '\0';
  3150. }
  3151. *buf = end_whitespace;
  3152. }
  3153. return begin_word;
  3154. }
  3155. /* Return HTTP header value, or NULL if not found. */
  3156. static const char *
  3157. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3158. {
  3159. int i;
  3160. for (i = 0; i < num_hdr; i++) {
  3161. if (!mg_strcasecmp(name, hdr[i].name)) {
  3162. return hdr[i].value;
  3163. }
  3164. }
  3165. return NULL;
  3166. }
  3167. #if defined(USE_WEBSOCKET)
  3168. /* Retrieve requested HTTP header multiple values, and return the number of
  3169. * found occurrences */
  3170. static int
  3171. get_req_headers(const struct mg_request_info *ri,
  3172. const char *name,
  3173. const char **output,
  3174. int output_max_size)
  3175. {
  3176. int i;
  3177. int cnt = 0;
  3178. if (ri) {
  3179. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3180. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3181. output[cnt++] = ri->http_headers[i].value;
  3182. }
  3183. }
  3184. }
  3185. return cnt;
  3186. }
  3187. #endif
  3188. const char *
  3189. mg_get_header(const struct mg_connection *conn, const char *name)
  3190. {
  3191. if (!conn) {
  3192. return NULL;
  3193. }
  3194. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3195. return get_header(conn->request_info.http_headers,
  3196. conn->request_info.num_headers,
  3197. name);
  3198. }
  3199. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3200. return get_header(conn->response_info.http_headers,
  3201. conn->response_info.num_headers,
  3202. name);
  3203. }
  3204. return NULL;
  3205. }
  3206. static const char *
  3207. get_http_version(const struct mg_connection *conn)
  3208. {
  3209. if (!conn) {
  3210. return NULL;
  3211. }
  3212. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3213. return conn->request_info.http_version;
  3214. }
  3215. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3216. return conn->response_info.http_version;
  3217. }
  3218. return NULL;
  3219. }
  3220. /* A helper function for traversing a comma separated list of values.
  3221. * It returns a list pointer shifted to the next value, or NULL if the end
  3222. * of the list found.
  3223. * Value is stored in val vector. If value has form "x=y", then eq_val
  3224. * vector is initialized to point to the "y" part, and val vector length
  3225. * is adjusted to point only to "x". */
  3226. static const char *
  3227. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3228. {
  3229. int end;
  3230. reparse:
  3231. if (val == NULL || list == NULL || *list == '\0') {
  3232. /* End of the list */
  3233. return NULL;
  3234. }
  3235. /* Skip over leading LWS */
  3236. while (*list == ' ' || *list == '\t')
  3237. list++;
  3238. val->ptr = list;
  3239. if ((list = strchr(val->ptr, ',')) != NULL) {
  3240. /* Comma found. Store length and shift the list ptr */
  3241. val->len = ((size_t)(list - val->ptr));
  3242. list++;
  3243. } else {
  3244. /* This value is the last one */
  3245. list = val->ptr + strlen(val->ptr);
  3246. val->len = ((size_t)(list - val->ptr));
  3247. }
  3248. /* Adjust length for trailing LWS */
  3249. end = (int)val->len - 1;
  3250. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3251. end--;
  3252. val->len = (size_t)(end) + (size_t)(1);
  3253. if (val->len == 0) {
  3254. /* Ignore any empty entries. */
  3255. goto reparse;
  3256. }
  3257. if (eq_val != NULL) {
  3258. /* Value has form "x=y", adjust pointers and lengths
  3259. * so that val points to "x", and eq_val points to "y". */
  3260. eq_val->len = 0;
  3261. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3262. if (eq_val->ptr != NULL) {
  3263. eq_val->ptr++; /* Skip over '=' character */
  3264. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3265. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3266. }
  3267. }
  3268. return list;
  3269. }
  3270. /* A helper function for checking if a comma separated list of values
  3271. * contains
  3272. * the given option (case insensitvely).
  3273. * 'header' can be NULL, in which case false is returned. */
  3274. static int
  3275. header_has_option(const char *header, const char *option)
  3276. {
  3277. struct vec opt_vec;
  3278. struct vec eq_vec;
  3279. DEBUG_ASSERT(option != NULL);
  3280. DEBUG_ASSERT(option[0] != '\0');
  3281. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3282. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3283. return 1;
  3284. }
  3285. return 0;
  3286. }
  3287. /* Perform case-insensitive match of string against pattern */
  3288. static ptrdiff_t
  3289. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3290. {
  3291. const char *or_str;
  3292. ptrdiff_t i, j, len, res;
  3293. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3294. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3295. return (res > 0) ? res
  3296. : match_prefix(or_str + 1,
  3297. (size_t)((pattern + pattern_len)
  3298. - (or_str + 1)),
  3299. str);
  3300. }
  3301. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3302. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3303. continue;
  3304. } else if (pattern[i] == '$') {
  3305. return (str[j] == '\0') ? j : -1;
  3306. } else if (pattern[i] == '*') {
  3307. i++;
  3308. if (pattern[i] == '*') {
  3309. i++;
  3310. len = (ptrdiff_t)strlen(str + j);
  3311. } else {
  3312. len = (ptrdiff_t)strcspn(str + j, "/");
  3313. }
  3314. if (i == (ptrdiff_t)pattern_len) {
  3315. return j + len;
  3316. }
  3317. do {
  3318. res = match_prefix(pattern + i,
  3319. (pattern_len - (size_t)i),
  3320. str + j + len);
  3321. } while (res == -1 && len-- > 0);
  3322. return (res == -1) ? -1 : j + res + len;
  3323. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3324. return -1;
  3325. }
  3326. }
  3327. return (ptrdiff_t)j;
  3328. }
  3329. static ptrdiff_t
  3330. match_prefix_strlen(const char *pattern, const char *str)
  3331. {
  3332. if (pattern == NULL) {
  3333. return -1;
  3334. }
  3335. return match_prefix(pattern, strlen(pattern), str);
  3336. }
  3337. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3338. * This function must tolerate situations when connection info is not
  3339. * set up, for example if request parsing failed. */
  3340. static int
  3341. should_keep_alive(const struct mg_connection *conn)
  3342. {
  3343. const char *http_version;
  3344. const char *header;
  3345. /* First satisfy needs of the server */
  3346. if ((conn == NULL) || conn->must_close) {
  3347. /* Close, if civetweb framework needs to close */
  3348. return 0;
  3349. }
  3350. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3351. /* Close, if keep alive is not enabled */
  3352. return 0;
  3353. }
  3354. /* Check explicit wish of the client */
  3355. header = mg_get_header(conn, "Connection");
  3356. if (header) {
  3357. /* If there is a connection header from the client, obey */
  3358. if (header_has_option(header, "keep-alive")) {
  3359. return 1;
  3360. }
  3361. return 0;
  3362. }
  3363. /* Use default of the standard */
  3364. http_version = get_http_version(conn);
  3365. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3366. /* HTTP 1.1 default is keep alive */
  3367. return 1;
  3368. }
  3369. /* HTTP 1.0 (and earlier) default is to close the connection */
  3370. return 0;
  3371. }
  3372. static int
  3373. should_decode_url(const struct mg_connection *conn)
  3374. {
  3375. if (!conn || !conn->dom_ctx) {
  3376. return 0;
  3377. }
  3378. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3379. }
  3380. static const char *
  3381. suggest_connection_header(const struct mg_connection *conn)
  3382. {
  3383. return should_keep_alive(conn) ? "keep-alive" : "close";
  3384. }
  3385. #include "response.inl"
  3386. static void
  3387. send_no_cache_header(struct mg_connection *conn)
  3388. {
  3389. /* Send all current and obsolete cache opt-out directives. */
  3390. mg_response_header_add(conn,
  3391. "Cache-Control",
  3392. "no-cache, no-store, "
  3393. "must-revalidate, private, max-age=0",
  3394. -1);
  3395. mg_response_header_add(conn, "Expires", "0", -1);
  3396. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3397. /* Obsolete, but still send it for HTTP/1.0 */
  3398. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3399. }
  3400. }
  3401. static void
  3402. send_static_cache_header(struct mg_connection *conn)
  3403. {
  3404. #if !defined(NO_CACHING)
  3405. int max_age;
  3406. char val[64];
  3407. const char *cache_control =
  3408. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3409. /* If there is a full cache-control option configured,0 use it */
  3410. if (cache_control != NULL) {
  3411. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3412. return;
  3413. }
  3414. /* Read the server config to check how long a file may be cached.
  3415. * The configuration is in seconds. */
  3416. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3417. if (max_age <= 0) {
  3418. /* 0 means "do not cache". All values <0 are reserved
  3419. * and may be used differently in the future. */
  3420. /* If a file should not be cached, do not only send
  3421. * max-age=0, but also pragmas and Expires headers. */
  3422. send_no_cache_header(conn);
  3423. return;
  3424. }
  3425. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3426. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3427. /* See also https://www.mnot.net/cache_docs/ */
  3428. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3429. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3430. * leap
  3431. * year to 31622400 seconds. For the moment, we just send whatever has
  3432. * been configured, still the behavior for >1 year should be considered
  3433. * as undefined. */
  3434. mg_snprintf(
  3435. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3436. mg_response_header_add(conn, "Cache-Control", val, -1);
  3437. #else /* NO_CACHING */
  3438. send_no_cache_header(conn);
  3439. #endif /* !NO_CACHING */
  3440. }
  3441. static void
  3442. send_additional_header(struct mg_connection *conn)
  3443. {
  3444. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3445. #if !defined(NO_SSL)
  3446. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3447. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3448. if (max_age >= 0) {
  3449. char val[64];
  3450. mg_snprintf(conn,
  3451. NULL,
  3452. val,
  3453. sizeof(val),
  3454. "max-age=%lu",
  3455. (unsigned long)max_age);
  3456. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3457. }
  3458. }
  3459. #endif
  3460. if (header && header[0]) {
  3461. mg_response_header_add_lines(conn, header);
  3462. }
  3463. }
  3464. #if !defined(NO_FILESYSTEMS)
  3465. static void handle_file_based_request(struct mg_connection *conn,
  3466. const char *path,
  3467. struct mg_file *filep);
  3468. #endif /* NO_FILESYSTEMS */
  3469. const char *
  3470. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3471. {
  3472. /* See IANA HTTP status code assignment:
  3473. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3474. */
  3475. switch (response_code) {
  3476. /* RFC2616 Section 10.1 - Informational 1xx */
  3477. case 100:
  3478. return "Continue"; /* RFC2616 Section 10.1.1 */
  3479. case 101:
  3480. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3481. case 102:
  3482. return "Processing"; /* RFC2518 Section 10.1 */
  3483. /* RFC2616 Section 10.2 - Successful 2xx */
  3484. case 200:
  3485. return "OK"; /* RFC2616 Section 10.2.1 */
  3486. case 201:
  3487. return "Created"; /* RFC2616 Section 10.2.2 */
  3488. case 202:
  3489. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3490. case 203:
  3491. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3492. case 204:
  3493. return "No Content"; /* RFC2616 Section 10.2.5 */
  3494. case 205:
  3495. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3496. case 206:
  3497. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3498. case 207:
  3499. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3500. */
  3501. case 208:
  3502. return "Already Reported"; /* RFC5842 Section 7.1 */
  3503. case 226:
  3504. return "IM used"; /* RFC3229 Section 10.4.1 */
  3505. /* RFC2616 Section 10.3 - Redirection 3xx */
  3506. case 300:
  3507. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3508. case 301:
  3509. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3510. case 302:
  3511. return "Found"; /* RFC2616 Section 10.3.3 */
  3512. case 303:
  3513. return "See Other"; /* RFC2616 Section 10.3.4 */
  3514. case 304:
  3515. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3516. case 305:
  3517. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3518. case 307:
  3519. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3520. case 308:
  3521. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3522. /* RFC2616 Section 10.4 - Client Error 4xx */
  3523. case 400:
  3524. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3525. case 401:
  3526. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3527. case 402:
  3528. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3529. case 403:
  3530. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3531. case 404:
  3532. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3533. case 405:
  3534. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3535. case 406:
  3536. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3537. case 407:
  3538. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3539. case 408:
  3540. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3541. case 409:
  3542. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3543. case 410:
  3544. return "Gone"; /* RFC2616 Section 10.4.11 */
  3545. case 411:
  3546. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3547. case 412:
  3548. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3549. case 413:
  3550. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3551. case 414:
  3552. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3553. case 415:
  3554. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3555. case 416:
  3556. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3557. */
  3558. case 417:
  3559. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3560. case 421:
  3561. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3562. case 422:
  3563. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3564. * Section 11.2 */
  3565. case 423:
  3566. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3567. case 424:
  3568. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3569. * Section 11.4 */
  3570. case 426:
  3571. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3572. case 428:
  3573. return "Precondition Required"; /* RFC 6585, Section 3 */
  3574. case 429:
  3575. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3576. case 431:
  3577. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3578. case 451:
  3579. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3580. * Section 3 */
  3581. /* RFC2616 Section 10.5 - Server Error 5xx */
  3582. case 500:
  3583. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3584. case 501:
  3585. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3586. case 502:
  3587. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3588. case 503:
  3589. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3590. case 504:
  3591. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3592. case 505:
  3593. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3594. case 506:
  3595. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3596. case 507:
  3597. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3598. * Section 11.5 */
  3599. case 508:
  3600. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3601. case 510:
  3602. return "Not Extended"; /* RFC 2774, Section 7 */
  3603. case 511:
  3604. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3605. /* Other status codes, not shown in the IANA HTTP status code
  3606. * assignment.
  3607. * E.g., "de facto" standards due to common use, ... */
  3608. case 418:
  3609. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3610. case 419:
  3611. return "Authentication Timeout"; /* common use */
  3612. case 420:
  3613. return "Enhance Your Calm"; /* common use */
  3614. case 440:
  3615. return "Login Timeout"; /* common use */
  3616. case 509:
  3617. return "Bandwidth Limit Exceeded"; /* common use */
  3618. default:
  3619. /* This error code is unknown. This should not happen. */
  3620. if (conn) {
  3621. mg_cry_internal(conn,
  3622. "Unknown HTTP response code: %u",
  3623. response_code);
  3624. }
  3625. /* Return at least a category according to RFC 2616 Section 10. */
  3626. if (response_code >= 100 && response_code < 200) {
  3627. /* Unknown informational status code */
  3628. return "Information";
  3629. }
  3630. if (response_code >= 200 && response_code < 300) {
  3631. /* Unknown success code */
  3632. return "Success";
  3633. }
  3634. if (response_code >= 300 && response_code < 400) {
  3635. /* Unknown redirection code */
  3636. return "Redirection";
  3637. }
  3638. if (response_code >= 400 && response_code < 500) {
  3639. /* Unknown request error code */
  3640. return "Client Error";
  3641. }
  3642. if (response_code >= 500 && response_code < 600) {
  3643. /* Unknown server error code */
  3644. return "Server Error";
  3645. }
  3646. /* Response code not even within reasonable range */
  3647. return "";
  3648. }
  3649. }
  3650. static int
  3651. mg_send_http_error_impl(struct mg_connection *conn,
  3652. int status,
  3653. const char *fmt,
  3654. va_list args)
  3655. {
  3656. char errmsg_buf[MG_BUF_LEN];
  3657. va_list ap;
  3658. int has_body;
  3659. #if !defined(NO_FILESYSTEMS)
  3660. char path_buf[UTF8_PATH_MAX];
  3661. int len, i, page_handler_found, scope, truncated;
  3662. const char *error_handler = NULL;
  3663. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3664. const char *error_page_file_ext, *tstr;
  3665. #endif /* NO_FILESYSTEMS */
  3666. int handled_by_callback = 0;
  3667. if ((conn == NULL) || (fmt == NULL)) {
  3668. return -2;
  3669. }
  3670. /* Set status (for log) */
  3671. conn->status_code = status;
  3672. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3673. has_body = ((status > 199) && (status != 204) && (status != 304));
  3674. /* Prepare message in buf, if required */
  3675. if (has_body
  3676. || (!conn->in_error_handler
  3677. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3678. /* Store error message in errmsg_buf */
  3679. va_copy(ap, args);
  3680. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3681. va_end(ap);
  3682. /* In a debug build, print all html errors */
  3683. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3684. }
  3685. /* If there is a http_error callback, call it.
  3686. * But don't do it recursively, if callback calls mg_send_http_error again.
  3687. */
  3688. if (!conn->in_error_handler
  3689. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3690. /* Mark in_error_handler to avoid recursion and call user callback. */
  3691. conn->in_error_handler = 1;
  3692. handled_by_callback =
  3693. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3694. == 0);
  3695. conn->in_error_handler = 0;
  3696. }
  3697. if (!handled_by_callback) {
  3698. /* Check for recursion */
  3699. if (conn->in_error_handler) {
  3700. DEBUG_TRACE(
  3701. "Recursion when handling error %u - fall back to default",
  3702. status);
  3703. #if !defined(NO_FILESYSTEMS)
  3704. } else {
  3705. /* Send user defined error pages, if defined */
  3706. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3707. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3708. page_handler_found = 0;
  3709. if (error_handler != NULL) {
  3710. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3711. switch (scope) {
  3712. case 1: /* Handler for specific error, e.g. 404 error */
  3713. mg_snprintf(conn,
  3714. &truncated,
  3715. path_buf,
  3716. sizeof(path_buf) - 32,
  3717. "%serror%03u.",
  3718. error_handler,
  3719. status);
  3720. break;
  3721. case 2: /* Handler for error group, e.g., 5xx error
  3722. * handler
  3723. * for all server errors (500-599) */
  3724. mg_snprintf(conn,
  3725. &truncated,
  3726. path_buf,
  3727. sizeof(path_buf) - 32,
  3728. "%serror%01uxx.",
  3729. error_handler,
  3730. status / 100);
  3731. break;
  3732. default: /* Handler for all errors */
  3733. mg_snprintf(conn,
  3734. &truncated,
  3735. path_buf,
  3736. sizeof(path_buf) - 32,
  3737. "%serror.",
  3738. error_handler);
  3739. break;
  3740. }
  3741. /* String truncation in buf may only occur if
  3742. * error_handler is too long. This string is
  3743. * from the config, not from a client. */
  3744. (void)truncated;
  3745. /* The following code is redundant, but it should avoid
  3746. * false positives in static source code analyzers and
  3747. * vulnerability scanners.
  3748. */
  3749. path_buf[sizeof(path_buf) - 32] = 0;
  3750. len = (int)strlen(path_buf);
  3751. if (len > (int)sizeof(path_buf) - 32) {
  3752. len = (int)sizeof(path_buf) - 32;
  3753. }
  3754. /* Start with the file extenstion from the configuration. */
  3755. tstr = strchr(error_page_file_ext, '.');
  3756. while (tstr) {
  3757. for (i = 1;
  3758. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3759. i++) {
  3760. /* buffer overrun is not possible here, since
  3761. * (i < 32) && (len < sizeof(path_buf) - 32)
  3762. * ==> (i + len) < sizeof(path_buf) */
  3763. path_buf[len + i - 1] = tstr[i];
  3764. }
  3765. /* buffer overrun is not possible here, since
  3766. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3767. * ==> (i + len) <= sizeof(path_buf) */
  3768. path_buf[len + i - 1] = 0;
  3769. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3770. DEBUG_TRACE("Check error page %s - found",
  3771. path_buf);
  3772. page_handler_found = 1;
  3773. break;
  3774. }
  3775. DEBUG_TRACE("Check error page %s - not found",
  3776. path_buf);
  3777. /* Continue with the next file extenstion from the
  3778. * configuration (if there is a next one). */
  3779. tstr = strchr(tstr + i, '.');
  3780. }
  3781. }
  3782. }
  3783. if (page_handler_found) {
  3784. conn->in_error_handler = 1;
  3785. handle_file_based_request(conn, path_buf, &error_page_file);
  3786. conn->in_error_handler = 0;
  3787. return 0;
  3788. }
  3789. #endif /* NO_FILESYSTEMS */
  3790. }
  3791. /* No custom error page. Send default error page. */
  3792. conn->must_close = 1;
  3793. mg_response_header_start(conn, status);
  3794. send_no_cache_header(conn);
  3795. send_additional_header(conn);
  3796. if (has_body) {
  3797. mg_response_header_add(conn,
  3798. "Content-Type",
  3799. "text/plain; charset=utf-8",
  3800. -1);
  3801. }
  3802. mg_response_header_send(conn);
  3803. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3804. if (has_body) {
  3805. /* For other errors, send a generic error message. */
  3806. const char *status_text = mg_get_response_code_text(conn, status);
  3807. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3808. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3809. } else {
  3810. /* No body allowed. Close the connection. */
  3811. DEBUG_TRACE("Error %i", status);
  3812. }
  3813. }
  3814. return 0;
  3815. }
  3816. int
  3817. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3818. {
  3819. va_list ap;
  3820. int ret;
  3821. va_start(ap, fmt);
  3822. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3823. va_end(ap);
  3824. return ret;
  3825. }
  3826. int
  3827. mg_send_http_ok(struct mg_connection *conn,
  3828. const char *mime_type,
  3829. long long content_length)
  3830. {
  3831. if ((mime_type == NULL) || (*mime_type == 0)) {
  3832. /* No content type defined: default to text/html */
  3833. mime_type = "text/html";
  3834. }
  3835. mg_response_header_start(conn, 200);
  3836. send_no_cache_header(conn);
  3837. send_additional_header(conn);
  3838. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3839. if (content_length < 0) {
  3840. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3841. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3842. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3843. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3844. }
  3845. } else {
  3846. char len[32];
  3847. int trunc = 0;
  3848. mg_snprintf(conn,
  3849. &trunc,
  3850. len,
  3851. sizeof(len),
  3852. "%" UINT64_FMT,
  3853. (uint64_t)content_length);
  3854. if (!trunc) {
  3855. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3856. * !trunc is always true */
  3857. mg_response_header_add(conn, "Content-Length", len, -1);
  3858. }
  3859. }
  3860. mg_response_header_send(conn);
  3861. return 0;
  3862. }
  3863. int
  3864. mg_send_http_redirect(struct mg_connection *conn,
  3865. const char *target_url,
  3866. int redirect_code)
  3867. {
  3868. /* Send a 30x redirect response.
  3869. *
  3870. * Redirect types (status codes):
  3871. *
  3872. * Status | Perm/Temp | Method | Version
  3873. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3874. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3875. * 303 | temporary | always use GET | HTTP/1.1
  3876. * 307 | temporary | always keep method | HTTP/1.1
  3877. * 308 | permanent | always keep method | HTTP/1.1
  3878. */
  3879. const char *redirect_text;
  3880. int ret;
  3881. size_t content_len = 0;
  3882. #if defined(MG_SEND_REDIRECT_BODY)
  3883. char reply[MG_BUF_LEN];
  3884. #endif
  3885. /* In case redirect_code=0, use 307. */
  3886. if (redirect_code == 0) {
  3887. redirect_code = 307;
  3888. }
  3889. /* In case redirect_code is none of the above, return error. */
  3890. if ((redirect_code != 301) && (redirect_code != 302)
  3891. && (redirect_code != 303) && (redirect_code != 307)
  3892. && (redirect_code != 308)) {
  3893. /* Parameter error */
  3894. return -2;
  3895. }
  3896. /* Get proper text for response code */
  3897. redirect_text = mg_get_response_code_text(conn, redirect_code);
  3898. /* If target_url is not defined, redirect to "/". */
  3899. if ((target_url == NULL) || (*target_url == 0)) {
  3900. target_url = "/";
  3901. }
  3902. #if defined(MG_SEND_REDIRECT_BODY)
  3903. /* TODO: condition name? */
  3904. /* Prepare a response body with a hyperlink.
  3905. *
  3906. * According to RFC2616 (and RFC1945 before):
  3907. * Unless the request method was HEAD, the entity of the
  3908. * response SHOULD contain a short hypertext note with a hyperlink to
  3909. * the new URI(s).
  3910. *
  3911. * However, this response body is not useful in M2M communication.
  3912. * Probably the original reason in the RFC was, clients not supporting
  3913. * a 30x HTTP redirect could still show the HTML page and let the user
  3914. * press the link. Since current browsers support 30x HTTP, the additional
  3915. * HTML body does not seem to make sense anymore.
  3916. *
  3917. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3918. * but it only notes:
  3919. * The server's response payload usually contains a short
  3920. * hypertext note with a hyperlink to the new URI(s).
  3921. *
  3922. * Deactivated by default. If you need the 30x body, set the define.
  3923. */
  3924. mg_snprintf(
  3925. conn,
  3926. NULL /* ignore truncation */,
  3927. reply,
  3928. sizeof(reply),
  3929. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3930. redirect_text,
  3931. target_url,
  3932. target_url);
  3933. content_len = strlen(reply);
  3934. #endif
  3935. /* Do not send any additional header. For all other options,
  3936. * including caching, there are suitable defaults. */
  3937. ret = mg_printf(conn,
  3938. "HTTP/1.1 %i %s\r\n"
  3939. "Location: %s\r\n"
  3940. "Content-Length: %u\r\n"
  3941. "Connection: %s\r\n\r\n",
  3942. redirect_code,
  3943. redirect_text,
  3944. target_url,
  3945. (unsigned int)content_len,
  3946. suggest_connection_header(conn));
  3947. #if defined(MG_SEND_REDIRECT_BODY)
  3948. /* Send response body */
  3949. if (ret > 0) {
  3950. /* ... unless it is a HEAD request */
  3951. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3952. ret = mg_write(conn, reply, content_len);
  3953. }
  3954. }
  3955. #endif
  3956. return (ret > 0) ? ret : -1;
  3957. }
  3958. #if defined(_WIN32)
  3959. /* Create substitutes for POSIX functions in Win32. */
  3960. #if defined(GCC_DIAGNOSTIC)
  3961. /* Show no warning in case system functions are not used. */
  3962. #pragma GCC diagnostic push
  3963. #pragma GCC diagnostic ignored "-Wunused-function"
  3964. #endif
  3965. static int
  3966. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3967. {
  3968. (void)unused;
  3969. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3970. InitializeCriticalSection(&mutex->sec);
  3971. return 0;
  3972. }
  3973. static int
  3974. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3975. {
  3976. DeleteCriticalSection(&mutex->sec);
  3977. return 0;
  3978. }
  3979. static int
  3980. pthread_mutex_lock(pthread_mutex_t *mutex)
  3981. {
  3982. EnterCriticalSection(&mutex->sec);
  3983. return 0;
  3984. }
  3985. static int
  3986. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3987. {
  3988. LeaveCriticalSection(&mutex->sec);
  3989. return 0;
  3990. }
  3991. FUNCTION_MAY_BE_UNUSED
  3992. static int
  3993. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3994. {
  3995. (void)unused;
  3996. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  3997. cv->waiting_thread = NULL;
  3998. return 0;
  3999. }
  4000. FUNCTION_MAY_BE_UNUSED
  4001. static int
  4002. pthread_cond_timedwait(pthread_cond_t *cv,
  4003. pthread_mutex_t *mutex,
  4004. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4005. {
  4006. struct mg_workerTLS **ptls,
  4007. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4008. int ok;
  4009. uint64_t nsnow, nswaitabs;
  4010. int64_t nswaitrel;
  4011. DWORD mswaitrel;
  4012. pthread_mutex_lock(&cv->threadIdSec);
  4013. /* Add this thread to cv's waiting list */
  4014. ptls = &cv->waiting_thread;
  4015. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4016. ;
  4017. tls->next_waiting_thread = NULL;
  4018. *ptls = tls;
  4019. pthread_mutex_unlock(&cv->threadIdSec);
  4020. if (abstime) {
  4021. nsnow = mg_get_current_time_ns();
  4022. nswaitabs =
  4023. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4024. nswaitrel = nswaitabs - nsnow;
  4025. if (nswaitrel < 0) {
  4026. nswaitrel = 0;
  4027. }
  4028. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4029. } else {
  4030. mswaitrel = (DWORD)INFINITE;
  4031. }
  4032. pthread_mutex_unlock(mutex);
  4033. ok = (WAIT_OBJECT_0
  4034. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4035. if (!ok) {
  4036. ok = 1;
  4037. pthread_mutex_lock(&cv->threadIdSec);
  4038. ptls = &cv->waiting_thread;
  4039. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4040. if (*ptls == tls) {
  4041. *ptls = tls->next_waiting_thread;
  4042. ok = 0;
  4043. break;
  4044. }
  4045. }
  4046. pthread_mutex_unlock(&cv->threadIdSec);
  4047. if (ok) {
  4048. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4049. (DWORD)INFINITE);
  4050. }
  4051. }
  4052. /* This thread has been removed from cv's waiting list */
  4053. pthread_mutex_lock(mutex);
  4054. return ok ? 0 : -1;
  4055. }
  4056. FUNCTION_MAY_BE_UNUSED
  4057. static int
  4058. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4059. {
  4060. return pthread_cond_timedwait(cv, mutex, NULL);
  4061. }
  4062. FUNCTION_MAY_BE_UNUSED
  4063. static int
  4064. pthread_cond_signal(pthread_cond_t *cv)
  4065. {
  4066. HANDLE wkup = NULL;
  4067. BOOL ok = FALSE;
  4068. pthread_mutex_lock(&cv->threadIdSec);
  4069. if (cv->waiting_thread) {
  4070. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4071. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4072. ok = SetEvent(wkup);
  4073. DEBUG_ASSERT(ok);
  4074. }
  4075. pthread_mutex_unlock(&cv->threadIdSec);
  4076. return ok ? 0 : 1;
  4077. }
  4078. FUNCTION_MAY_BE_UNUSED
  4079. static int
  4080. pthread_cond_broadcast(pthread_cond_t *cv)
  4081. {
  4082. pthread_mutex_lock(&cv->threadIdSec);
  4083. while (cv->waiting_thread) {
  4084. pthread_cond_signal(cv);
  4085. }
  4086. pthread_mutex_unlock(&cv->threadIdSec);
  4087. return 0;
  4088. }
  4089. FUNCTION_MAY_BE_UNUSED
  4090. static int
  4091. pthread_cond_destroy(pthread_cond_t *cv)
  4092. {
  4093. pthread_mutex_lock(&cv->threadIdSec);
  4094. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4095. pthread_mutex_unlock(&cv->threadIdSec);
  4096. pthread_mutex_destroy(&cv->threadIdSec);
  4097. return 0;
  4098. }
  4099. #if defined(ALTERNATIVE_QUEUE)
  4100. FUNCTION_MAY_BE_UNUSED
  4101. static void *
  4102. event_create(void)
  4103. {
  4104. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4105. }
  4106. FUNCTION_MAY_BE_UNUSED
  4107. static int
  4108. event_wait(void *eventhdl)
  4109. {
  4110. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4111. return (res == WAIT_OBJECT_0);
  4112. }
  4113. FUNCTION_MAY_BE_UNUSED
  4114. static int
  4115. event_signal(void *eventhdl)
  4116. {
  4117. return (int)SetEvent((HANDLE)eventhdl);
  4118. }
  4119. FUNCTION_MAY_BE_UNUSED
  4120. static void
  4121. event_destroy(void *eventhdl)
  4122. {
  4123. CloseHandle((HANDLE)eventhdl);
  4124. }
  4125. #endif
  4126. #if defined(GCC_DIAGNOSTIC)
  4127. /* Enable unused function warning again */
  4128. #pragma GCC diagnostic pop
  4129. #endif
  4130. /* For Windows, change all slashes to backslashes in path names. */
  4131. static void
  4132. change_slashes_to_backslashes(char *path)
  4133. {
  4134. int i;
  4135. for (i = 0; path[i] != '\0'; i++) {
  4136. if (path[i] == '/') {
  4137. path[i] = '\\';
  4138. }
  4139. /* remove double backslash (check i > 0 to preserve UNC paths,
  4140. * like \\server\file.txt) */
  4141. if ((i > 0) && (path[i] == '\\')) {
  4142. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4143. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4144. }
  4145. }
  4146. }
  4147. }
  4148. static int
  4149. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4150. {
  4151. int diff;
  4152. do {
  4153. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4154. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4155. s1++;
  4156. s2++;
  4157. } while ((diff == 0) && (s1[-1] != L'\0'));
  4158. return diff;
  4159. }
  4160. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4161. * wbuf and wbuf_len is a target buffer and its length. */
  4162. static void
  4163. path_to_unicode(const struct mg_connection *conn,
  4164. const char *path,
  4165. wchar_t *wbuf,
  4166. size_t wbuf_len)
  4167. {
  4168. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4169. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4170. DWORD long_len, err;
  4171. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4172. mg_strlcpy(buf, path, sizeof(buf));
  4173. change_slashes_to_backslashes(buf);
  4174. /* Convert to Unicode and back. If doubly-converted string does not
  4175. * match the original, something is fishy, reject. */
  4176. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4177. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4178. WideCharToMultiByte(
  4179. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4180. if (strcmp(buf, buf2) != 0) {
  4181. wbuf[0] = L'\0';
  4182. }
  4183. /* Windows file systems are not case sensitive, but you can still use
  4184. * uppercase and lowercase letters (on all modern file systems).
  4185. * The server can check if the URI uses the same upper/lowercase
  4186. * letters an the file system, effectively making Windows servers
  4187. * case sensitive (like Linux servers are). It is still not possible
  4188. * to use two files with the same name in different cases on Windows
  4189. * (like /a and /A) - this would be possible in Linux.
  4190. * As a default, Windows is not case sensitive, but the case sensitive
  4191. * file name check can be activated by an additional configuration. */
  4192. if (conn) {
  4193. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4194. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4195. "yes")) {
  4196. /* Use case sensitive compare function */
  4197. fcompare = wcscmp;
  4198. }
  4199. }
  4200. (void)conn; /* conn is currently unused */
  4201. /* Only accept a full file path, not a Windows short (8.3) path. */
  4202. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4203. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4204. if (long_len == 0) {
  4205. err = GetLastError();
  4206. if (err == ERROR_FILE_NOT_FOUND) {
  4207. /* File does not exist. This is not always a problem here. */
  4208. return;
  4209. }
  4210. }
  4211. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4212. /* Short name is used. */
  4213. wbuf[0] = L'\0';
  4214. }
  4215. }
  4216. #if !defined(NO_FILESYSTEMS)
  4217. /* Get file information, return 1 if file exists, 0 if not */
  4218. static int
  4219. mg_stat(const struct mg_connection *conn,
  4220. const char *path,
  4221. struct mg_file_stat *filep)
  4222. {
  4223. wchar_t wbuf[UTF16_PATH_MAX];
  4224. WIN32_FILE_ATTRIBUTE_DATA info;
  4225. time_t creation_time;
  4226. size_t len;
  4227. if (!filep) {
  4228. return 0;
  4229. }
  4230. memset(filep, 0, sizeof(*filep));
  4231. if (mg_path_suspicious(conn, path)) {
  4232. return 0;
  4233. }
  4234. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4235. /* Windows happily opens files with some garbage at the end of file name.
  4236. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4237. * "a.cgi", despite one would expect an error back. */
  4238. len = strlen(path);
  4239. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4240. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4241. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4242. filep->last_modified =
  4243. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4244. info.ftLastWriteTime.dwHighDateTime);
  4245. /* On Windows, the file creation time can be higher than the
  4246. * modification time, e.g. when a file is copied.
  4247. * Since the Last-Modified timestamp is used for caching
  4248. * it should be based on the most recent timestamp. */
  4249. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4250. info.ftCreationTime.dwHighDateTime);
  4251. if (creation_time > filep->last_modified) {
  4252. filep->last_modified = creation_time;
  4253. }
  4254. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4255. return 1;
  4256. }
  4257. return 0;
  4258. }
  4259. #endif
  4260. static int
  4261. mg_remove(const struct mg_connection *conn, const char *path)
  4262. {
  4263. wchar_t wbuf[UTF16_PATH_MAX];
  4264. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4265. return DeleteFileW(wbuf) ? 0 : -1;
  4266. }
  4267. static int
  4268. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4269. {
  4270. wchar_t wbuf[UTF16_PATH_MAX];
  4271. (void)mode;
  4272. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4273. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4274. }
  4275. /* Create substitutes for POSIX functions in Win32. */
  4276. #if defined(GCC_DIAGNOSTIC)
  4277. /* Show no warning in case system functions are not used. */
  4278. #pragma GCC diagnostic push
  4279. #pragma GCC diagnostic ignored "-Wunused-function"
  4280. #endif
  4281. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4282. FUNCTION_MAY_BE_UNUSED
  4283. static DIR *
  4284. mg_opendir(const struct mg_connection *conn, const char *name)
  4285. {
  4286. DIR *dir = NULL;
  4287. wchar_t wpath[UTF16_PATH_MAX];
  4288. DWORD attrs;
  4289. if (name == NULL) {
  4290. SetLastError(ERROR_BAD_ARGUMENTS);
  4291. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4292. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4293. } else {
  4294. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4295. attrs = GetFileAttributesW(wpath);
  4296. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4297. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4298. (void)wcscat(wpath, L"\\*");
  4299. dir->handle = FindFirstFileW(wpath, &dir->info);
  4300. dir->result.d_name[0] = '\0';
  4301. } else {
  4302. mg_free(dir);
  4303. dir = NULL;
  4304. }
  4305. }
  4306. return dir;
  4307. }
  4308. FUNCTION_MAY_BE_UNUSED
  4309. static int
  4310. mg_closedir(DIR *dir)
  4311. {
  4312. int result = 0;
  4313. if (dir != NULL) {
  4314. if (dir->handle != INVALID_HANDLE_VALUE)
  4315. result = FindClose(dir->handle) ? 0 : -1;
  4316. mg_free(dir);
  4317. } else {
  4318. result = -1;
  4319. SetLastError(ERROR_BAD_ARGUMENTS);
  4320. }
  4321. return result;
  4322. }
  4323. FUNCTION_MAY_BE_UNUSED
  4324. static struct dirent *
  4325. mg_readdir(DIR *dir)
  4326. {
  4327. struct dirent *result = 0;
  4328. if (dir) {
  4329. if (dir->handle != INVALID_HANDLE_VALUE) {
  4330. result = &dir->result;
  4331. (void)WideCharToMultiByte(CP_UTF8,
  4332. 0,
  4333. dir->info.cFileName,
  4334. -1,
  4335. result->d_name,
  4336. sizeof(result->d_name),
  4337. NULL,
  4338. NULL);
  4339. if (!FindNextFileW(dir->handle, &dir->info)) {
  4340. (void)FindClose(dir->handle);
  4341. dir->handle = INVALID_HANDLE_VALUE;
  4342. }
  4343. } else {
  4344. SetLastError(ERROR_FILE_NOT_FOUND);
  4345. }
  4346. } else {
  4347. SetLastError(ERROR_BAD_ARGUMENTS);
  4348. }
  4349. return result;
  4350. }
  4351. #if !defined(HAVE_POLL)
  4352. #undef POLLIN
  4353. #undef POLLPRI
  4354. #undef POLLOUT
  4355. #define POLLIN (1) /* Data ready - read will not block. */
  4356. #define POLLPRI (2) /* Priority data ready. */
  4357. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4358. FUNCTION_MAY_BE_UNUSED
  4359. static int
  4360. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4361. {
  4362. struct timeval tv;
  4363. fd_set rset;
  4364. fd_set wset;
  4365. unsigned int i;
  4366. int result;
  4367. SOCKET maxfd = 0;
  4368. memset(&tv, 0, sizeof(tv));
  4369. tv.tv_sec = milliseconds / 1000;
  4370. tv.tv_usec = (milliseconds % 1000) * 1000;
  4371. FD_ZERO(&rset);
  4372. FD_ZERO(&wset);
  4373. for (i = 0; i < n; i++) {
  4374. if (pfd[i].events & POLLIN) {
  4375. FD_SET(pfd[i].fd, &rset);
  4376. }
  4377. if (pfd[i].events & POLLOUT) {
  4378. FD_SET(pfd[i].fd, &wset);
  4379. }
  4380. pfd[i].revents = 0;
  4381. if (pfd[i].fd > maxfd) {
  4382. maxfd = pfd[i].fd;
  4383. }
  4384. }
  4385. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4386. for (i = 0; i < n; i++) {
  4387. if (FD_ISSET(pfd[i].fd, &rset)) {
  4388. pfd[i].revents |= POLLIN;
  4389. }
  4390. if (FD_ISSET(pfd[i].fd, &wset)) {
  4391. pfd[i].revents |= POLLOUT;
  4392. }
  4393. }
  4394. }
  4395. /* We should subtract the time used in select from remaining
  4396. * "milliseconds", in particular if called from mg_poll with a
  4397. * timeout quantum.
  4398. * Unfortunately, the remaining time is not stored in "tv" in all
  4399. * implementations, so the result in "tv" must be considered undefined.
  4400. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4401. return result;
  4402. }
  4403. #endif /* HAVE_POLL */
  4404. #if defined(GCC_DIAGNOSTIC)
  4405. /* Enable unused function warning again */
  4406. #pragma GCC diagnostic pop
  4407. #endif
  4408. static void
  4409. set_close_on_exec(SOCKET sock,
  4410. const struct mg_connection *conn /* may be null */,
  4411. struct mg_context *ctx /* may be null */)
  4412. {
  4413. (void)conn; /* Unused. */
  4414. (void)ctx;
  4415. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4416. }
  4417. int
  4418. mg_start_thread(mg_thread_func_t f, void *p)
  4419. {
  4420. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4421. /* Compile-time option to control stack size, e.g.
  4422. * -DUSE_STACK_SIZE=16384
  4423. */
  4424. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4425. == ((uintptr_t)(-1L)))
  4426. ? -1
  4427. : 0);
  4428. #else
  4429. return (
  4430. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4431. ? -1
  4432. : 0);
  4433. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4434. }
  4435. /* Start a thread storing the thread context. */
  4436. static int
  4437. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4438. void *p,
  4439. pthread_t *threadidptr)
  4440. {
  4441. uintptr_t uip;
  4442. HANDLE threadhandle;
  4443. int result = -1;
  4444. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4445. threadhandle = (HANDLE)uip;
  4446. if ((uip != 0) && (threadidptr != NULL)) {
  4447. *threadidptr = threadhandle;
  4448. result = 0;
  4449. }
  4450. return result;
  4451. }
  4452. /* Wait for a thread to finish. */
  4453. static int
  4454. mg_join_thread(pthread_t threadid)
  4455. {
  4456. int result;
  4457. DWORD dwevent;
  4458. result = -1;
  4459. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4460. if (dwevent == WAIT_FAILED) {
  4461. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4462. } else {
  4463. if (dwevent == WAIT_OBJECT_0) {
  4464. CloseHandle(threadid);
  4465. result = 0;
  4466. }
  4467. }
  4468. return result;
  4469. }
  4470. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4471. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4472. /* Create substitutes for POSIX functions in Win32. */
  4473. #if defined(GCC_DIAGNOSTIC)
  4474. /* Show no warning in case system functions are not used. */
  4475. #pragma GCC diagnostic push
  4476. #pragma GCC diagnostic ignored "-Wunused-function"
  4477. #endif
  4478. FUNCTION_MAY_BE_UNUSED
  4479. static HANDLE
  4480. dlopen(const char *dll_name, int flags)
  4481. {
  4482. wchar_t wbuf[UTF16_PATH_MAX];
  4483. (void)flags;
  4484. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4485. return LoadLibraryW(wbuf);
  4486. }
  4487. FUNCTION_MAY_BE_UNUSED
  4488. static int
  4489. dlclose(void *handle)
  4490. {
  4491. int result;
  4492. if (FreeLibrary((HMODULE)handle) != 0) {
  4493. result = 0;
  4494. } else {
  4495. result = -1;
  4496. }
  4497. return result;
  4498. }
  4499. #if defined(GCC_DIAGNOSTIC)
  4500. /* Enable unused function warning again */
  4501. #pragma GCC diagnostic pop
  4502. #endif
  4503. #endif
  4504. #if !defined(NO_CGI)
  4505. #define SIGKILL (0)
  4506. static int
  4507. kill(pid_t pid, int sig_num)
  4508. {
  4509. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4510. (void)CloseHandle((HANDLE)pid);
  4511. return 0;
  4512. }
  4513. #if !defined(WNOHANG)
  4514. #define WNOHANG (1)
  4515. #endif
  4516. static pid_t
  4517. waitpid(pid_t pid, int *status, int flags)
  4518. {
  4519. DWORD timeout = INFINITE;
  4520. DWORD waitres;
  4521. (void)status; /* Currently not used by any client here */
  4522. if ((flags | WNOHANG) == WNOHANG) {
  4523. timeout = 0;
  4524. }
  4525. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4526. if (waitres == WAIT_OBJECT_0) {
  4527. return pid;
  4528. }
  4529. if (waitres == WAIT_TIMEOUT) {
  4530. return 0;
  4531. }
  4532. return (pid_t)-1;
  4533. }
  4534. static void
  4535. trim_trailing_whitespaces(char *s)
  4536. {
  4537. char *e = s + strlen(s);
  4538. while ((e > s) && isspace((unsigned char)e[-1])) {
  4539. *(--e) = '\0';
  4540. }
  4541. }
  4542. static pid_t
  4543. spawn_process(struct mg_connection *conn,
  4544. const char *prog,
  4545. char *envblk,
  4546. char *envp[],
  4547. int fdin[2],
  4548. int fdout[2],
  4549. int fderr[2],
  4550. const char *dir,
  4551. unsigned char cgi_config_idx)
  4552. {
  4553. HANDLE me;
  4554. char *interp;
  4555. char *interp_arg = 0;
  4556. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4557. int truncated;
  4558. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4559. STARTUPINFOA si;
  4560. PROCESS_INFORMATION pi = {0};
  4561. (void)envp;
  4562. memset(&si, 0, sizeof(si));
  4563. si.cb = sizeof(si);
  4564. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4565. si.wShowWindow = SW_HIDE;
  4566. me = GetCurrentProcess();
  4567. DuplicateHandle(me,
  4568. (HANDLE)_get_osfhandle(fdin[0]),
  4569. me,
  4570. &si.hStdInput,
  4571. 0,
  4572. TRUE,
  4573. DUPLICATE_SAME_ACCESS);
  4574. DuplicateHandle(me,
  4575. (HANDLE)_get_osfhandle(fdout[1]),
  4576. me,
  4577. &si.hStdOutput,
  4578. 0,
  4579. TRUE,
  4580. DUPLICATE_SAME_ACCESS);
  4581. DuplicateHandle(me,
  4582. (HANDLE)_get_osfhandle(fderr[1]),
  4583. me,
  4584. &si.hStdError,
  4585. 0,
  4586. TRUE,
  4587. DUPLICATE_SAME_ACCESS);
  4588. /* Mark handles that should not be inherited. See
  4589. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4590. */
  4591. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4592. HANDLE_FLAG_INHERIT,
  4593. 0);
  4594. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4595. HANDLE_FLAG_INHERIT,
  4596. 0);
  4597. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4598. HANDLE_FLAG_INHERIT,
  4599. 0);
  4600. /* First check, if there is a CGI interpreter configured for all CGI
  4601. * scripts. */
  4602. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4603. if (interp != NULL) {
  4604. /* If there is a configured interpreter, check for additional arguments
  4605. */
  4606. interp_arg =
  4607. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4608. } else {
  4609. /* Otherwise, the interpreter must be stated in the first line of the
  4610. * CGI script file, after a #! (shebang) mark. */
  4611. buf[0] = buf[1] = '\0';
  4612. /* Get the full script path */
  4613. mg_snprintf(
  4614. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4615. if (truncated) {
  4616. pi.hProcess = (pid_t)-1;
  4617. goto spawn_cleanup;
  4618. }
  4619. /* Open the script file, to read the first line */
  4620. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4621. /* Read the first line of the script into the buffer */
  4622. mg_fgets(buf, sizeof(buf), &file);
  4623. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4624. buf[sizeof(buf) - 1] = '\0';
  4625. }
  4626. if ((buf[0] == '#') && (buf[1] == '!')) {
  4627. trim_trailing_whitespaces(buf + 2);
  4628. } else {
  4629. buf[2] = '\0';
  4630. }
  4631. interp = buf + 2;
  4632. }
  4633. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4634. if (interp[0] != '\0') {
  4635. /* This is an interpreted script file. We must call the interpreter. */
  4636. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4637. mg_snprintf(conn,
  4638. &truncated,
  4639. cmdline,
  4640. sizeof(cmdline),
  4641. "\"%s\" %s \"%s\\%s\"",
  4642. interp,
  4643. interp_arg,
  4644. full_dir,
  4645. prog);
  4646. } else {
  4647. mg_snprintf(conn,
  4648. &truncated,
  4649. cmdline,
  4650. sizeof(cmdline),
  4651. "\"%s\" \"%s\\%s\"",
  4652. interp,
  4653. full_dir,
  4654. prog);
  4655. }
  4656. } else {
  4657. /* This is (probably) a compiled program. We call it directly. */
  4658. mg_snprintf(conn,
  4659. &truncated,
  4660. cmdline,
  4661. sizeof(cmdline),
  4662. "\"%s\\%s\"",
  4663. full_dir,
  4664. prog);
  4665. }
  4666. if (truncated) {
  4667. pi.hProcess = (pid_t)-1;
  4668. goto spawn_cleanup;
  4669. }
  4670. DEBUG_TRACE("Running [%s]", cmdline);
  4671. if (CreateProcessA(NULL,
  4672. cmdline,
  4673. NULL,
  4674. NULL,
  4675. TRUE,
  4676. CREATE_NEW_PROCESS_GROUP,
  4677. envblk,
  4678. NULL,
  4679. &si,
  4680. &pi)
  4681. == 0) {
  4682. mg_cry_internal(
  4683. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4684. pi.hProcess = (pid_t)-1;
  4685. /* goto spawn_cleanup; */
  4686. }
  4687. spawn_cleanup:
  4688. (void)CloseHandle(si.hStdOutput);
  4689. (void)CloseHandle(si.hStdError);
  4690. (void)CloseHandle(si.hStdInput);
  4691. if (pi.hThread != NULL) {
  4692. (void)CloseHandle(pi.hThread);
  4693. }
  4694. return (pid_t)pi.hProcess;
  4695. }
  4696. #endif /* !NO_CGI */
  4697. static int
  4698. set_blocking_mode(SOCKET sock)
  4699. {
  4700. unsigned long non_blocking = 0;
  4701. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4702. }
  4703. static int
  4704. set_non_blocking_mode(SOCKET sock)
  4705. {
  4706. unsigned long non_blocking = 1;
  4707. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4708. }
  4709. #else
  4710. #if !defined(NO_FILESYSTEMS)
  4711. static int
  4712. mg_stat(const struct mg_connection *conn,
  4713. const char *path,
  4714. struct mg_file_stat *filep)
  4715. {
  4716. struct stat st;
  4717. if (!filep) {
  4718. return 0;
  4719. }
  4720. memset(filep, 0, sizeof(*filep));
  4721. if (mg_path_suspicious(conn, path)) {
  4722. return 0;
  4723. }
  4724. if (0 == stat(path, &st)) {
  4725. filep->size = (uint64_t)(st.st_size);
  4726. filep->last_modified = st.st_mtime;
  4727. filep->is_directory = S_ISDIR(st.st_mode);
  4728. return 1;
  4729. }
  4730. return 0;
  4731. }
  4732. #endif /* NO_FILESYSTEMS */
  4733. static void
  4734. set_close_on_exec(int fd,
  4735. const struct mg_connection *conn /* may be null */,
  4736. struct mg_context *ctx /* may be null */)
  4737. {
  4738. #if defined(__ZEPHYR__)
  4739. (void)fd;
  4740. (void)conn;
  4741. (void)ctx;
  4742. #else
  4743. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4744. if (conn || ctx) {
  4745. struct mg_connection fc;
  4746. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4747. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4748. __func__,
  4749. strerror(ERRNO));
  4750. }
  4751. }
  4752. #endif
  4753. }
  4754. int
  4755. mg_start_thread(mg_thread_func_t func, void *param)
  4756. {
  4757. pthread_t thread_id;
  4758. pthread_attr_t attr;
  4759. int result;
  4760. (void)pthread_attr_init(&attr);
  4761. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4762. #if defined(__ZEPHYR__)
  4763. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4764. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4765. /* Compile-time option to control stack size,
  4766. * e.g. -DUSE_STACK_SIZE=16384 */
  4767. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4768. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4769. result = pthread_create(&thread_id, &attr, func, param);
  4770. pthread_attr_destroy(&attr);
  4771. return result;
  4772. }
  4773. /* Start a thread storing the thread context. */
  4774. static int
  4775. mg_start_thread_with_id(mg_thread_func_t func,
  4776. void *param,
  4777. pthread_t *threadidptr)
  4778. {
  4779. pthread_t thread_id;
  4780. pthread_attr_t attr;
  4781. int result;
  4782. (void)pthread_attr_init(&attr);
  4783. #if defined(__ZEPHYR__)
  4784. pthread_attr_setstack(&attr,
  4785. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4786. ZEPHYR_STACK_SIZE);
  4787. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4788. /* Compile-time option to control stack size,
  4789. * e.g. -DUSE_STACK_SIZE=16384 */
  4790. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4791. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4792. result = pthread_create(&thread_id, &attr, func, param);
  4793. pthread_attr_destroy(&attr);
  4794. if ((result == 0) && (threadidptr != NULL)) {
  4795. *threadidptr = thread_id;
  4796. }
  4797. return result;
  4798. }
  4799. /* Wait for a thread to finish. */
  4800. static int
  4801. mg_join_thread(pthread_t threadid)
  4802. {
  4803. int result;
  4804. result = pthread_join(threadid, NULL);
  4805. return result;
  4806. }
  4807. #if !defined(NO_CGI)
  4808. static pid_t
  4809. spawn_process(struct mg_connection *conn,
  4810. const char *prog,
  4811. char *envblk,
  4812. char *envp[],
  4813. int fdin[2],
  4814. int fdout[2],
  4815. int fderr[2],
  4816. const char *dir,
  4817. unsigned char cgi_config_idx)
  4818. {
  4819. pid_t pid;
  4820. const char *interp;
  4821. (void)envblk;
  4822. if ((pid = fork()) == -1) {
  4823. /* Parent */
  4824. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4825. } else if (pid != 0) {
  4826. /* Make sure children close parent-side descriptors.
  4827. * The caller will close the child-side immediately. */
  4828. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4829. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4830. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4831. } else {
  4832. /* Child */
  4833. if (chdir(dir) != 0) {
  4834. mg_cry_internal(
  4835. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4836. } else if (dup2(fdin[0], 0) == -1) {
  4837. mg_cry_internal(conn,
  4838. "%s: dup2(%d, 0): %s",
  4839. __func__,
  4840. fdin[0],
  4841. strerror(ERRNO));
  4842. } else if (dup2(fdout[1], 1) == -1) {
  4843. mg_cry_internal(conn,
  4844. "%s: dup2(%d, 1): %s",
  4845. __func__,
  4846. fdout[1],
  4847. strerror(ERRNO));
  4848. } else if (dup2(fderr[1], 2) == -1) {
  4849. mg_cry_internal(conn,
  4850. "%s: dup2(%d, 2): %s",
  4851. __func__,
  4852. fderr[1],
  4853. strerror(ERRNO));
  4854. } else {
  4855. struct sigaction sa;
  4856. /* Keep stderr and stdout in two different pipes.
  4857. * Stdout will be sent back to the client,
  4858. * stderr should go into a server error log. */
  4859. (void)close(fdin[0]);
  4860. (void)close(fdout[1]);
  4861. (void)close(fderr[1]);
  4862. /* Close write end fdin and read end fdout and fderr */
  4863. (void)close(fdin[1]);
  4864. (void)close(fdout[0]);
  4865. (void)close(fderr[0]);
  4866. /* After exec, all signal handlers are restored to their default
  4867. * values, with one exception of SIGCHLD. According to
  4868. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4869. * will leave unchanged after exec if it was set to be ignored.
  4870. * Restore it to default action. */
  4871. memset(&sa, 0, sizeof(sa));
  4872. sa.sa_handler = SIG_DFL;
  4873. sigaction(SIGCHLD, &sa, NULL);
  4874. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4875. if (interp == NULL) {
  4876. /* no interpreter configured, call the programm directly */
  4877. (void)execle(prog, prog, NULL, envp);
  4878. mg_cry_internal(conn,
  4879. "%s: execle(%s): %s",
  4880. __func__,
  4881. prog,
  4882. strerror(ERRNO));
  4883. } else {
  4884. /* call the configured interpreter */
  4885. const char *interp_args =
  4886. conn->dom_ctx
  4887. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4888. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4889. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4890. } else {
  4891. (void)execle(interp, interp, prog, NULL, envp);
  4892. }
  4893. mg_cry_internal(conn,
  4894. "%s: execle(%s %s): %s",
  4895. __func__,
  4896. interp,
  4897. prog,
  4898. strerror(ERRNO));
  4899. }
  4900. }
  4901. exit(EXIT_FAILURE);
  4902. }
  4903. return pid;
  4904. }
  4905. #endif /* !NO_CGI */
  4906. static int
  4907. set_non_blocking_mode(SOCKET sock)
  4908. {
  4909. int flags = fcntl(sock, F_GETFL, 0);
  4910. if (flags < 0) {
  4911. return -1;
  4912. }
  4913. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4914. return -1;
  4915. }
  4916. return 0;
  4917. }
  4918. static int
  4919. set_blocking_mode(SOCKET sock)
  4920. {
  4921. int flags = fcntl(sock, F_GETFL, 0);
  4922. if (flags < 0) {
  4923. return -1;
  4924. }
  4925. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4926. return -1;
  4927. }
  4928. return 0;
  4929. }
  4930. #endif /* _WIN32 / else */
  4931. /* End of initial operating system specific define block. */
  4932. /* Get a random number (independent of C rand function) */
  4933. static uint64_t
  4934. get_random(void)
  4935. {
  4936. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4937. static uint64_t lcg = 0; /* Linear congruential generator */
  4938. uint64_t now = mg_get_current_time_ns();
  4939. if (lfsr == 0) {
  4940. /* lfsr will be only 0 if has not been initialized,
  4941. * so this code is called only once. */
  4942. lfsr = mg_get_current_time_ns();
  4943. lcg = mg_get_current_time_ns();
  4944. } else {
  4945. /* Get the next step of both random number generators. */
  4946. lfsr = (lfsr >> 1)
  4947. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4948. << 63);
  4949. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4950. }
  4951. /* Combining two pseudo-random number generators and a high resolution
  4952. * part
  4953. * of the current server time will make it hard (impossible?) to guess
  4954. * the
  4955. * next number. */
  4956. return (lfsr ^ lcg ^ now);
  4957. }
  4958. static int
  4959. mg_poll(struct mg_pollfd *pfd,
  4960. unsigned int n,
  4961. int milliseconds,
  4962. stop_flag_t *stop_flag)
  4963. {
  4964. /* Call poll, but only for a maximum time of a few seconds.
  4965. * This will allow to stop the server after some seconds, instead
  4966. * of having to wait for a long socket timeout. */
  4967. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4968. do {
  4969. int result;
  4970. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  4971. /* Shut down signal */
  4972. return -2;
  4973. }
  4974. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4975. ms_now = milliseconds;
  4976. }
  4977. result = poll(pfd, n, ms_now);
  4978. if (result != 0) {
  4979. /* Poll returned either success (1) or error (-1).
  4980. * Forward both to the caller. */
  4981. return result;
  4982. }
  4983. /* Poll returned timeout (0). */
  4984. if (milliseconds > 0) {
  4985. milliseconds -= ms_now;
  4986. }
  4987. } while (milliseconds > 0);
  4988. /* timeout: return 0 */
  4989. return 0;
  4990. }
  4991. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4992. * descriptor.
  4993. * Return value:
  4994. * >=0 .. number of bytes successfully written
  4995. * -1 .. timeout
  4996. * -2 .. error
  4997. */
  4998. static int
  4999. push_inner(struct mg_context *ctx,
  5000. FILE *fp,
  5001. SOCKET sock,
  5002. SSL *ssl,
  5003. const char *buf,
  5004. int len,
  5005. double timeout)
  5006. {
  5007. uint64_t start = 0, now = 0, timeout_ns = 0;
  5008. int n, err;
  5009. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5010. #if defined(_WIN32)
  5011. typedef int len_t;
  5012. #else
  5013. typedef size_t len_t;
  5014. #endif
  5015. if (timeout > 0) {
  5016. now = mg_get_current_time_ns();
  5017. start = now;
  5018. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5019. }
  5020. if (ctx == NULL) {
  5021. return -2;
  5022. }
  5023. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5024. if (ssl) {
  5025. return -2;
  5026. }
  5027. #endif
  5028. /* Try to read until it succeeds, fails, times out, or the server
  5029. * shuts down. */
  5030. for (;;) {
  5031. #if defined(USE_MBEDTLS)
  5032. if (ssl != NULL) {
  5033. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5034. if (n <= 0) {
  5035. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5036. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5037. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5038. n = 0;
  5039. } else {
  5040. fprintf(stderr, "SSL write failed, error %d\n", n);
  5041. return -2;
  5042. }
  5043. } else {
  5044. err = 0;
  5045. }
  5046. } else
  5047. #elif !defined(NO_SSL)
  5048. if (ssl != NULL) {
  5049. ERR_clear_error();
  5050. n = SSL_write(ssl, buf, len);
  5051. if (n <= 0) {
  5052. err = SSL_get_error(ssl, n);
  5053. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5054. err = ERRNO;
  5055. } else if ((err == SSL_ERROR_WANT_READ)
  5056. || (err == SSL_ERROR_WANT_WRITE)) {
  5057. n = 0;
  5058. } else {
  5059. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5060. ERR_clear_error();
  5061. return -2;
  5062. }
  5063. ERR_clear_error();
  5064. } else {
  5065. err = 0;
  5066. }
  5067. } else
  5068. #endif
  5069. if (fp != NULL) {
  5070. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5071. if (ferror(fp)) {
  5072. n = -1;
  5073. err = ERRNO;
  5074. } else {
  5075. err = 0;
  5076. }
  5077. } else {
  5078. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5079. err = (n < 0) ? ERRNO : 0;
  5080. #if defined(_WIN32)
  5081. if (err == WSAEWOULDBLOCK) {
  5082. err = 0;
  5083. n = 0;
  5084. }
  5085. #else
  5086. if (ERROR_TRY_AGAIN(err)) {
  5087. err = 0;
  5088. n = 0;
  5089. }
  5090. #endif
  5091. if (n < 0) {
  5092. /* shutdown of the socket at client side */
  5093. return -2;
  5094. }
  5095. }
  5096. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5097. return -2;
  5098. }
  5099. if ((n > 0) || ((n == 0) && (len == 0))) {
  5100. /* some data has been read, or no data was requested */
  5101. return n;
  5102. }
  5103. if (n < 0) {
  5104. /* socket error - check errno */
  5105. DEBUG_TRACE("send() failed, error %d", err);
  5106. /* TODO (mid): error handling depending on the error code.
  5107. * These codes are different between Windows and Linux.
  5108. * Currently there is no problem with failing send calls,
  5109. * if there is a reproducible situation, it should be
  5110. * investigated in detail.
  5111. */
  5112. return -2;
  5113. }
  5114. /* Only in case n=0 (timeout), repeat calling the write function */
  5115. /* If send failed, wait before retry */
  5116. if (fp != NULL) {
  5117. /* For files, just wait a fixed time.
  5118. * Maybe it helps, maybe not. */
  5119. mg_sleep(5);
  5120. } else {
  5121. /* For sockets, wait for the socket using poll */
  5122. struct mg_pollfd pfd[1];
  5123. int pollres;
  5124. pfd[0].fd = sock;
  5125. pfd[0].events = POLLOUT;
  5126. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5127. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5128. return -2;
  5129. }
  5130. if (pollres > 0) {
  5131. continue;
  5132. }
  5133. }
  5134. if (timeout > 0) {
  5135. now = mg_get_current_time_ns();
  5136. if ((now - start) > timeout_ns) {
  5137. /* Timeout */
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5143. used */
  5144. return -1;
  5145. }
  5146. static int
  5147. push_all(struct mg_context *ctx,
  5148. FILE *fp,
  5149. SOCKET sock,
  5150. SSL *ssl,
  5151. const char *buf,
  5152. int len)
  5153. {
  5154. double timeout = -1.0;
  5155. int n, nwritten = 0;
  5156. if (ctx == NULL) {
  5157. return -1;
  5158. }
  5159. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5160. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5161. }
  5162. if (timeout <= 0.0) {
  5163. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5164. }
  5165. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5166. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5167. if (n < 0) {
  5168. if (nwritten == 0) {
  5169. nwritten = -1; /* Propagate the error */
  5170. }
  5171. break;
  5172. } else if (n == 0) {
  5173. break; /* No more data to write */
  5174. } else {
  5175. nwritten += n;
  5176. len -= n;
  5177. }
  5178. }
  5179. return nwritten;
  5180. }
  5181. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5182. * Return value:
  5183. * >=0 .. number of bytes successfully read
  5184. * -1 .. timeout
  5185. * -2 .. error
  5186. */
  5187. static int
  5188. pull_inner(FILE *fp,
  5189. struct mg_connection *conn,
  5190. char *buf,
  5191. int len,
  5192. double timeout)
  5193. {
  5194. int nread, err = 0;
  5195. #if defined(_WIN32)
  5196. typedef int len_t;
  5197. #else
  5198. typedef size_t len_t;
  5199. #endif
  5200. /* We need an additional wait loop around this, because in some cases
  5201. * with TLSwe may get data from the socket but not from SSL_read.
  5202. * In this case we need to repeat at least once.
  5203. */
  5204. if (fp != NULL) {
  5205. /* Use read() instead of fread(), because if we're reading from the
  5206. * CGI pipe, fread() may block until IO buffer is filled up. We
  5207. * cannot afford to block and must pass all read bytes immediately
  5208. * to the client. */
  5209. nread = (int)read(fileno(fp), buf, (size_t)len);
  5210. err = (nread < 0) ? ERRNO : 0;
  5211. if ((nread == 0) && (len > 0)) {
  5212. /* Should get data, but got EOL */
  5213. return -2;
  5214. }
  5215. #if defined(USE_MBEDTLS)
  5216. } else if (conn->ssl != NULL) {
  5217. struct mg_pollfd pfd[1];
  5218. int to_read;
  5219. int pollres;
  5220. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5221. if (to_read > 0) {
  5222. /* We already know there is no more data buffered in conn->buf
  5223. * but there is more available in the SSL layer. So don't poll
  5224. * conn->client.sock yet. */
  5225. pollres = 1;
  5226. if (to_read > len)
  5227. to_read = len;
  5228. } else {
  5229. pfd[0].fd = conn->client.sock;
  5230. pfd[0].events = POLLIN;
  5231. to_read = len;
  5232. pollres = mg_poll(pfd,
  5233. 1,
  5234. (int)(timeout * 1000.0),
  5235. &(conn->phys_ctx->stop_flag));
  5236. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5237. return -2;
  5238. }
  5239. }
  5240. if (pollres > 0) {
  5241. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5242. if (nread <= 0) {
  5243. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5244. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5245. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5246. nread = 0;
  5247. } else {
  5248. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5249. return -2;
  5250. }
  5251. } else {
  5252. err = 0;
  5253. }
  5254. } else if (pollres < 0) {
  5255. /* Error */
  5256. return -2;
  5257. } else {
  5258. /* pollres = 0 means timeout */
  5259. nread = 0;
  5260. }
  5261. #elif !defined(NO_SSL)
  5262. } else if (conn->ssl != NULL) {
  5263. int ssl_pending;
  5264. struct mg_pollfd pfd[1];
  5265. int pollres;
  5266. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5267. /* We already know there is no more data buffered in conn->buf
  5268. * but there is more available in the SSL layer. So don't poll
  5269. * conn->client.sock yet. */
  5270. if (ssl_pending > len) {
  5271. ssl_pending = len;
  5272. }
  5273. pollres = 1;
  5274. } else {
  5275. pfd[0].fd = conn->client.sock;
  5276. pfd[0].events = POLLIN;
  5277. pollres = mg_poll(pfd,
  5278. 1,
  5279. (int)(timeout * 1000.0),
  5280. &(conn->phys_ctx->stop_flag));
  5281. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5282. return -2;
  5283. }
  5284. }
  5285. if (pollres > 0) {
  5286. ERR_clear_error();
  5287. nread =
  5288. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5289. if (nread <= 0) {
  5290. err = SSL_get_error(conn->ssl, nread);
  5291. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5292. err = ERRNO;
  5293. } else if ((err == SSL_ERROR_WANT_READ)
  5294. || (err == SSL_ERROR_WANT_WRITE)) {
  5295. nread = 0;
  5296. } else {
  5297. /* All errors should return -2 */
  5298. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5299. ERR_clear_error();
  5300. return -2;
  5301. }
  5302. ERR_clear_error();
  5303. } else {
  5304. err = 0;
  5305. }
  5306. } else if (pollres < 0) {
  5307. /* Error */
  5308. return -2;
  5309. } else {
  5310. /* pollres = 0 means timeout */
  5311. nread = 0;
  5312. }
  5313. #endif
  5314. } else {
  5315. struct mg_pollfd pfd[1];
  5316. int pollres;
  5317. pfd[0].fd = conn->client.sock;
  5318. pfd[0].events = POLLIN;
  5319. pollres = mg_poll(pfd,
  5320. 1,
  5321. (int)(timeout * 1000.0),
  5322. &(conn->phys_ctx->stop_flag));
  5323. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5324. return -2;
  5325. }
  5326. if (pollres > 0) {
  5327. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5328. err = (nread < 0) ? ERRNO : 0;
  5329. if (nread <= 0) {
  5330. /* shutdown of the socket at client side */
  5331. return -2;
  5332. }
  5333. } else if (pollres < 0) {
  5334. /* error callint poll */
  5335. return -2;
  5336. } else {
  5337. /* pollres = 0 means timeout */
  5338. nread = 0;
  5339. }
  5340. }
  5341. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5342. return -2;
  5343. }
  5344. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5345. /* some data has been read, or no data was requested */
  5346. return nread;
  5347. }
  5348. if (nread < 0) {
  5349. /* socket error - check errno */
  5350. #if defined(_WIN32)
  5351. if (err == WSAEWOULDBLOCK) {
  5352. /* TODO (low): check if this is still required */
  5353. /* standard case if called from close_socket_gracefully */
  5354. return -2;
  5355. } else if (err == WSAETIMEDOUT) {
  5356. /* TODO (low): check if this is still required */
  5357. /* timeout is handled by the while loop */
  5358. return 0;
  5359. } else if (err == WSAECONNABORTED) {
  5360. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5361. return -2;
  5362. } else {
  5363. DEBUG_TRACE("recv() failed, error %d", err);
  5364. return -2;
  5365. }
  5366. #else
  5367. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5368. * if the timeout is reached and if the socket was set to non-
  5369. * blocking in close_socket_gracefully, so we can not distinguish
  5370. * here. We have to wait for the timeout in both cases for now.
  5371. */
  5372. if (ERROR_TRY_AGAIN(err)) {
  5373. /* TODO (low): check if this is still required */
  5374. /* EAGAIN/EWOULDBLOCK:
  5375. * standard case if called from close_socket_gracefully
  5376. * => should return -1 */
  5377. /* or timeout occurred
  5378. * => the code must stay in the while loop */
  5379. /* EINTR can be generated on a socket with a timeout set even
  5380. * when SA_RESTART is effective for all relevant signals
  5381. * (see signal(7)).
  5382. * => stay in the while loop */
  5383. } else {
  5384. DEBUG_TRACE("recv() failed, error %d", err);
  5385. return -2;
  5386. }
  5387. #endif
  5388. }
  5389. /* Timeout occurred, but no data available. */
  5390. return -1;
  5391. }
  5392. static int
  5393. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5394. {
  5395. int n, nread = 0;
  5396. double timeout = -1.0;
  5397. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5398. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5399. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5400. }
  5401. if (timeout <= 0.0) {
  5402. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5403. }
  5404. start_time = mg_get_current_time_ns();
  5405. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5406. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5407. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5408. if (n == -2) {
  5409. if (nread == 0) {
  5410. nread = -1; /* Propagate the error */
  5411. }
  5412. break;
  5413. } else if (n == -1) {
  5414. /* timeout */
  5415. if (timeout >= 0.0) {
  5416. now = mg_get_current_time_ns();
  5417. if ((now - start_time) <= timeout_ns) {
  5418. continue;
  5419. }
  5420. }
  5421. break;
  5422. } else if (n == 0) {
  5423. break; /* No more data to read */
  5424. } else {
  5425. nread += n;
  5426. len -= n;
  5427. }
  5428. }
  5429. return nread;
  5430. }
  5431. static void
  5432. discard_unread_request_data(struct mg_connection *conn)
  5433. {
  5434. char buf[MG_BUF_LEN];
  5435. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5436. ;
  5437. }
  5438. static int
  5439. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5440. {
  5441. int64_t content_len, n, buffered_len, nread;
  5442. int64_t len64 =
  5443. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5444. * int, we may not read more
  5445. * bytes */
  5446. const char *body;
  5447. if (conn == NULL) {
  5448. return 0;
  5449. }
  5450. /* If Content-Length is not set for a response with body data,
  5451. * we do not know in advance how much data should be read. */
  5452. content_len = conn->content_len;
  5453. if (content_len < 0) {
  5454. /* The body data is completed when the connection is closed. */
  5455. content_len = INT64_MAX;
  5456. }
  5457. nread = 0;
  5458. if (conn->consumed_content < content_len) {
  5459. /* Adjust number of bytes to read. */
  5460. int64_t left_to_read = content_len - conn->consumed_content;
  5461. if (left_to_read < len64) {
  5462. /* Do not read more than the total content length of the
  5463. * request.
  5464. */
  5465. len64 = left_to_read;
  5466. }
  5467. /* Return buffered data */
  5468. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5469. - conn->consumed_content;
  5470. if (buffered_len > 0) {
  5471. if (len64 < buffered_len) {
  5472. buffered_len = len64;
  5473. }
  5474. body = conn->buf + conn->request_len + conn->consumed_content;
  5475. memcpy(buf, body, (size_t)buffered_len);
  5476. len64 -= buffered_len;
  5477. conn->consumed_content += buffered_len;
  5478. nread += buffered_len;
  5479. buf = (char *)buf + buffered_len;
  5480. }
  5481. /* We have returned all buffered data. Read new data from the remote
  5482. * socket.
  5483. */
  5484. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5485. conn->consumed_content += n;
  5486. nread += n;
  5487. } else {
  5488. nread = ((nread > 0) ? nread : n);
  5489. }
  5490. }
  5491. return (int)nread;
  5492. }
  5493. /* Forward declarations */
  5494. static void handle_request(struct mg_connection *);
  5495. static void log_access(const struct mg_connection *);
  5496. /* Handle request, update statistics and call access log */
  5497. static void
  5498. handle_request_stat_log(struct mg_connection *conn)
  5499. {
  5500. #if defined(USE_SERVER_STATS)
  5501. struct timespec tnow;
  5502. conn->conn_state = 4; /* processing */
  5503. #endif
  5504. handle_request(conn);
  5505. #if defined(USE_SERVER_STATS)
  5506. conn->conn_state = 5; /* processed */
  5507. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5508. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5509. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5510. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5511. conn->num_bytes_sent);
  5512. #endif
  5513. DEBUG_TRACE("%s", "handle_request done");
  5514. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5515. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5516. DEBUG_TRACE("%s", "end_request callback done");
  5517. }
  5518. log_access(conn);
  5519. }
  5520. #if defined(USE_HTTP2)
  5521. #if defined(NO_SSL)
  5522. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5523. #endif
  5524. #define USE_ALPN
  5525. #include "mod_http2.inl"
  5526. /* Not supported with HTTP/2 */
  5527. #define HTTP1_only \
  5528. { \
  5529. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5530. http2_must_use_http1(conn); \
  5531. return; \
  5532. } \
  5533. }
  5534. #else
  5535. #define HTTP1_only
  5536. #endif
  5537. int
  5538. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5539. {
  5540. if (len > INT_MAX) {
  5541. len = INT_MAX;
  5542. }
  5543. if (conn == NULL) {
  5544. return 0;
  5545. }
  5546. if (conn->is_chunked) {
  5547. size_t all_read = 0;
  5548. while (len > 0) {
  5549. if (conn->is_chunked >= 3) {
  5550. /* No more data left to read */
  5551. return 0;
  5552. }
  5553. if (conn->is_chunked != 1) {
  5554. /* Has error */
  5555. return -1;
  5556. }
  5557. if (conn->consumed_content != conn->content_len) {
  5558. /* copy from the current chunk */
  5559. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5560. if (read_ret < 1) {
  5561. /* read error */
  5562. conn->is_chunked = 2;
  5563. return -1;
  5564. }
  5565. all_read += (size_t)read_ret;
  5566. len -= (size_t)read_ret;
  5567. if (conn->consumed_content == conn->content_len) {
  5568. /* Add data bytes in the current chunk have been read,
  5569. * so we are expecting \r\n now. */
  5570. char x[2];
  5571. conn->content_len += 2;
  5572. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5573. || (x[1] != '\n')) {
  5574. /* Protocol violation */
  5575. conn->is_chunked = 2;
  5576. return -1;
  5577. }
  5578. }
  5579. } else {
  5580. /* fetch a new chunk */
  5581. size_t i;
  5582. char lenbuf[64];
  5583. char *end = NULL;
  5584. unsigned long chunkSize = 0;
  5585. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5586. conn->content_len++;
  5587. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5588. lenbuf[i] = 0;
  5589. }
  5590. if ((i > 0) && (lenbuf[i] == '\r')
  5591. && (lenbuf[i - 1] != '\r')) {
  5592. continue;
  5593. }
  5594. if ((i > 1) && (lenbuf[i] == '\n')
  5595. && (lenbuf[i - 1] == '\r')) {
  5596. lenbuf[i + 1] = 0;
  5597. chunkSize = strtoul(lenbuf, &end, 16);
  5598. if (chunkSize == 0) {
  5599. /* regular end of content */
  5600. conn->is_chunked = 3;
  5601. }
  5602. break;
  5603. }
  5604. if (!isxdigit((unsigned char)lenbuf[i])) {
  5605. /* illegal character for chunk length */
  5606. conn->is_chunked = 2;
  5607. return -1;
  5608. }
  5609. }
  5610. if ((end == NULL) || (*end != '\r')) {
  5611. /* chunksize not set correctly */
  5612. conn->is_chunked = 2;
  5613. return -1;
  5614. }
  5615. if (chunkSize == 0) {
  5616. /* try discarding trailer for keep-alive */
  5617. conn->content_len += 2;
  5618. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5619. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5620. conn->is_chunked = 4;
  5621. }
  5622. break;
  5623. }
  5624. /* append a new chunk */
  5625. conn->content_len += (int64_t)chunkSize;
  5626. }
  5627. }
  5628. return (int)all_read;
  5629. }
  5630. return mg_read_inner(conn, buf, len);
  5631. }
  5632. int
  5633. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5634. {
  5635. time_t now;
  5636. int n, total, allowed;
  5637. if (conn == NULL) {
  5638. return 0;
  5639. }
  5640. if (len > INT_MAX) {
  5641. return -1;
  5642. }
  5643. /* Mark connection as "data sent" */
  5644. conn->request_state = 10;
  5645. #if defined(USE_HTTP2)
  5646. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5647. http2_data_frame_head(conn, len, 0);
  5648. }
  5649. #endif
  5650. if (conn->throttle > 0) {
  5651. if ((now = time(NULL)) != conn->last_throttle_time) {
  5652. conn->last_throttle_time = now;
  5653. conn->last_throttle_bytes = 0;
  5654. }
  5655. allowed = conn->throttle - conn->last_throttle_bytes;
  5656. if (allowed > (int)len) {
  5657. allowed = (int)len;
  5658. }
  5659. total = push_all(conn->phys_ctx,
  5660. NULL,
  5661. conn->client.sock,
  5662. conn->ssl,
  5663. (const char *)buf,
  5664. allowed);
  5665. if (total == allowed) {
  5666. buf = (const char *)buf + total;
  5667. conn->last_throttle_bytes += total;
  5668. while ((total < (int)len)
  5669. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5670. allowed = (conn->throttle > ((int)len - total))
  5671. ? (int)len - total
  5672. : conn->throttle;
  5673. n = push_all(conn->phys_ctx,
  5674. NULL,
  5675. conn->client.sock,
  5676. conn->ssl,
  5677. (const char *)buf,
  5678. allowed);
  5679. if (n != allowed) {
  5680. break;
  5681. }
  5682. sleep(1);
  5683. conn->last_throttle_bytes = allowed;
  5684. conn->last_throttle_time = time(NULL);
  5685. buf = (const char *)buf + n;
  5686. total += n;
  5687. }
  5688. }
  5689. } else {
  5690. total = push_all(conn->phys_ctx,
  5691. NULL,
  5692. conn->client.sock,
  5693. conn->ssl,
  5694. (const char *)buf,
  5695. (int)len);
  5696. }
  5697. if (total > 0) {
  5698. conn->num_bytes_sent += total;
  5699. }
  5700. return total;
  5701. }
  5702. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5703. int
  5704. mg_send_chunk(struct mg_connection *conn,
  5705. const char *chunk,
  5706. unsigned int chunk_len)
  5707. {
  5708. char lenbuf[16];
  5709. size_t lenbuf_len;
  5710. int ret;
  5711. int t;
  5712. /* First store the length information in a text buffer. */
  5713. sprintf(lenbuf, "%x\r\n", chunk_len);
  5714. lenbuf_len = strlen(lenbuf);
  5715. /* Then send length information, chunk and terminating \r\n. */
  5716. ret = mg_write(conn, lenbuf, lenbuf_len);
  5717. if (ret != (int)lenbuf_len) {
  5718. return -1;
  5719. }
  5720. t = ret;
  5721. ret = mg_write(conn, chunk, chunk_len);
  5722. if (ret != (int)chunk_len) {
  5723. return -1;
  5724. }
  5725. t += ret;
  5726. ret = mg_write(conn, "\r\n", 2);
  5727. if (ret != 2) {
  5728. return -1;
  5729. }
  5730. t += ret;
  5731. return t;
  5732. }
  5733. #if defined(GCC_DIAGNOSTIC)
  5734. /* This block forwards format strings to printf implementations,
  5735. * so we need to disable the format-nonliteral warning. */
  5736. #pragma GCC diagnostic push
  5737. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5738. #endif
  5739. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5740. static int
  5741. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5742. {
  5743. va_list ap_copy;
  5744. size_t size = MG_BUF_LEN / 4;
  5745. int len = -1;
  5746. *buf = NULL;
  5747. while (len < 0) {
  5748. if (*buf) {
  5749. mg_free(*buf);
  5750. }
  5751. size *= 4;
  5752. *buf = (char *)mg_malloc(size);
  5753. if (!*buf) {
  5754. break;
  5755. }
  5756. va_copy(ap_copy, ap);
  5757. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5758. va_end(ap_copy);
  5759. (*buf)[size - 1] = 0;
  5760. }
  5761. return len;
  5762. }
  5763. /* Print message to buffer. If buffer is large enough to hold the message,
  5764. * return buffer. If buffer is to small, allocate large enough buffer on
  5765. * heap,
  5766. * and return allocated buffer. */
  5767. static int
  5768. alloc_vprintf(char **out_buf,
  5769. char *prealloc_buf,
  5770. size_t prealloc_size,
  5771. const char *fmt,
  5772. va_list ap)
  5773. {
  5774. va_list ap_copy;
  5775. int len;
  5776. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5777. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5778. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5779. * Therefore, we make two passes: on first pass, get required message
  5780. * length.
  5781. * On second pass, actually print the message. */
  5782. va_copy(ap_copy, ap);
  5783. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5784. va_end(ap_copy);
  5785. if (len < 0) {
  5786. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5787. * Switch to alternative code path that uses incremental
  5788. * allocations.
  5789. */
  5790. va_copy(ap_copy, ap);
  5791. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5792. va_end(ap_copy);
  5793. } else if ((size_t)(len) >= prealloc_size) {
  5794. /* The pre-allocated buffer not large enough. */
  5795. /* Allocate a new buffer. */
  5796. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5797. if (!*out_buf) {
  5798. /* Allocation failed. Return -1 as "out of memory" error. */
  5799. return -1;
  5800. }
  5801. /* Buffer allocation successful. Store the string there. */
  5802. va_copy(ap_copy, ap);
  5803. IGNORE_UNUSED_RESULT(
  5804. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5805. va_end(ap_copy);
  5806. } else {
  5807. /* The pre-allocated buffer is large enough.
  5808. * Use it to store the string and return the address. */
  5809. va_copy(ap_copy, ap);
  5810. IGNORE_UNUSED_RESULT(
  5811. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5812. va_end(ap_copy);
  5813. *out_buf = prealloc_buf;
  5814. }
  5815. return len;
  5816. }
  5817. #if defined(GCC_DIAGNOSTIC)
  5818. /* Enable format-nonliteral warning again. */
  5819. #pragma GCC diagnostic pop
  5820. #endif
  5821. static int
  5822. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5823. {
  5824. char mem[MG_BUF_LEN];
  5825. char *buf = NULL;
  5826. int len;
  5827. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5828. len = mg_write(conn, buf, (size_t)len);
  5829. }
  5830. if (buf != mem) {
  5831. mg_free(buf);
  5832. }
  5833. return len;
  5834. }
  5835. int
  5836. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5837. {
  5838. va_list ap;
  5839. int result;
  5840. va_start(ap, fmt);
  5841. result = mg_vprintf(conn, fmt, ap);
  5842. va_end(ap);
  5843. return result;
  5844. }
  5845. int
  5846. mg_url_decode(const char *src,
  5847. int src_len,
  5848. char *dst,
  5849. int dst_len,
  5850. int is_form_url_encoded)
  5851. {
  5852. int i, j, a, b;
  5853. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5854. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5855. if ((i < src_len - 2) && (src[i] == '%')
  5856. && isxdigit((unsigned char)src[i + 1])
  5857. && isxdigit((unsigned char)src[i + 2])) {
  5858. a = tolower((unsigned char)src[i + 1]);
  5859. b = tolower((unsigned char)src[i + 2]);
  5860. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5861. i += 2;
  5862. } else if (is_form_url_encoded && (src[i] == '+')) {
  5863. dst[j] = ' ';
  5864. } else {
  5865. dst[j] = src[i];
  5866. }
  5867. }
  5868. dst[j] = '\0'; /* Null-terminate the destination */
  5869. return (i >= src_len) ? j : -1;
  5870. }
  5871. /* form url decoding of an entire string */
  5872. static void
  5873. url_decode_in_place(char *buf)
  5874. {
  5875. int len = (int)strlen(buf);
  5876. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5877. }
  5878. int
  5879. mg_get_var(const char *data,
  5880. size_t data_len,
  5881. const char *name,
  5882. char *dst,
  5883. size_t dst_len)
  5884. {
  5885. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5886. }
  5887. int
  5888. mg_get_var2(const char *data,
  5889. size_t data_len,
  5890. const char *name,
  5891. char *dst,
  5892. size_t dst_len,
  5893. size_t occurrence)
  5894. {
  5895. const char *p, *e, *s;
  5896. size_t name_len;
  5897. int len;
  5898. if ((dst == NULL) || (dst_len == 0)) {
  5899. len = -2;
  5900. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5901. len = -1;
  5902. dst[0] = '\0';
  5903. } else {
  5904. name_len = strlen(name);
  5905. e = data + data_len;
  5906. len = -1;
  5907. dst[0] = '\0';
  5908. /* data is "var1=val1&var2=val2...". Find variable first */
  5909. for (p = data; p + name_len < e; p++) {
  5910. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5911. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5912. /* Point p to variable value */
  5913. p += name_len + 1;
  5914. /* Point s to the end of the value */
  5915. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5916. if (s == NULL) {
  5917. s = e;
  5918. }
  5919. DEBUG_ASSERT(s >= p);
  5920. if (s < p) {
  5921. return -3;
  5922. }
  5923. /* Decode variable into destination buffer */
  5924. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5925. /* Redirect error code from -1 to -2 (destination buffer too
  5926. * small). */
  5927. if (len == -1) {
  5928. len = -2;
  5929. }
  5930. break;
  5931. }
  5932. }
  5933. }
  5934. return len;
  5935. }
  5936. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5937. int
  5938. mg_split_form_urlencoded(char *data,
  5939. struct mg_header *form_fields,
  5940. unsigned num_form_fields)
  5941. {
  5942. char *b;
  5943. int i;
  5944. int num = 0;
  5945. if (data == NULL) {
  5946. /* parameter error */
  5947. return -1;
  5948. }
  5949. if ((form_fields == NULL) && (num_form_fields == 0)) {
  5950. /* determine the number of expected fields */
  5951. if (data[0] == 0) {
  5952. return 0;
  5953. }
  5954. /* count number of & to return the number of key-value-pairs */
  5955. num = 1;
  5956. while (*data) {
  5957. if (*data == '&') {
  5958. num++;
  5959. }
  5960. data++;
  5961. }
  5962. return num;
  5963. }
  5964. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  5965. /* parameter error */
  5966. return -1;
  5967. }
  5968. for (i = 0; i < (int)num_form_fields; i++) {
  5969. /* extract key-value pairs from input data */
  5970. while ((*data == ' ') || (*data == '\t')) {
  5971. /* skip initial spaces */
  5972. data++;
  5973. }
  5974. if (*data == 0) {
  5975. /* end of string reached */
  5976. break;
  5977. }
  5978. form_fields[num].name = data;
  5979. /* find & or = */
  5980. b = data;
  5981. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  5982. b++;
  5983. }
  5984. if (*b == 0) {
  5985. /* last key without value */
  5986. form_fields[num].value = NULL;
  5987. } else if (*b == '&') {
  5988. /* mid key without value */
  5989. form_fields[num].value = NULL;
  5990. } else {
  5991. /* terminate string */
  5992. *b = 0;
  5993. /* value starts after '=' */
  5994. data = b + 1;
  5995. form_fields[num].value = data;
  5996. }
  5997. /* new field is stored */
  5998. num++;
  5999. /* find a next key */
  6000. b = strchr(data, '&');
  6001. if (b == 0) {
  6002. /* no more data */
  6003. break;
  6004. } else {
  6005. /* terminate value of last field at '&' */
  6006. *b = 0;
  6007. /* next key-value-pairs starts after '&' */
  6008. data = b + 1;
  6009. }
  6010. }
  6011. /* Decode all values */
  6012. for (i = 0; i < num; i++) {
  6013. if (form_fields[i].name) {
  6014. url_decode_in_place((char *)form_fields[i].name);
  6015. }
  6016. if (form_fields[i].value) {
  6017. url_decode_in_place((char *)form_fields[i].value);
  6018. }
  6019. }
  6020. /* return number of fields found */
  6021. return num;
  6022. }
  6023. /* HCP24: some changes to compare hole var_name */
  6024. int
  6025. mg_get_cookie(const char *cookie_header,
  6026. const char *var_name,
  6027. char *dst,
  6028. size_t dst_size)
  6029. {
  6030. const char *s, *p, *end;
  6031. int name_len, len = -1;
  6032. if ((dst == NULL) || (dst_size == 0)) {
  6033. return -2;
  6034. }
  6035. dst[0] = '\0';
  6036. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6037. return -1;
  6038. }
  6039. name_len = (int)strlen(var_name);
  6040. end = s + strlen(s);
  6041. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6042. if (s[name_len] == '=') {
  6043. /* HCP24: now check is it a substring or a full cookie name */
  6044. if ((s == cookie_header) || (s[-1] == ' ')) {
  6045. s += name_len + 1;
  6046. if ((p = strchr(s, ' ')) == NULL) {
  6047. p = end;
  6048. }
  6049. if (p[-1] == ';') {
  6050. p--;
  6051. }
  6052. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6053. s++;
  6054. p--;
  6055. }
  6056. if ((size_t)(p - s) < dst_size) {
  6057. len = (int)(p - s);
  6058. mg_strlcpy(dst, s, (size_t)len + 1);
  6059. } else {
  6060. len = -3;
  6061. }
  6062. break;
  6063. }
  6064. }
  6065. }
  6066. return len;
  6067. }
  6068. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6069. static void
  6070. base64_encode(const unsigned char *src, int src_len, char *dst)
  6071. {
  6072. static const char *b64 =
  6073. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6074. int i, j, a, b, c;
  6075. for (i = j = 0; i < src_len; i += 3) {
  6076. a = src[i];
  6077. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6078. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6079. dst[j++] = b64[a >> 2];
  6080. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6081. if (i + 1 < src_len) {
  6082. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6083. }
  6084. if (i + 2 < src_len) {
  6085. dst[j++] = b64[c & 63];
  6086. }
  6087. }
  6088. while (j % 4 != 0) {
  6089. dst[j++] = '=';
  6090. }
  6091. dst[j++] = '\0';
  6092. }
  6093. #endif
  6094. #if defined(USE_LUA)
  6095. static unsigned char
  6096. b64reverse(char letter)
  6097. {
  6098. if ((letter >= 'A') && (letter <= 'Z')) {
  6099. return letter - 'A';
  6100. }
  6101. if ((letter >= 'a') && (letter <= 'z')) {
  6102. return letter - 'a' + 26;
  6103. }
  6104. if ((letter >= '0') && (letter <= '9')) {
  6105. return letter - '0' + 52;
  6106. }
  6107. if (letter == '+') {
  6108. return 62;
  6109. }
  6110. if (letter == '/') {
  6111. return 63;
  6112. }
  6113. if (letter == '=') {
  6114. return 255; /* normal end */
  6115. }
  6116. return 254; /* error */
  6117. }
  6118. static int
  6119. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6120. {
  6121. int i;
  6122. unsigned char a, b, c, d;
  6123. *dst_len = 0;
  6124. for (i = 0; i < src_len; i += 4) {
  6125. a = b64reverse(src[i]);
  6126. if (a >= 254) {
  6127. return i;
  6128. }
  6129. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6130. if (b >= 254) {
  6131. return i + 1;
  6132. }
  6133. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6134. if (c == 254) {
  6135. return i + 2;
  6136. }
  6137. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6138. if (d == 254) {
  6139. return i + 3;
  6140. }
  6141. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6142. if (c != 255) {
  6143. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6144. if (d != 255) {
  6145. dst[(*dst_len)++] = (c << 6) + d;
  6146. }
  6147. }
  6148. }
  6149. return -1;
  6150. }
  6151. #endif
  6152. static int
  6153. is_put_or_delete_method(const struct mg_connection *conn)
  6154. {
  6155. if (conn) {
  6156. const char *s = conn->request_info.request_method;
  6157. return (s != NULL)
  6158. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6159. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6160. }
  6161. return 0;
  6162. }
  6163. #if !defined(NO_FILES)
  6164. static int
  6165. extention_matches_script(
  6166. struct mg_connection *conn, /* in: request (must be valid) */
  6167. const char *filename /* in: filename (must be valid) */
  6168. )
  6169. {
  6170. #if !defined(NO_CGI)
  6171. unsigned char cgi_config_idx, inc, max;
  6172. #endif
  6173. #if defined(USE_LUA)
  6174. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6175. filename)
  6176. > 0) {
  6177. return 1;
  6178. }
  6179. #endif
  6180. #if defined(USE_DUKTAPE)
  6181. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6182. filename)
  6183. > 0) {
  6184. return 1;
  6185. }
  6186. #endif
  6187. #if !defined(NO_CGI)
  6188. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6189. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6190. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6191. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6192. && (match_prefix_strlen(
  6193. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6194. filename)
  6195. > 0)) {
  6196. return 1;
  6197. }
  6198. }
  6199. #endif
  6200. /* filename and conn could be unused, if all preocessor conditions
  6201. * are false (no script language supported). */
  6202. (void)filename;
  6203. (void)conn;
  6204. return 0;
  6205. }
  6206. static int
  6207. extention_matches_template_text(
  6208. struct mg_connection *conn, /* in: request (must be valid) */
  6209. const char *filename /* in: filename (must be valid) */
  6210. )
  6211. {
  6212. #if defined(USE_LUA)
  6213. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6214. filename)
  6215. > 0) {
  6216. return 1;
  6217. }
  6218. #endif
  6219. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6220. > 0) {
  6221. return 1;
  6222. }
  6223. return 0;
  6224. }
  6225. /* For given directory path, substitute it to valid index file.
  6226. * Return 1 if index file has been found, 0 if not found.
  6227. * If the file is found, it's stats is returned in stp. */
  6228. static int
  6229. substitute_index_file(struct mg_connection *conn,
  6230. char *path,
  6231. size_t path_len,
  6232. struct mg_file_stat *filestat)
  6233. {
  6234. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6235. struct vec filename_vec;
  6236. size_t n = strlen(path);
  6237. int found = 0;
  6238. /* The 'path' given to us points to the directory. Remove all trailing
  6239. * directory separator characters from the end of the path, and
  6240. * then append single directory separator character. */
  6241. while ((n > 0) && (path[n - 1] == '/')) {
  6242. n--;
  6243. }
  6244. path[n] = '/';
  6245. /* Traverse index files list. For each entry, append it to the given
  6246. * path and see if the file exists. If it exists, break the loop */
  6247. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6248. /* Ignore too long entries that may overflow path buffer */
  6249. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6250. continue;
  6251. }
  6252. /* Prepare full path to the index file */
  6253. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6254. /* Does it exist? */
  6255. if (mg_stat(conn, path, filestat)) {
  6256. /* Yes it does, break the loop */
  6257. found = 1;
  6258. break;
  6259. }
  6260. }
  6261. /* If no index file exists, restore directory path */
  6262. if (!found) {
  6263. path[n] = '\0';
  6264. }
  6265. return found;
  6266. }
  6267. #endif
  6268. static void
  6269. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6270. char *filename, /* out: filename */
  6271. size_t filename_buf_len, /* in: size of filename buffer */
  6272. struct mg_file_stat *filestat, /* out: file status structure */
  6273. int *is_found, /* out: file found (directly) */
  6274. int *is_script_resource, /* out: handled by a script? */
  6275. int *is_websocket_request, /* out: websocket connetion? */
  6276. int *is_put_or_delete_request, /* out: put/delete a file? */
  6277. int *is_template_text /* out: SSI file or LSP file? */
  6278. )
  6279. {
  6280. char const *accept_encoding;
  6281. #if !defined(NO_FILES)
  6282. const char *uri = conn->request_info.local_uri;
  6283. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6284. const char *rewrite;
  6285. struct vec a, b;
  6286. ptrdiff_t match_len;
  6287. char gz_path[UTF8_PATH_MAX];
  6288. int truncated;
  6289. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6290. char *tmp_str;
  6291. size_t tmp_str_len, sep_pos;
  6292. int allow_substitute_script_subresources;
  6293. #endif
  6294. #else
  6295. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6296. #endif
  6297. /* Step 1: Set all initially unknown outputs to zero */
  6298. memset(filestat, 0, sizeof(*filestat));
  6299. *filename = 0;
  6300. *is_found = 0;
  6301. *is_script_resource = 0;
  6302. *is_template_text = 0;
  6303. /* Step 2: Check if the request attempts to modify the file system */
  6304. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6305. /* Step 3: Check if it is a websocket request, and modify the document
  6306. * root if required */
  6307. #if defined(USE_WEBSOCKET)
  6308. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6309. #if !defined(NO_FILES)
  6310. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6311. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6312. }
  6313. #endif /* !NO_FILES */
  6314. #else /* USE_WEBSOCKET */
  6315. *is_websocket_request = 0;
  6316. #endif /* USE_WEBSOCKET */
  6317. /* Step 4: Check if gzip encoded response is allowed */
  6318. conn->accept_gzip = 0;
  6319. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6320. if (strstr(accept_encoding, "gzip") != NULL) {
  6321. conn->accept_gzip = 1;
  6322. }
  6323. }
  6324. #if !defined(NO_FILES)
  6325. /* Step 5: If there is no root directory, don't look for files. */
  6326. /* Note that root == NULL is a regular use case here. This occurs,
  6327. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6328. * config is not required. */
  6329. if (root == NULL) {
  6330. /* all file related outputs have already been set to 0, just return
  6331. */
  6332. return;
  6333. }
  6334. /* Step 6: Determine the local file path from the root path and the
  6335. * request uri. */
  6336. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6337. * part of the path one byte on the right. */
  6338. truncated = 0;
  6339. mg_snprintf(
  6340. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6341. if (truncated) {
  6342. goto interpret_cleanup;
  6343. }
  6344. /* Step 7: URI rewriting */
  6345. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6346. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6347. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6348. mg_snprintf(conn,
  6349. &truncated,
  6350. filename,
  6351. filename_buf_len - 1,
  6352. "%.*s%s",
  6353. (int)b.len,
  6354. b.ptr,
  6355. uri + match_len);
  6356. break;
  6357. }
  6358. }
  6359. if (truncated) {
  6360. goto interpret_cleanup;
  6361. }
  6362. /* Step 8: Check if the file exists at the server */
  6363. /* Local file path and name, corresponding to requested URI
  6364. * is now stored in "filename" variable. */
  6365. if (mg_stat(conn, filename, filestat)) {
  6366. int uri_len = (int)strlen(uri);
  6367. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6368. /* 8.1: File exists. */
  6369. *is_found = 1;
  6370. /* 8.2: Check if it is a script type. */
  6371. if (extention_matches_script(conn, filename)) {
  6372. /* The request addresses a CGI resource, Lua script or
  6373. * server-side javascript.
  6374. * The URI corresponds to the script itself (like
  6375. * /path/script.cgi), and there is no additional resource
  6376. * path (like /path/script.cgi/something).
  6377. * Requests that modify (replace or delete) a resource, like
  6378. * PUT and DELETE requests, should replace/delete the script
  6379. * file.
  6380. * Requests that read or write from/to a resource, like GET and
  6381. * POST requests, should call the script and return the
  6382. * generated response. */
  6383. *is_script_resource = (!*is_put_or_delete_request);
  6384. }
  6385. /* 8.3: Check for SSI and LSP files */
  6386. if (extention_matches_template_text(conn, filename)) {
  6387. /* Same as above, but for *.lsp and *.shtml files. */
  6388. /* A "template text" is a file delivered directly to the client,
  6389. * but with some text tags replaced by dynamic content.
  6390. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6391. * (LP, LSP) file. */
  6392. *is_template_text = (!*is_put_or_delete_request);
  6393. }
  6394. /* 8.4: If the request target is a directory, there could be
  6395. * a substitute file (index.html, index.cgi, ...). */
  6396. if (filestat->is_directory && is_uri_end_slash) {
  6397. /* Use a local copy here, since substitute_index_file will
  6398. * change the content of the file status */
  6399. struct mg_file_stat tmp_filestat;
  6400. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6401. if (substitute_index_file(
  6402. conn, filename, filename_buf_len, &tmp_filestat)) {
  6403. /* Substitute file found. Copy stat to the output, then
  6404. * check if the file is a script file */
  6405. *filestat = tmp_filestat;
  6406. if (extention_matches_script(conn, filename)) {
  6407. /* Substitute file is a script file */
  6408. *is_script_resource = 1;
  6409. } else if (extention_matches_template_text(conn, filename)) {
  6410. /* Substitute file is a LSP or SSI file */
  6411. *is_template_text = 1;
  6412. } else {
  6413. /* Substitute file is a regular file */
  6414. *is_script_resource = 0;
  6415. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6416. }
  6417. }
  6418. /* If there is no substitute file, the server could return
  6419. * a directory listing in a later step */
  6420. }
  6421. return;
  6422. }
  6423. /* Step 9: Check for zipped files: */
  6424. /* If we can't find the actual file, look for the file
  6425. * with the same name but a .gz extension. If we find it,
  6426. * use that and set the gzipped flag in the file struct
  6427. * to indicate that the response need to have the content-
  6428. * encoding: gzip header.
  6429. * We can only do this if the browser declares support. */
  6430. if (conn->accept_gzip) {
  6431. mg_snprintf(
  6432. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6433. if (truncated) {
  6434. goto interpret_cleanup;
  6435. }
  6436. if (mg_stat(conn, gz_path, filestat)) {
  6437. if (filestat) {
  6438. filestat->is_gzipped = 1;
  6439. *is_found = 1;
  6440. }
  6441. /* Currently gz files can not be scripts. */
  6442. return;
  6443. }
  6444. }
  6445. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6446. /* Step 10: Script resources may handle sub-resources */
  6447. /* Support PATH_INFO for CGI scripts. */
  6448. tmp_str_len = strlen(filename);
  6449. tmp_str =
  6450. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6451. if (!tmp_str) {
  6452. /* Out of memory */
  6453. goto interpret_cleanup;
  6454. }
  6455. memcpy(tmp_str, filename, tmp_str_len + 1);
  6456. /* Check config, if index scripts may have sub-resources */
  6457. allow_substitute_script_subresources =
  6458. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6459. "yes");
  6460. sep_pos = tmp_str_len;
  6461. while (sep_pos > 0) {
  6462. sep_pos--;
  6463. if (tmp_str[sep_pos] == '/') {
  6464. int is_script = 0, does_exist = 0;
  6465. tmp_str[sep_pos] = 0;
  6466. if (tmp_str[0]) {
  6467. is_script = extention_matches_script(conn, tmp_str);
  6468. does_exist = mg_stat(conn, tmp_str, filestat);
  6469. }
  6470. if (does_exist && is_script) {
  6471. filename[sep_pos] = 0;
  6472. memmove(filename + sep_pos + 2,
  6473. filename + sep_pos + 1,
  6474. strlen(filename + sep_pos + 1) + 1);
  6475. conn->path_info = filename + sep_pos + 1;
  6476. filename[sep_pos + 1] = '/';
  6477. *is_script_resource = 1;
  6478. *is_found = 1;
  6479. break;
  6480. }
  6481. if (allow_substitute_script_subresources) {
  6482. if (substitute_index_file(
  6483. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6484. /* some intermediate directory has an index file */
  6485. if (extention_matches_script(conn, tmp_str)) {
  6486. size_t script_name_len = strlen(tmp_str);
  6487. /* subres_name read before this memory locatio will be
  6488. overwritten */
  6489. char *subres_name = filename + sep_pos;
  6490. size_t subres_name_len = strlen(subres_name);
  6491. DEBUG_TRACE("Substitute script %s serving path %s",
  6492. tmp_str,
  6493. filename);
  6494. /* this index file is a script */
  6495. if ((script_name_len + subres_name_len + 2)
  6496. >= filename_buf_len) {
  6497. mg_free(tmp_str);
  6498. goto interpret_cleanup;
  6499. }
  6500. conn->path_info =
  6501. filename + script_name_len + 1; /* new target */
  6502. memmove(conn->path_info, subres_name, subres_name_len);
  6503. conn->path_info[subres_name_len] = 0;
  6504. memcpy(filename, tmp_str, script_name_len + 1);
  6505. *is_script_resource = 1;
  6506. *is_found = 1;
  6507. break;
  6508. } else {
  6509. DEBUG_TRACE("Substitute file %s serving path %s",
  6510. tmp_str,
  6511. filename);
  6512. /* non-script files will not have sub-resources */
  6513. filename[sep_pos] = 0;
  6514. conn->path_info = 0;
  6515. *is_script_resource = 0;
  6516. *is_found = 0;
  6517. break;
  6518. }
  6519. }
  6520. }
  6521. tmp_str[sep_pos] = '/';
  6522. }
  6523. }
  6524. mg_free(tmp_str);
  6525. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6526. #endif /* !defined(NO_FILES) */
  6527. return;
  6528. #if !defined(NO_FILES)
  6529. /* Reset all outputs */
  6530. interpret_cleanup:
  6531. memset(filestat, 0, sizeof(*filestat));
  6532. *filename = 0;
  6533. *is_found = 0;
  6534. *is_script_resource = 0;
  6535. *is_websocket_request = 0;
  6536. *is_put_or_delete_request = 0;
  6537. #endif /* !defined(NO_FILES) */
  6538. }
  6539. /* Check whether full request is buffered. Return:
  6540. * -1 if request or response is malformed
  6541. * 0 if request or response is not yet fully buffered
  6542. * >0 actual request length, including last \r\n\r\n */
  6543. static int
  6544. get_http_header_len(const char *buf, int buflen)
  6545. {
  6546. int i;
  6547. for (i = 0; i < buflen; i++) {
  6548. /* Do an unsigned comparison in some conditions below */
  6549. const unsigned char c = (unsigned char)buf[i];
  6550. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6551. && !isprint(c)) {
  6552. /* abort scan as soon as one malformed character is found */
  6553. return -1;
  6554. }
  6555. if (i < buflen - 1) {
  6556. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6557. /* Two newline, no carriage return - not standard compliant,
  6558. * but it should be accepted */
  6559. return i + 2;
  6560. }
  6561. }
  6562. if (i < buflen - 3) {
  6563. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6564. && (buf[i + 3] == '\n')) {
  6565. /* Two \r\n - standard compliant */
  6566. return i + 4;
  6567. }
  6568. }
  6569. }
  6570. return 0;
  6571. }
  6572. #if !defined(NO_CACHING)
  6573. /* Convert month to the month number. Return -1 on error, or month number */
  6574. static int
  6575. get_month_index(const char *s)
  6576. {
  6577. size_t i;
  6578. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6579. if (!strcmp(s, month_names[i])) {
  6580. return (int)i;
  6581. }
  6582. }
  6583. return -1;
  6584. }
  6585. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6586. static time_t
  6587. parse_date_string(const char *datetime)
  6588. {
  6589. char month_str[32] = {0};
  6590. int second, minute, hour, day, month, year;
  6591. time_t result = (time_t)0;
  6592. struct tm tm;
  6593. if ((sscanf(datetime,
  6594. "%d/%3s/%d %d:%d:%d",
  6595. &day,
  6596. month_str,
  6597. &year,
  6598. &hour,
  6599. &minute,
  6600. &second)
  6601. == 6)
  6602. || (sscanf(datetime,
  6603. "%d %3s %d %d:%d:%d",
  6604. &day,
  6605. month_str,
  6606. &year,
  6607. &hour,
  6608. &minute,
  6609. &second)
  6610. == 6)
  6611. || (sscanf(datetime,
  6612. "%*3s, %d %3s %d %d:%d:%d",
  6613. &day,
  6614. month_str,
  6615. &year,
  6616. &hour,
  6617. &minute,
  6618. &second)
  6619. == 6)
  6620. || (sscanf(datetime,
  6621. "%d-%3s-%d %d:%d:%d",
  6622. &day,
  6623. month_str,
  6624. &year,
  6625. &hour,
  6626. &minute,
  6627. &second)
  6628. == 6)) {
  6629. month = get_month_index(month_str);
  6630. if ((month >= 0) && (year >= 1970)) {
  6631. memset(&tm, 0, sizeof(tm));
  6632. tm.tm_year = year - 1900;
  6633. tm.tm_mon = month;
  6634. tm.tm_mday = day;
  6635. tm.tm_hour = hour;
  6636. tm.tm_min = minute;
  6637. tm.tm_sec = second;
  6638. result = timegm(&tm);
  6639. }
  6640. }
  6641. return result;
  6642. }
  6643. #endif /* !NO_CACHING */
  6644. /* Pre-process URIs according to RFC + protect against directory disclosure
  6645. * attacks by removing '..', excessive '/' and '\' characters */
  6646. static void
  6647. remove_dot_segments(char *inout)
  6648. {
  6649. /* Windows backend protection
  6650. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6651. * in URI by slash */
  6652. char *out_end = inout;
  6653. char *in = inout;
  6654. if (!in) {
  6655. /* Param error. */
  6656. return;
  6657. }
  6658. while (*in) {
  6659. if (*in == '\\') {
  6660. *in = '/';
  6661. }
  6662. in++;
  6663. }
  6664. /* Algorithm "remove_dot_segments" from
  6665. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6666. /* Step 1:
  6667. * The input buffer is initialized.
  6668. * The output buffer is initialized to the empty string.
  6669. */
  6670. in = inout;
  6671. /* Step 2:
  6672. * While the input buffer is not empty, loop as follows:
  6673. */
  6674. /* Less than out_end of the inout buffer is used as output, so keep
  6675. * condition: out_end <= in */
  6676. while (*in) {
  6677. /* Step 2a:
  6678. * If the input buffer begins with a prefix of "../" or "./",
  6679. * then remove that prefix from the input buffer;
  6680. */
  6681. if (!strncmp(in, "../", 3)) {
  6682. in += 3;
  6683. } else if (!strncmp(in, "./", 2)) {
  6684. in += 2;
  6685. }
  6686. /* otherwise */
  6687. /* Step 2b:
  6688. * if the input buffer begins with a prefix of "/./" or "/.",
  6689. * where "." is a complete path segment, then replace that
  6690. * prefix with "/" in the input buffer;
  6691. */
  6692. else if (!strncmp(in, "/./", 3)) {
  6693. in += 2;
  6694. } else if (!strcmp(in, "/.")) {
  6695. in[1] = 0;
  6696. }
  6697. /* otherwise */
  6698. /* Step 2c:
  6699. * if the input buffer begins with a prefix of "/../" or "/..",
  6700. * where ".." is a complete path segment, then replace that
  6701. * prefix with "/" in the input buffer and remove the last
  6702. * segment and its preceding "/" (if any) from the output
  6703. * buffer;
  6704. */
  6705. else if (!strncmp(in, "/../", 4)) {
  6706. in += 3;
  6707. if (inout != out_end) {
  6708. /* remove last segment */
  6709. do {
  6710. out_end--;
  6711. } while ((inout != out_end) && (*out_end != '/'));
  6712. }
  6713. } else if (!strcmp(in, "/..")) {
  6714. in[1] = 0;
  6715. if (inout != out_end) {
  6716. /* remove last segment */
  6717. do {
  6718. out_end--;
  6719. } while ((inout != out_end) && (*out_end != '/'));
  6720. }
  6721. }
  6722. /* otherwise */
  6723. /* Step 2d:
  6724. * if the input buffer consists only of "." or "..", then remove
  6725. * that from the input buffer;
  6726. */
  6727. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6728. *in = 0;
  6729. }
  6730. /* otherwise */
  6731. /* Step 2e:
  6732. * move the first path segment in the input buffer to the end of
  6733. * the output buffer, including the initial "/" character (if
  6734. * any) and any subsequent characters up to, but not including,
  6735. * the next "/" character or the end of the input buffer.
  6736. */
  6737. else {
  6738. do {
  6739. *out_end = *in;
  6740. out_end++;
  6741. in++;
  6742. } while ((*in != 0) && (*in != '/'));
  6743. }
  6744. }
  6745. /* Step 3:
  6746. * Finally, the output buffer is returned as the result of
  6747. * remove_dot_segments.
  6748. */
  6749. /* Terminate output */
  6750. *out_end = 0;
  6751. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6752. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6753. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6754. * or "//" anymore.
  6755. */
  6756. out_end = in = inout;
  6757. while (*in) {
  6758. if (*in == '.') {
  6759. /* remove . at the end or preceding of / */
  6760. char *in_ahead = in;
  6761. do {
  6762. in_ahead++;
  6763. } while (*in_ahead == '.');
  6764. if (*in_ahead == '/') {
  6765. in = in_ahead;
  6766. if ((out_end != inout) && (out_end[-1] == '/')) {
  6767. /* remove generated // */
  6768. out_end--;
  6769. }
  6770. } else if (*in_ahead == 0) {
  6771. in = in_ahead;
  6772. } else {
  6773. do {
  6774. *out_end++ = '.';
  6775. in++;
  6776. } while (in != in_ahead);
  6777. }
  6778. } else if (*in == '/') {
  6779. /* replace // by / */
  6780. *out_end++ = '/';
  6781. do {
  6782. in++;
  6783. } while (*in == '/');
  6784. } else {
  6785. *out_end++ = *in;
  6786. in++;
  6787. }
  6788. }
  6789. *out_end = 0;
  6790. }
  6791. static const struct {
  6792. const char *extension;
  6793. size_t ext_len;
  6794. const char *mime_type;
  6795. } builtin_mime_types[] = {
  6796. /* IANA registered MIME types
  6797. * (http://www.iana.org/assignments/media-types)
  6798. * application types */
  6799. {".bin", 4, "application/octet-stream"},
  6800. {".deb", 4, "application/octet-stream"},
  6801. {".dmg", 4, "application/octet-stream"},
  6802. {".dll", 4, "application/octet-stream"},
  6803. {".doc", 4, "application/msword"},
  6804. {".eps", 4, "application/postscript"},
  6805. {".exe", 4, "application/octet-stream"},
  6806. {".iso", 4, "application/octet-stream"},
  6807. {".js", 3, "application/javascript"},
  6808. {".json", 5, "application/json"},
  6809. {".msi", 4, "application/octet-stream"},
  6810. {".pdf", 4, "application/pdf"},
  6811. {".ps", 3, "application/postscript"},
  6812. {".rtf", 4, "application/rtf"},
  6813. {".xhtml", 6, "application/xhtml+xml"},
  6814. {".xsl", 4, "application/xml"},
  6815. {".xslt", 5, "application/xml"},
  6816. /* fonts */
  6817. {".ttf", 4, "application/font-sfnt"},
  6818. {".cff", 4, "application/font-sfnt"},
  6819. {".otf", 4, "application/font-sfnt"},
  6820. {".aat", 4, "application/font-sfnt"},
  6821. {".sil", 4, "application/font-sfnt"},
  6822. {".pfr", 4, "application/font-tdpfr"},
  6823. {".woff", 5, "application/font-woff"},
  6824. /* audio */
  6825. {".mp3", 4, "audio/mpeg"},
  6826. {".oga", 4, "audio/ogg"},
  6827. {".ogg", 4, "audio/ogg"},
  6828. /* image */
  6829. {".gif", 4, "image/gif"},
  6830. {".ief", 4, "image/ief"},
  6831. {".jpeg", 5, "image/jpeg"},
  6832. {".jpg", 4, "image/jpeg"},
  6833. {".jpm", 4, "image/jpm"},
  6834. {".jpx", 4, "image/jpx"},
  6835. {".png", 4, "image/png"},
  6836. {".svg", 4, "image/svg+xml"},
  6837. {".tif", 4, "image/tiff"},
  6838. {".tiff", 5, "image/tiff"},
  6839. /* model */
  6840. {".wrl", 4, "model/vrml"},
  6841. /* text */
  6842. {".css", 4, "text/css"},
  6843. {".csv", 4, "text/csv"},
  6844. {".htm", 4, "text/html"},
  6845. {".html", 5, "text/html"},
  6846. {".sgm", 4, "text/sgml"},
  6847. {".shtm", 5, "text/html"},
  6848. {".shtml", 6, "text/html"},
  6849. {".txt", 4, "text/plain"},
  6850. {".xml", 4, "text/xml"},
  6851. /* video */
  6852. {".mov", 4, "video/quicktime"},
  6853. {".mp4", 4, "video/mp4"},
  6854. {".mpeg", 5, "video/mpeg"},
  6855. {".mpg", 4, "video/mpeg"},
  6856. {".ogv", 4, "video/ogg"},
  6857. {".qt", 3, "video/quicktime"},
  6858. /* not registered types
  6859. * (http://reference.sitepoint.com/html/mime-types-full,
  6860. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6861. {".arj", 4, "application/x-arj-compressed"},
  6862. {".gz", 3, "application/x-gunzip"},
  6863. {".rar", 4, "application/x-arj-compressed"},
  6864. {".swf", 4, "application/x-shockwave-flash"},
  6865. {".tar", 4, "application/x-tar"},
  6866. {".tgz", 4, "application/x-tar-gz"},
  6867. {".torrent", 8, "application/x-bittorrent"},
  6868. {".ppt", 4, "application/x-mspowerpoint"},
  6869. {".xls", 4, "application/x-msexcel"},
  6870. {".zip", 4, "application/x-zip-compressed"},
  6871. {".aac",
  6872. 4,
  6873. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6874. {".aif", 4, "audio/x-aif"},
  6875. {".m3u", 4, "audio/x-mpegurl"},
  6876. {".mid", 4, "audio/x-midi"},
  6877. {".ra", 3, "audio/x-pn-realaudio"},
  6878. {".ram", 4, "audio/x-pn-realaudio"},
  6879. {".wav", 4, "audio/x-wav"},
  6880. {".bmp", 4, "image/bmp"},
  6881. {".ico", 4, "image/x-icon"},
  6882. {".pct", 4, "image/x-pct"},
  6883. {".pict", 5, "image/pict"},
  6884. {".rgb", 4, "image/x-rgb"},
  6885. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6886. {".asf", 4, "video/x-ms-asf"},
  6887. {".avi", 4, "video/x-msvideo"},
  6888. {".m4v", 4, "video/x-m4v"},
  6889. {NULL, 0, NULL}};
  6890. const char *
  6891. mg_get_builtin_mime_type(const char *path)
  6892. {
  6893. const char *ext;
  6894. size_t i, path_len;
  6895. path_len = strlen(path);
  6896. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6897. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6898. if ((path_len > builtin_mime_types[i].ext_len)
  6899. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6900. return builtin_mime_types[i].mime_type;
  6901. }
  6902. }
  6903. return "text/plain";
  6904. }
  6905. /* Look at the "path" extension and figure what mime type it has.
  6906. * Store mime type in the vector. */
  6907. static void
  6908. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6909. {
  6910. struct vec ext_vec, mime_vec;
  6911. const char *list, *ext;
  6912. size_t path_len;
  6913. path_len = strlen(path);
  6914. if ((conn == NULL) || (vec == NULL)) {
  6915. if (vec != NULL) {
  6916. memset(vec, '\0', sizeof(struct vec));
  6917. }
  6918. return;
  6919. }
  6920. /* Scan user-defined mime types first, in case user wants to
  6921. * override default mime types. */
  6922. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6923. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6924. /* ext now points to the path suffix */
  6925. ext = path + path_len - ext_vec.len;
  6926. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6927. *vec = mime_vec;
  6928. return;
  6929. }
  6930. }
  6931. vec->ptr = mg_get_builtin_mime_type(path);
  6932. vec->len = strlen(vec->ptr);
  6933. }
  6934. /* Stringify binary data. Output buffer must be twice as big as input,
  6935. * because each byte takes 2 bytes in string representation */
  6936. static void
  6937. bin2str(char *to, const unsigned char *p, size_t len)
  6938. {
  6939. static const char *hex = "0123456789abcdef";
  6940. for (; len--; p++) {
  6941. *to++ = hex[p[0] >> 4];
  6942. *to++ = hex[p[0] & 0x0f];
  6943. }
  6944. *to = '\0';
  6945. }
  6946. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6947. */
  6948. char *
  6949. mg_md5(char buf[33], ...)
  6950. {
  6951. md5_byte_t hash[16];
  6952. const char *p;
  6953. va_list ap;
  6954. md5_state_t ctx;
  6955. md5_init(&ctx);
  6956. va_start(ap, buf);
  6957. while ((p = va_arg(ap, const char *)) != NULL) {
  6958. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6959. }
  6960. va_end(ap);
  6961. md5_finish(&ctx, hash);
  6962. bin2str(buf, hash, sizeof(hash));
  6963. return buf;
  6964. }
  6965. /* Check the user's password, return 1 if OK */
  6966. static int
  6967. check_password(const char *method,
  6968. const char *ha1,
  6969. const char *uri,
  6970. const char *nonce,
  6971. const char *nc,
  6972. const char *cnonce,
  6973. const char *qop,
  6974. const char *response)
  6975. {
  6976. char ha2[32 + 1], expected_response[32 + 1];
  6977. /* Some of the parameters may be NULL */
  6978. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6979. || (qop == NULL) || (response == NULL)) {
  6980. return 0;
  6981. }
  6982. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6983. if (strlen(response) != 32) {
  6984. return 0;
  6985. }
  6986. mg_md5(ha2, method, ":", uri, NULL);
  6987. mg_md5(expected_response,
  6988. ha1,
  6989. ":",
  6990. nonce,
  6991. ":",
  6992. nc,
  6993. ":",
  6994. cnonce,
  6995. ":",
  6996. qop,
  6997. ":",
  6998. ha2,
  6999. NULL);
  7000. return mg_strcasecmp(response, expected_response) == 0;
  7001. }
  7002. #if !defined(NO_FILESYSTEMS)
  7003. /* Use the global passwords file, if specified by auth_gpass option,
  7004. * or search for .htpasswd in the requested directory. */
  7005. static void
  7006. open_auth_file(struct mg_connection *conn,
  7007. const char *path,
  7008. struct mg_file *filep)
  7009. {
  7010. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7011. char name[UTF8_PATH_MAX];
  7012. const char *p, *e,
  7013. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7014. int truncated;
  7015. if (gpass != NULL) {
  7016. /* Use global passwords file */
  7017. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7018. #if defined(DEBUG)
  7019. /* Use mg_cry_internal here, since gpass has been
  7020. * configured. */
  7021. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7022. #endif
  7023. }
  7024. /* Important: using local struct mg_file to test path for
  7025. * is_directory flag. If filep is used, mg_stat() makes it
  7026. * appear as if auth file was opened.
  7027. * TODO(mid): Check if this is still required after rewriting
  7028. * mg_stat */
  7029. } else if (mg_stat(conn, path, &filep->stat)
  7030. && filep->stat.is_directory) {
  7031. mg_snprintf(conn,
  7032. &truncated,
  7033. name,
  7034. sizeof(name),
  7035. "%s/%s",
  7036. path,
  7037. PASSWORDS_FILE_NAME);
  7038. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7039. #if defined(DEBUG)
  7040. /* Don't use mg_cry_internal here, but only a trace, since
  7041. * this is a typical case. It will occur for every directory
  7042. * without a password file. */
  7043. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7044. #endif
  7045. }
  7046. } else {
  7047. /* Try to find .htpasswd in requested directory. */
  7048. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7049. if (e[0] == '/') {
  7050. break;
  7051. }
  7052. }
  7053. mg_snprintf(conn,
  7054. &truncated,
  7055. name,
  7056. sizeof(name),
  7057. "%.*s/%s",
  7058. (int)(e - p),
  7059. p,
  7060. PASSWORDS_FILE_NAME);
  7061. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7062. #if defined(DEBUG)
  7063. /* Don't use mg_cry_internal here, but only a trace, since
  7064. * this is a typical case. It will occur for every directory
  7065. * without a password file. */
  7066. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7067. #endif
  7068. }
  7069. }
  7070. }
  7071. }
  7072. #endif /* NO_FILESYSTEMS */
  7073. /* Parsed Authorization header */
  7074. struct ah {
  7075. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7076. };
  7077. /* Return 1 on success. Always initializes the ah structure. */
  7078. static int
  7079. parse_auth_header(struct mg_connection *conn,
  7080. char *buf,
  7081. size_t buf_size,
  7082. struct ah *ah)
  7083. {
  7084. char *name, *value, *s;
  7085. const char *auth_header;
  7086. uint64_t nonce;
  7087. if (!ah || !conn) {
  7088. return 0;
  7089. }
  7090. (void)memset(ah, 0, sizeof(*ah));
  7091. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7092. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7093. return 0;
  7094. }
  7095. /* Make modifiable copy of the auth header */
  7096. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7097. s = buf;
  7098. /* Parse authorization header */
  7099. for (;;) {
  7100. /* Gobble initial spaces */
  7101. while (isspace((unsigned char)*s)) {
  7102. s++;
  7103. }
  7104. name = skip_quoted(&s, "=", " ", 0);
  7105. /* Value is either quote-delimited, or ends at first comma or space.
  7106. */
  7107. if (s[0] == '\"') {
  7108. s++;
  7109. value = skip_quoted(&s, "\"", " ", '\\');
  7110. if (s[0] == ',') {
  7111. s++;
  7112. }
  7113. } else {
  7114. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7115. * uses spaces */
  7116. }
  7117. if (*name == '\0') {
  7118. break;
  7119. }
  7120. if (!strcmp(name, "username")) {
  7121. ah->user = value;
  7122. } else if (!strcmp(name, "cnonce")) {
  7123. ah->cnonce = value;
  7124. } else if (!strcmp(name, "response")) {
  7125. ah->response = value;
  7126. } else if (!strcmp(name, "uri")) {
  7127. ah->uri = value;
  7128. } else if (!strcmp(name, "qop")) {
  7129. ah->qop = value;
  7130. } else if (!strcmp(name, "nc")) {
  7131. ah->nc = value;
  7132. } else if (!strcmp(name, "nonce")) {
  7133. ah->nonce = value;
  7134. }
  7135. }
  7136. #if !defined(NO_NONCE_CHECK)
  7137. /* Read the nonce from the response. */
  7138. if (ah->nonce == NULL) {
  7139. return 0;
  7140. }
  7141. s = NULL;
  7142. nonce = strtoull(ah->nonce, &s, 10);
  7143. if ((s == NULL) || (*s != 0)) {
  7144. return 0;
  7145. }
  7146. /* Convert the nonce from the client to a number. */
  7147. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7148. /* The converted number corresponds to the time the nounce has been
  7149. * created. This should not be earlier than the server start. */
  7150. /* Server side nonce check is valuable in all situations but one:
  7151. * if the server restarts frequently, but the client should not see
  7152. * that, so the server should accept nonces from previous starts. */
  7153. /* However, the reasonable default is to not accept a nonce from a
  7154. * previous start, so if anyone changed the access rights between
  7155. * two restarts, a new login is required. */
  7156. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7157. /* nonce is from a previous start of the server and no longer valid
  7158. * (replay attack?) */
  7159. return 0;
  7160. }
  7161. /* Check if the nonce is too high, so it has not (yet) been used by the
  7162. * server. */
  7163. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7164. + conn->dom_ctx->nonce_count)) {
  7165. return 0;
  7166. }
  7167. #else
  7168. (void)nonce;
  7169. #endif
  7170. /* CGI needs it as REMOTE_USER */
  7171. if (ah->user != NULL) {
  7172. conn->request_info.remote_user =
  7173. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7174. } else {
  7175. return 0;
  7176. }
  7177. return 1;
  7178. }
  7179. static const char *
  7180. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7181. {
  7182. if (!filep) {
  7183. return NULL;
  7184. }
  7185. if (filep->access.fp != NULL) {
  7186. return fgets(buf, (int)size, filep->access.fp);
  7187. } else {
  7188. return NULL;
  7189. }
  7190. }
  7191. /* Define the initial recursion depth for procesesing htpasswd files that
  7192. * include other htpasswd
  7193. * (or even the same) files. It is not difficult to provide a file or files
  7194. * s.t. they force civetweb
  7195. * to infinitely recurse and then crash.
  7196. */
  7197. #define INITIAL_DEPTH 9
  7198. #if INITIAL_DEPTH <= 0
  7199. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7200. #endif
  7201. #if !defined(NO_FILESYSTEMS)
  7202. struct read_auth_file_struct {
  7203. struct mg_connection *conn;
  7204. struct ah ah;
  7205. const char *domain;
  7206. char buf[256 + 256 + 40];
  7207. const char *f_user;
  7208. const char *f_domain;
  7209. const char *f_ha1;
  7210. };
  7211. static int
  7212. read_auth_file(struct mg_file *filep,
  7213. struct read_auth_file_struct *workdata,
  7214. int depth)
  7215. {
  7216. int is_authorized = 0;
  7217. struct mg_file fp;
  7218. size_t l;
  7219. if (!filep || !workdata || (0 == depth)) {
  7220. return 0;
  7221. }
  7222. /* Loop over passwords file */
  7223. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7224. l = strlen(workdata->buf);
  7225. while (l > 0) {
  7226. if (isspace((unsigned char)workdata->buf[l - 1])
  7227. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7228. l--;
  7229. workdata->buf[l] = 0;
  7230. } else
  7231. break;
  7232. }
  7233. if (l < 1) {
  7234. continue;
  7235. }
  7236. workdata->f_user = workdata->buf;
  7237. if (workdata->f_user[0] == ':') {
  7238. /* user names may not contain a ':' and may not be empty,
  7239. * so lines starting with ':' may be used for a special purpose
  7240. */
  7241. if (workdata->f_user[1] == '#') {
  7242. /* :# is a comment */
  7243. continue;
  7244. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7245. if (mg_fopen(workdata->conn,
  7246. workdata->f_user + 9,
  7247. MG_FOPEN_MODE_READ,
  7248. &fp)) {
  7249. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7250. (void)mg_fclose(
  7251. &fp.access); /* ignore error on read only file */
  7252. /* No need to continue processing files once we have a
  7253. * match, since nothing will reset it back
  7254. * to 0.
  7255. */
  7256. if (is_authorized) {
  7257. return is_authorized;
  7258. }
  7259. } else {
  7260. mg_cry_internal(workdata->conn,
  7261. "%s: cannot open authorization file: %s",
  7262. __func__,
  7263. workdata->buf);
  7264. }
  7265. continue;
  7266. }
  7267. /* everything is invalid for the moment (might change in the
  7268. * future) */
  7269. mg_cry_internal(workdata->conn,
  7270. "%s: syntax error in authorization file: %s",
  7271. __func__,
  7272. workdata->buf);
  7273. continue;
  7274. }
  7275. workdata->f_domain = strchr(workdata->f_user, ':');
  7276. if (workdata->f_domain == NULL) {
  7277. mg_cry_internal(workdata->conn,
  7278. "%s: syntax error in authorization file: %s",
  7279. __func__,
  7280. workdata->buf);
  7281. continue;
  7282. }
  7283. *(char *)(workdata->f_domain) = 0;
  7284. (workdata->f_domain)++;
  7285. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7286. if (workdata->f_ha1 == NULL) {
  7287. mg_cry_internal(workdata->conn,
  7288. "%s: syntax error in authorization file: %s",
  7289. __func__,
  7290. workdata->buf);
  7291. continue;
  7292. }
  7293. *(char *)(workdata->f_ha1) = 0;
  7294. (workdata->f_ha1)++;
  7295. if (!strcmp(workdata->ah.user, workdata->f_user)
  7296. && !strcmp(workdata->domain, workdata->f_domain)) {
  7297. return check_password(workdata->conn->request_info.request_method,
  7298. workdata->f_ha1,
  7299. workdata->ah.uri,
  7300. workdata->ah.nonce,
  7301. workdata->ah.nc,
  7302. workdata->ah.cnonce,
  7303. workdata->ah.qop,
  7304. workdata->ah.response);
  7305. }
  7306. }
  7307. return is_authorized;
  7308. }
  7309. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7310. static int
  7311. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7312. {
  7313. struct read_auth_file_struct workdata;
  7314. char buf[MG_BUF_LEN];
  7315. if (!conn || !conn->dom_ctx) {
  7316. return 0;
  7317. }
  7318. memset(&workdata, 0, sizeof(workdata));
  7319. workdata.conn = conn;
  7320. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7321. return 0;
  7322. }
  7323. if (realm) {
  7324. workdata.domain = realm;
  7325. } else {
  7326. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7327. }
  7328. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7329. }
  7330. /* Public function to check http digest authentication header */
  7331. int
  7332. mg_check_digest_access_authentication(struct mg_connection *conn,
  7333. const char *realm,
  7334. const char *filename)
  7335. {
  7336. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7337. int auth;
  7338. if (!conn || !filename) {
  7339. return -1;
  7340. }
  7341. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7342. return -2;
  7343. }
  7344. auth = authorize(conn, &file, realm);
  7345. mg_fclose(&file.access);
  7346. return auth;
  7347. }
  7348. #endif /* NO_FILESYSTEMS */
  7349. /* Return 1 if request is authorised, 0 otherwise. */
  7350. static int
  7351. check_authorization(struct mg_connection *conn, const char *path)
  7352. {
  7353. #if !defined(NO_FILESYSTEMS)
  7354. char fname[UTF8_PATH_MAX];
  7355. struct vec uri_vec, filename_vec;
  7356. const char *list;
  7357. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7358. int authorized = 1, truncated;
  7359. if (!conn || !conn->dom_ctx) {
  7360. return 0;
  7361. }
  7362. list = conn->dom_ctx->config[PROTECT_URI];
  7363. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7364. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7365. mg_snprintf(conn,
  7366. &truncated,
  7367. fname,
  7368. sizeof(fname),
  7369. "%.*s",
  7370. (int)filename_vec.len,
  7371. filename_vec.ptr);
  7372. if (truncated
  7373. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7374. mg_cry_internal(conn,
  7375. "%s: cannot open %s: %s",
  7376. __func__,
  7377. fname,
  7378. strerror(errno));
  7379. }
  7380. break;
  7381. }
  7382. }
  7383. if (!is_file_opened(&file.access)) {
  7384. open_auth_file(conn, path, &file);
  7385. }
  7386. if (is_file_opened(&file.access)) {
  7387. authorized = authorize(conn, &file, NULL);
  7388. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7389. }
  7390. return authorized;
  7391. #else
  7392. (void)conn;
  7393. (void)path;
  7394. return 1;
  7395. #endif /* NO_FILESYSTEMS */
  7396. }
  7397. /* Internal function. Assumes conn is valid */
  7398. static void
  7399. send_authorization_request(struct mg_connection *conn, const char *realm)
  7400. {
  7401. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7402. int trunc = 0;
  7403. char buf[128];
  7404. if (!realm) {
  7405. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7406. }
  7407. mg_lock_context(conn->phys_ctx);
  7408. nonce += conn->dom_ctx->nonce_count;
  7409. ++conn->dom_ctx->nonce_count;
  7410. mg_unlock_context(conn->phys_ctx);
  7411. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7412. conn->must_close = 1;
  7413. /* Create 401 response */
  7414. mg_response_header_start(conn, 401);
  7415. send_no_cache_header(conn);
  7416. send_additional_header(conn);
  7417. mg_response_header_add(conn, "Content-Length", "0", -1);
  7418. /* Content for "WWW-Authenticate" header */
  7419. mg_snprintf(conn,
  7420. &trunc,
  7421. buf,
  7422. sizeof(buf),
  7423. "Digest qop=\"auth\", realm=\"%s\", "
  7424. "nonce=\"%" UINT64_FMT "\"",
  7425. realm,
  7426. nonce);
  7427. if (!trunc) {
  7428. /* !trunc should always be true */
  7429. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7430. }
  7431. /* Send all headers */
  7432. mg_response_header_send(conn);
  7433. }
  7434. /* Interface function. Parameters are provided by the user, so do
  7435. * at least some basic checks.
  7436. */
  7437. int
  7438. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7439. const char *realm)
  7440. {
  7441. if (conn && conn->dom_ctx) {
  7442. send_authorization_request(conn, realm);
  7443. return 0;
  7444. }
  7445. return -1;
  7446. }
  7447. #if !defined(NO_FILES)
  7448. static int
  7449. is_authorized_for_put(struct mg_connection *conn)
  7450. {
  7451. if (conn) {
  7452. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7453. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7454. int ret = 0;
  7455. if (passfile != NULL
  7456. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7457. ret = authorize(conn, &file, NULL);
  7458. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7459. }
  7460. return ret;
  7461. }
  7462. return 0;
  7463. }
  7464. #endif
  7465. int
  7466. mg_modify_passwords_file(const char *fname,
  7467. const char *domain,
  7468. const char *user,
  7469. const char *pass)
  7470. {
  7471. int found, i;
  7472. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[UTF8_PATH_MAX + 8];
  7473. FILE *fp, *fp2;
  7474. found = 0;
  7475. fp = fp2 = NULL;
  7476. /* Regard empty password as no password - remove user record. */
  7477. if ((pass != NULL) && (pass[0] == '\0')) {
  7478. pass = NULL;
  7479. }
  7480. /* Other arguments must not be empty */
  7481. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7482. return 0;
  7483. }
  7484. /* Using the given file format, user name and domain must not contain
  7485. * ':'
  7486. */
  7487. if (strchr(user, ':') != NULL) {
  7488. return 0;
  7489. }
  7490. if (strchr(domain, ':') != NULL) {
  7491. return 0;
  7492. }
  7493. /* Do not allow control characters like newline in user name and domain.
  7494. * Do not allow excessively long names either. */
  7495. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7496. if (iscntrl((unsigned char)user[i])) {
  7497. return 0;
  7498. }
  7499. }
  7500. if (user[i]) {
  7501. return 0;
  7502. }
  7503. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7504. if (iscntrl((unsigned char)domain[i])) {
  7505. return 0;
  7506. }
  7507. }
  7508. if (domain[i]) {
  7509. return 0;
  7510. }
  7511. /* The maximum length of the path to the password file is limited */
  7512. if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
  7513. return 0;
  7514. }
  7515. /* Create a temporary file name. Length has been checked before. */
  7516. strcpy(tmp, fname);
  7517. strcat(tmp, ".tmp");
  7518. /* Create the file if does not exist */
  7519. /* Use of fopen here is OK, since fname is only ASCII */
  7520. if ((fp = fopen(fname, "a+")) != NULL) {
  7521. (void)fclose(fp);
  7522. }
  7523. /* Open the given file and temporary file */
  7524. if ((fp = fopen(fname, "r")) == NULL) {
  7525. return 0;
  7526. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7527. fclose(fp);
  7528. return 0;
  7529. }
  7530. /* Copy the stuff to temporary file */
  7531. while (fgets(line, sizeof(line), fp) != NULL) {
  7532. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7533. continue;
  7534. }
  7535. u[255] = 0;
  7536. d[255] = 0;
  7537. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7538. found++;
  7539. if (pass != NULL) {
  7540. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7541. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7542. }
  7543. } else {
  7544. fprintf(fp2, "%s", line);
  7545. }
  7546. }
  7547. /* If new user, just add it */
  7548. if (!found && (pass != NULL)) {
  7549. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7550. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7551. }
  7552. /* Close files */
  7553. fclose(fp);
  7554. fclose(fp2);
  7555. /* Put the temp file in place of real file */
  7556. IGNORE_UNUSED_RESULT(remove(fname));
  7557. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7558. return 1;
  7559. }
  7560. static int
  7561. is_valid_port(unsigned long port)
  7562. {
  7563. return (port <= 0xffff);
  7564. }
  7565. static int
  7566. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7567. {
  7568. struct addrinfo hints, *res, *ressave;
  7569. int func_ret = 0;
  7570. int gai_ret;
  7571. memset(&hints, 0, sizeof(struct addrinfo));
  7572. hints.ai_family = af;
  7573. if (!resolve_src) {
  7574. hints.ai_flags = AI_NUMERICHOST;
  7575. }
  7576. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7577. if (gai_ret != 0) {
  7578. /* gai_strerror could be used to convert gai_ret to a string */
  7579. /* POSIX return values: see
  7580. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7581. */
  7582. /* Windows return values: see
  7583. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7584. */
  7585. return 0;
  7586. }
  7587. ressave = res;
  7588. while (res) {
  7589. if ((dstlen >= (size_t)res->ai_addrlen)
  7590. && (res->ai_addr->sa_family == af)) {
  7591. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7592. func_ret = 1;
  7593. }
  7594. res = res->ai_next;
  7595. }
  7596. freeaddrinfo(ressave);
  7597. return func_ret;
  7598. }
  7599. static int
  7600. connect_socket(struct mg_context *ctx /* may be NULL */,
  7601. const char *host,
  7602. int port,
  7603. int use_ssl,
  7604. char *ebuf,
  7605. size_t ebuf_len,
  7606. SOCKET *sock /* output: socket, must not be NULL */,
  7607. union usa *sa /* output: socket address, must not be NULL */
  7608. )
  7609. {
  7610. int ip_ver = 0;
  7611. int conn_ret = -1;
  7612. int sockerr = 0;
  7613. *sock = INVALID_SOCKET;
  7614. memset(sa, 0, sizeof(*sa));
  7615. if (ebuf_len > 0) {
  7616. *ebuf = 0;
  7617. }
  7618. if (host == NULL) {
  7619. mg_snprintf(NULL,
  7620. NULL, /* No truncation check for ebuf */
  7621. ebuf,
  7622. ebuf_len,
  7623. "%s",
  7624. "NULL host");
  7625. return 0;
  7626. }
  7627. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7628. mg_snprintf(NULL,
  7629. NULL, /* No truncation check for ebuf */
  7630. ebuf,
  7631. ebuf_len,
  7632. "%s",
  7633. "invalid port");
  7634. return 0;
  7635. }
  7636. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7637. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7638. if (use_ssl && (TLS_client_method == NULL)) {
  7639. mg_snprintf(NULL,
  7640. NULL, /* No truncation check for ebuf */
  7641. ebuf,
  7642. ebuf_len,
  7643. "%s",
  7644. "SSL is not initialized");
  7645. return 0;
  7646. }
  7647. #else
  7648. if (use_ssl && (SSLv23_client_method == NULL)) {
  7649. mg_snprintf(NULL,
  7650. NULL, /* No truncation check for ebuf */
  7651. ebuf,
  7652. ebuf_len,
  7653. "%s",
  7654. "SSL is not initialized");
  7655. return 0;
  7656. }
  7657. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7658. #else
  7659. (void)use_ssl;
  7660. #endif /* NO SSL */
  7661. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7662. sa->sin.sin_port = htons((uint16_t)port);
  7663. ip_ver = 4;
  7664. #if defined(USE_IPV6)
  7665. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7666. sa->sin6.sin6_port = htons((uint16_t)port);
  7667. ip_ver = 6;
  7668. } else if (host[0] == '[') {
  7669. /* While getaddrinfo on Windows will work with [::1],
  7670. * getaddrinfo on Linux only works with ::1 (without []). */
  7671. size_t l = strlen(host + 1);
  7672. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7673. if (h) {
  7674. h[l - 1] = 0;
  7675. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7676. sa->sin6.sin6_port = htons((uint16_t)port);
  7677. ip_ver = 6;
  7678. }
  7679. mg_free(h);
  7680. }
  7681. #endif
  7682. }
  7683. if (ip_ver == 0) {
  7684. mg_snprintf(NULL,
  7685. NULL, /* No truncation check for ebuf */
  7686. ebuf,
  7687. ebuf_len,
  7688. "%s",
  7689. "host not found");
  7690. return 0;
  7691. }
  7692. if (ip_ver == 4) {
  7693. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7694. }
  7695. #if defined(USE_IPV6)
  7696. else if (ip_ver == 6) {
  7697. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7698. }
  7699. #endif
  7700. #if 0 /* Not available as client */
  7701. #if defined(USE_X_DOM_SOCKET)
  7702. else if (ip_ver == 99) {
  7703. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7704. }
  7705. #endif
  7706. #endif
  7707. if (*sock == INVALID_SOCKET) {
  7708. mg_snprintf(NULL,
  7709. NULL, /* No truncation check for ebuf */
  7710. ebuf,
  7711. ebuf_len,
  7712. "socket(): %s",
  7713. strerror(ERRNO));
  7714. return 0;
  7715. }
  7716. if (0 != set_non_blocking_mode(*sock)) {
  7717. mg_snprintf(NULL,
  7718. NULL, /* No truncation check for ebuf */
  7719. ebuf,
  7720. ebuf_len,
  7721. "Cannot set socket to non-blocking: %s",
  7722. strerror(ERRNO));
  7723. closesocket(*sock);
  7724. *sock = INVALID_SOCKET;
  7725. return 0;
  7726. }
  7727. set_close_on_exec(*sock, NULL, ctx);
  7728. if (ip_ver == 4) {
  7729. /* connected with IPv4 */
  7730. conn_ret = connect(*sock,
  7731. (struct sockaddr *)((void *)&sa->sin),
  7732. sizeof(sa->sin));
  7733. }
  7734. #if defined(USE_IPV6)
  7735. else if (ip_ver == 6) {
  7736. /* connected with IPv6 */
  7737. conn_ret = connect(*sock,
  7738. (struct sockaddr *)((void *)&sa->sin6),
  7739. sizeof(sa->sin6));
  7740. }
  7741. #endif
  7742. if (conn_ret != 0) {
  7743. sockerr = ERRNO;
  7744. }
  7745. #if defined(_WIN32)
  7746. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7747. #else
  7748. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7749. #endif
  7750. /* Data for getsockopt */
  7751. void *psockerr = &sockerr;
  7752. int ret;
  7753. #if defined(_WIN32)
  7754. int len = (int)sizeof(sockerr);
  7755. #else
  7756. socklen_t len = (socklen_t)sizeof(sockerr);
  7757. #endif
  7758. /* Data for poll */
  7759. struct mg_pollfd pfd[1];
  7760. int pollres;
  7761. int ms_wait = 10000; /* 10 second timeout */
  7762. stop_flag_t nonstop;
  7763. STOP_FLAG_ASSIGN(&nonstop, 0);
  7764. /* For a non-blocking socket, the connect sequence is:
  7765. * 1) call connect (will not block)
  7766. * 2) wait until the socket is ready for writing (select or poll)
  7767. * 3) check connection state with getsockopt
  7768. */
  7769. pfd[0].fd = *sock;
  7770. pfd[0].events = POLLOUT;
  7771. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7772. if (pollres != 1) {
  7773. /* Not connected */
  7774. mg_snprintf(NULL,
  7775. NULL, /* No truncation check for ebuf */
  7776. ebuf,
  7777. ebuf_len,
  7778. "connect(%s:%d): timeout",
  7779. host,
  7780. port);
  7781. closesocket(*sock);
  7782. *sock = INVALID_SOCKET;
  7783. return 0;
  7784. }
  7785. #if defined(_WIN32)
  7786. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7787. #else
  7788. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7789. #endif
  7790. if ((ret == 0) && (sockerr == 0)) {
  7791. conn_ret = 0;
  7792. }
  7793. }
  7794. if (conn_ret != 0) {
  7795. /* Not connected */
  7796. mg_snprintf(NULL,
  7797. NULL, /* No truncation check for ebuf */
  7798. ebuf,
  7799. ebuf_len,
  7800. "connect(%s:%d): error %s",
  7801. host,
  7802. port,
  7803. strerror(sockerr));
  7804. closesocket(*sock);
  7805. *sock = INVALID_SOCKET;
  7806. return 0;
  7807. }
  7808. return 1;
  7809. }
  7810. int
  7811. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7812. {
  7813. static const char *dont_escape = "._-$,;~()";
  7814. static const char *hex = "0123456789abcdef";
  7815. char *pos = dst;
  7816. const char *end = dst + dst_len - 1;
  7817. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7818. if (isalnum((unsigned char)*src)
  7819. || (strchr(dont_escape, *src) != NULL)) {
  7820. *pos = *src;
  7821. } else if (pos + 2 < end) {
  7822. pos[0] = '%';
  7823. pos[1] = hex[(unsigned char)*src >> 4];
  7824. pos[2] = hex[(unsigned char)*src & 0xf];
  7825. pos += 2;
  7826. } else {
  7827. break;
  7828. }
  7829. }
  7830. *pos = '\0';
  7831. return (*src == '\0') ? (int)(pos - dst) : -1;
  7832. }
  7833. /* Return 0 on success, non-zero if an error occurs. */
  7834. static int
  7835. print_dir_entry(struct de *de)
  7836. {
  7837. size_t namesize, escsize, i;
  7838. char *href, *esc, *p;
  7839. char size[64], mod[64];
  7840. #if defined(REENTRANT_TIME)
  7841. struct tm _tm;
  7842. struct tm *tm = &_tm;
  7843. #else
  7844. struct tm *tm;
  7845. #endif
  7846. /* Estimate worst case size for encoding and escaping */
  7847. namesize = strlen(de->file_name) + 1;
  7848. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7849. href = (char *)mg_malloc(namesize * 3 + escsize);
  7850. if (href == NULL) {
  7851. return -1;
  7852. }
  7853. mg_url_encode(de->file_name, href, namesize * 3);
  7854. esc = NULL;
  7855. if (escsize > 0) {
  7856. /* HTML escaping needed */
  7857. esc = href + namesize * 3;
  7858. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7859. mg_strlcpy(p, de->file_name + i, 2);
  7860. if (*p == '&') {
  7861. strcpy(p, "&amp;");
  7862. } else if (*p == '<') {
  7863. strcpy(p, "&lt;");
  7864. } else if (*p == '>') {
  7865. strcpy(p, "&gt;");
  7866. }
  7867. }
  7868. }
  7869. if (de->file.is_directory) {
  7870. mg_snprintf(de->conn,
  7871. NULL, /* Buffer is big enough */
  7872. size,
  7873. sizeof(size),
  7874. "%s",
  7875. "[DIRECTORY]");
  7876. } else {
  7877. /* We use (signed) cast below because MSVC 6 compiler cannot
  7878. * convert unsigned __int64 to double. Sigh. */
  7879. if (de->file.size < 1024) {
  7880. mg_snprintf(de->conn,
  7881. NULL, /* Buffer is big enough */
  7882. size,
  7883. sizeof(size),
  7884. "%d",
  7885. (int)de->file.size);
  7886. } else if (de->file.size < 0x100000) {
  7887. mg_snprintf(de->conn,
  7888. NULL, /* Buffer is big enough */
  7889. size,
  7890. sizeof(size),
  7891. "%.1fk",
  7892. (double)de->file.size / 1024.0);
  7893. } else if (de->file.size < 0x40000000) {
  7894. mg_snprintf(de->conn,
  7895. NULL, /* Buffer is big enough */
  7896. size,
  7897. sizeof(size),
  7898. "%.1fM",
  7899. (double)de->file.size / 1048576);
  7900. } else {
  7901. mg_snprintf(de->conn,
  7902. NULL, /* Buffer is big enough */
  7903. size,
  7904. sizeof(size),
  7905. "%.1fG",
  7906. (double)de->file.size / 1073741824);
  7907. }
  7908. }
  7909. /* Note: mg_snprintf will not cause a buffer overflow above.
  7910. * So, string truncation checks are not required here. */
  7911. #if defined(REENTRANT_TIME)
  7912. localtime_r(&de->file.last_modified, tm);
  7913. #else
  7914. tm = localtime(&de->file.last_modified);
  7915. #endif
  7916. if (tm != NULL) {
  7917. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7918. } else {
  7919. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7920. mod[sizeof(mod) - 1] = '\0';
  7921. }
  7922. mg_printf(de->conn,
  7923. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7924. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7925. href,
  7926. de->file.is_directory ? "/" : "",
  7927. esc ? esc : de->file_name,
  7928. de->file.is_directory ? "/" : "",
  7929. mod,
  7930. size);
  7931. mg_free(href);
  7932. return 0;
  7933. }
  7934. /* This function is called from send_directory() and used for
  7935. * sorting directory entries by size, or name, or modification time.
  7936. * On windows, __cdecl specification is needed in case if project is built
  7937. * with __stdcall convention. qsort always requires __cdels callback. */
  7938. static int WINCDECL
  7939. compare_dir_entries(const void *p1, const void *p2)
  7940. {
  7941. if (p1 && p2) {
  7942. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7943. const char *query_string = a->conn->request_info.query_string;
  7944. int cmp_result = 0;
  7945. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7946. query_string = "n";
  7947. }
  7948. if (a->file.is_directory && !b->file.is_directory) {
  7949. return -1; /* Always put directories on top */
  7950. } else if (!a->file.is_directory && b->file.is_directory) {
  7951. return 1; /* Always put directories on top */
  7952. } else if (*query_string == 'n') {
  7953. cmp_result = strcmp(a->file_name, b->file_name);
  7954. } else if (*query_string == 's') {
  7955. cmp_result = (a->file.size == b->file.size)
  7956. ? 0
  7957. : ((a->file.size > b->file.size) ? 1 : -1);
  7958. } else if (*query_string == 'd') {
  7959. cmp_result =
  7960. (a->file.last_modified == b->file.last_modified)
  7961. ? 0
  7962. : ((a->file.last_modified > b->file.last_modified) ? 1
  7963. : -1);
  7964. }
  7965. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7966. }
  7967. return 0;
  7968. }
  7969. static int
  7970. must_hide_file(struct mg_connection *conn, const char *path)
  7971. {
  7972. if (conn && conn->dom_ctx) {
  7973. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7974. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7975. return (match_prefix_strlen(pw_pattern, path) > 0)
  7976. || (match_prefix_strlen(pattern, path) > 0);
  7977. }
  7978. return 0;
  7979. }
  7980. #if !defined(NO_FILESYSTEMS)
  7981. static int
  7982. scan_directory(struct mg_connection *conn,
  7983. const char *dir,
  7984. void *data,
  7985. int (*cb)(struct de *, void *))
  7986. {
  7987. char path[UTF8_PATH_MAX];
  7988. struct dirent *dp;
  7989. DIR *dirp;
  7990. struct de de;
  7991. int truncated;
  7992. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7993. return 0;
  7994. } else {
  7995. de.conn = conn;
  7996. while ((dp = mg_readdir(dirp)) != NULL) {
  7997. /* Do not show current dir and hidden files */
  7998. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7999. || must_hide_file(conn, dp->d_name)) {
  8000. continue;
  8001. }
  8002. mg_snprintf(
  8003. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8004. /* If we don't memset stat structure to zero, mtime will have
  8005. * garbage and strftime() will segfault later on in
  8006. * print_dir_entry(). memset is required only if mg_stat()
  8007. * fails. For more details, see
  8008. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8009. memset(&de.file, 0, sizeof(de.file));
  8010. if (truncated) {
  8011. /* If the path is not complete, skip processing. */
  8012. continue;
  8013. }
  8014. if (!mg_stat(conn, path, &de.file)) {
  8015. mg_cry_internal(conn,
  8016. "%s: mg_stat(%s) failed: %s",
  8017. __func__,
  8018. path,
  8019. strerror(ERRNO));
  8020. }
  8021. de.file_name = dp->d_name;
  8022. if (cb(&de, data)) {
  8023. /* stopped */
  8024. break;
  8025. }
  8026. }
  8027. (void)mg_closedir(dirp);
  8028. }
  8029. return 1;
  8030. }
  8031. #endif /* NO_FILESYSTEMS */
  8032. #if !defined(NO_FILES)
  8033. static int
  8034. remove_directory(struct mg_connection *conn, const char *dir)
  8035. {
  8036. char path[UTF8_PATH_MAX];
  8037. struct dirent *dp;
  8038. DIR *dirp;
  8039. struct de de;
  8040. int truncated;
  8041. int ok = 1;
  8042. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8043. return 0;
  8044. } else {
  8045. de.conn = conn;
  8046. while ((dp = mg_readdir(dirp)) != NULL) {
  8047. /* Do not show current dir (but show hidden files as they will
  8048. * also be removed) */
  8049. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8050. continue;
  8051. }
  8052. mg_snprintf(
  8053. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8054. /* If we don't memset stat structure to zero, mtime will have
  8055. * garbage and strftime() will segfault later on in
  8056. * print_dir_entry(). memset is required only if mg_stat()
  8057. * fails. For more details, see
  8058. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8059. memset(&de.file, 0, sizeof(de.file));
  8060. if (truncated) {
  8061. /* Do not delete anything shorter */
  8062. ok = 0;
  8063. continue;
  8064. }
  8065. if (!mg_stat(conn, path, &de.file)) {
  8066. mg_cry_internal(conn,
  8067. "%s: mg_stat(%s) failed: %s",
  8068. __func__,
  8069. path,
  8070. strerror(ERRNO));
  8071. ok = 0;
  8072. }
  8073. if (de.file.is_directory) {
  8074. if (remove_directory(conn, path) == 0) {
  8075. ok = 0;
  8076. }
  8077. } else {
  8078. /* This will fail file is the file is in memory */
  8079. if (mg_remove(conn, path) == 0) {
  8080. ok = 0;
  8081. }
  8082. }
  8083. }
  8084. (void)mg_closedir(dirp);
  8085. IGNORE_UNUSED_RESULT(rmdir(dir));
  8086. }
  8087. return ok;
  8088. }
  8089. #endif
  8090. struct dir_scan_data {
  8091. struct de *entries;
  8092. size_t num_entries;
  8093. size_t arr_size;
  8094. };
  8095. #if !defined(NO_FILESYSTEMS)
  8096. static int
  8097. dir_scan_callback(struct de *de, void *data)
  8098. {
  8099. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8100. struct de *entries = dsd->entries;
  8101. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8102. /* Here "entries" is a temporary pointer and can be replaced,
  8103. * "dsd->entries" is the original pointer */
  8104. entries =
  8105. (struct de *)mg_realloc(entries,
  8106. dsd->arr_size * 2 * sizeof(entries[0]));
  8107. if (entries == NULL) {
  8108. /* stop scan */
  8109. return 1;
  8110. }
  8111. dsd->entries = entries;
  8112. dsd->arr_size *= 2;
  8113. }
  8114. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8115. if (entries[dsd->num_entries].file_name == NULL) {
  8116. /* stop scan */
  8117. return 1;
  8118. }
  8119. entries[dsd->num_entries].file = de->file;
  8120. entries[dsd->num_entries].conn = de->conn;
  8121. dsd->num_entries++;
  8122. return 0;
  8123. }
  8124. static void
  8125. handle_directory_request(struct mg_connection *conn, const char *dir)
  8126. {
  8127. size_t i;
  8128. int sort_direction;
  8129. struct dir_scan_data data = {NULL, 0, 128};
  8130. char date[64], *esc, *p;
  8131. const char *title;
  8132. time_t curtime = time(NULL);
  8133. if (!conn) {
  8134. return;
  8135. }
  8136. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8137. mg_send_http_error(conn,
  8138. 500,
  8139. "Error: Cannot open directory\nopendir(%s): %s",
  8140. dir,
  8141. strerror(ERRNO));
  8142. return;
  8143. }
  8144. gmt_time_string(date, sizeof(date), &curtime);
  8145. esc = NULL;
  8146. title = conn->request_info.local_uri;
  8147. if (title[strcspn(title, "&<>")]) {
  8148. /* HTML escaping needed */
  8149. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8150. if (esc) {
  8151. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8152. mg_strlcpy(p, title + i, 2);
  8153. if (*p == '&') {
  8154. strcpy(p, "&amp;");
  8155. } else if (*p == '<') {
  8156. strcpy(p, "&lt;");
  8157. } else if (*p == '>') {
  8158. strcpy(p, "&gt;");
  8159. }
  8160. }
  8161. } else {
  8162. title = "";
  8163. }
  8164. }
  8165. sort_direction = ((conn->request_info.query_string != NULL)
  8166. && (conn->request_info.query_string[0] != '\0')
  8167. && (conn->request_info.query_string[1] == 'd'))
  8168. ? 'a'
  8169. : 'd';
  8170. conn->must_close = 1;
  8171. /* Create 200 OK response */
  8172. mg_response_header_start(conn, 200);
  8173. send_static_cache_header(conn);
  8174. send_additional_header(conn);
  8175. mg_response_header_add(conn,
  8176. "Content-Type",
  8177. "text/html; charset=utf-8",
  8178. -1);
  8179. /* Send all headers */
  8180. mg_response_header_send(conn);
  8181. /* Body */
  8182. mg_printf(conn,
  8183. "<html><head><title>Index of %s</title>"
  8184. "<style>th {text-align: left;}</style></head>"
  8185. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8186. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8187. "<th><a href=\"?d%c\">Modified</a></th>"
  8188. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8189. "<tr><td colspan=\"3\"><hr></td></tr>",
  8190. esc ? esc : title,
  8191. esc ? esc : title,
  8192. sort_direction,
  8193. sort_direction,
  8194. sort_direction);
  8195. mg_free(esc);
  8196. /* Print first entry - link to a parent directory */
  8197. mg_printf(conn,
  8198. "<tr><td><a href=\"%s\">%s</a></td>"
  8199. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8200. "..",
  8201. "Parent directory",
  8202. "-",
  8203. "-");
  8204. /* Sort and print directory entries */
  8205. if (data.entries != NULL) {
  8206. qsort(data.entries,
  8207. data.num_entries,
  8208. sizeof(data.entries[0]),
  8209. compare_dir_entries);
  8210. for (i = 0; i < data.num_entries; i++) {
  8211. print_dir_entry(&data.entries[i]);
  8212. mg_free(data.entries[i].file_name);
  8213. }
  8214. mg_free(data.entries);
  8215. }
  8216. mg_printf(conn, "%s", "</table></pre></body></html>");
  8217. conn->status_code = 200;
  8218. }
  8219. #endif /* NO_FILESYSTEMS */
  8220. /* Send len bytes from the opened file to the client. */
  8221. static void
  8222. send_file_data(struct mg_connection *conn,
  8223. struct mg_file *filep,
  8224. int64_t offset,
  8225. int64_t len)
  8226. {
  8227. char buf[MG_BUF_LEN];
  8228. int to_read, num_read, num_written;
  8229. int64_t size;
  8230. if (!filep || !conn) {
  8231. return;
  8232. }
  8233. /* Sanity check the offset */
  8234. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8235. : (int64_t)(filep->stat.size);
  8236. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8237. if (len > 0 && filep->access.fp != NULL) {
  8238. /* file stored on disk */
  8239. #if defined(__linux__)
  8240. /* sendfile is only available for Linux */
  8241. if ((conn->ssl == 0) && (conn->throttle == 0)
  8242. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8243. "yes"))) {
  8244. off_t sf_offs = (off_t)offset;
  8245. ssize_t sf_sent;
  8246. int sf_file = fileno(filep->access.fp);
  8247. int loop_cnt = 0;
  8248. do {
  8249. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8250. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8251. size_t sf_tosend =
  8252. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8253. sf_sent =
  8254. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8255. if (sf_sent > 0) {
  8256. len -= sf_sent;
  8257. offset += sf_sent;
  8258. } else if (loop_cnt == 0) {
  8259. /* This file can not be sent using sendfile.
  8260. * This might be the case for pseudo-files in the
  8261. * /sys/ and /proc/ file system.
  8262. * Use the regular user mode copy code instead. */
  8263. break;
  8264. } else if (sf_sent == 0) {
  8265. /* No error, but 0 bytes sent. May be EOF? */
  8266. return;
  8267. }
  8268. loop_cnt++;
  8269. } while ((len > 0) && (sf_sent >= 0));
  8270. if (sf_sent > 0) {
  8271. return; /* OK */
  8272. }
  8273. /* sf_sent<0 means error, thus fall back to the classic way */
  8274. /* This is always the case, if sf_file is not a "normal" file,
  8275. * e.g., for sending data from the output of a CGI process. */
  8276. offset = (int64_t)sf_offs;
  8277. }
  8278. #endif
  8279. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8280. mg_cry_internal(conn,
  8281. "%s: fseeko() failed: %s",
  8282. __func__,
  8283. strerror(ERRNO));
  8284. mg_send_http_error(
  8285. conn,
  8286. 500,
  8287. "%s",
  8288. "Error: Unable to access file at requested position.");
  8289. } else {
  8290. while (len > 0) {
  8291. /* Calculate how much to read from the file in the buffer */
  8292. to_read = sizeof(buf);
  8293. if ((int64_t)to_read > len) {
  8294. to_read = (int)len;
  8295. }
  8296. /* Read from file, exit the loop on error */
  8297. if ((num_read =
  8298. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8299. <= 0) {
  8300. break;
  8301. }
  8302. /* Send read bytes to the client, exit the loop on error */
  8303. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8304. != num_read) {
  8305. break;
  8306. }
  8307. /* Both read and were successful, adjust counters */
  8308. len -= num_written;
  8309. }
  8310. }
  8311. }
  8312. }
  8313. static int
  8314. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8315. {
  8316. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8317. }
  8318. static void
  8319. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8320. {
  8321. if ((filestat != NULL) && (buf != NULL)) {
  8322. mg_snprintf(NULL,
  8323. NULL, /* All calls to construct_etag use 64 byte buffer */
  8324. buf,
  8325. buf_len,
  8326. "\"%lx.%" INT64_FMT "\"",
  8327. (unsigned long)filestat->last_modified,
  8328. filestat->size);
  8329. }
  8330. }
  8331. static void
  8332. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8333. {
  8334. if (filep != NULL && filep->fp != NULL) {
  8335. #if defined(_WIN32)
  8336. (void)conn; /* Unused. */
  8337. #else
  8338. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8339. mg_cry_internal(conn,
  8340. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8341. __func__,
  8342. strerror(ERRNO));
  8343. }
  8344. #endif
  8345. }
  8346. }
  8347. #if defined(USE_ZLIB)
  8348. #include "mod_zlib.inl"
  8349. #endif
  8350. #if !defined(NO_FILESYSTEMS)
  8351. static void
  8352. handle_static_file_request(struct mg_connection *conn,
  8353. const char *path,
  8354. struct mg_file *filep,
  8355. const char *mime_type,
  8356. const char *additional_headers)
  8357. {
  8358. char lm[64], etag[64];
  8359. char range[128]; /* large enough, so there will be no overflow */
  8360. const char *range_hdr;
  8361. int64_t cl, r1, r2;
  8362. struct vec mime_vec;
  8363. int n, truncated;
  8364. char gz_path[UTF8_PATH_MAX];
  8365. const char *encoding = 0;
  8366. const char *origin_hdr;
  8367. const char *cors_orig_cfg;
  8368. const char *cors1, *cors2;
  8369. int is_head_request;
  8370. #if defined(USE_ZLIB)
  8371. /* Compression is allowed, unless there is a reason not to use
  8372. * compression. If the file is already compressed, too small or a
  8373. * "range" request was made, on the fly compression is not possible. */
  8374. int allow_on_the_fly_compression = 1;
  8375. #endif
  8376. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8377. return;
  8378. }
  8379. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8380. if (mime_type == NULL) {
  8381. get_mime_type(conn, path, &mime_vec);
  8382. } else {
  8383. mime_vec.ptr = mime_type;
  8384. mime_vec.len = strlen(mime_type);
  8385. }
  8386. if (filep->stat.size > INT64_MAX) {
  8387. mg_send_http_error(conn,
  8388. 500,
  8389. "Error: File size is too large to send\n%" INT64_FMT,
  8390. filep->stat.size);
  8391. return;
  8392. }
  8393. cl = (int64_t)filep->stat.size;
  8394. conn->status_code = 200;
  8395. range[0] = '\0';
  8396. #if defined(USE_ZLIB)
  8397. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8398. * it's important to rewrite the filename after resolving
  8399. * the mime type from it, to preserve the actual file's type */
  8400. if (!conn->accept_gzip) {
  8401. allow_on_the_fly_compression = 0;
  8402. }
  8403. #endif
  8404. /* Check if there is a range header */
  8405. range_hdr = mg_get_header(conn, "Range");
  8406. /* For gzipped files, add *.gz */
  8407. if (filep->stat.is_gzipped) {
  8408. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8409. if (truncated) {
  8410. mg_send_http_error(conn,
  8411. 500,
  8412. "Error: Path of zipped file too long (%s)",
  8413. path);
  8414. return;
  8415. }
  8416. path = gz_path;
  8417. encoding = "gzip";
  8418. #if defined(USE_ZLIB)
  8419. /* File is already compressed. No "on the fly" compression. */
  8420. allow_on_the_fly_compression = 0;
  8421. #endif
  8422. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8423. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8424. struct mg_file_stat file_stat;
  8425. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8426. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8427. && !file_stat.is_directory) {
  8428. file_stat.is_gzipped = 1;
  8429. filep->stat = file_stat;
  8430. cl = (int64_t)filep->stat.size;
  8431. path = gz_path;
  8432. encoding = "gzip";
  8433. #if defined(USE_ZLIB)
  8434. /* File is already compressed. No "on the fly" compression. */
  8435. allow_on_the_fly_compression = 0;
  8436. #endif
  8437. }
  8438. }
  8439. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8440. mg_send_http_error(conn,
  8441. 500,
  8442. "Error: Cannot open file\nfopen(%s): %s",
  8443. path,
  8444. strerror(ERRNO));
  8445. return;
  8446. }
  8447. fclose_on_exec(&filep->access, conn);
  8448. /* If "Range" request was made: parse header, send only selected part
  8449. * of the file. */
  8450. r1 = r2 = 0;
  8451. if ((range_hdr != NULL)
  8452. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8453. && (r2 >= 0)) {
  8454. /* actually, range requests don't play well with a pre-gzipped
  8455. * file (since the range is specified in the uncompressed space) */
  8456. if (filep->stat.is_gzipped) {
  8457. mg_send_http_error(
  8458. conn,
  8459. 416, /* 416 = Range Not Satisfiable */
  8460. "%s",
  8461. "Error: Range requests in gzipped files are not supported");
  8462. (void)mg_fclose(
  8463. &filep->access); /* ignore error on read only file */
  8464. return;
  8465. }
  8466. conn->status_code = 206;
  8467. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8468. mg_snprintf(conn,
  8469. NULL, /* range buffer is big enough */
  8470. range,
  8471. sizeof(range),
  8472. "bytes "
  8473. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8474. r1,
  8475. r1 + cl - 1,
  8476. filep->stat.size);
  8477. #if defined(USE_ZLIB)
  8478. /* Do not compress ranges. */
  8479. allow_on_the_fly_compression = 0;
  8480. #endif
  8481. }
  8482. /* Do not compress small files. Small files do not benefit from file
  8483. * compression, but there is still some overhead. */
  8484. #if defined(USE_ZLIB)
  8485. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8486. /* File is below the size limit. */
  8487. allow_on_the_fly_compression = 0;
  8488. }
  8489. #endif
  8490. /* Standard CORS header */
  8491. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8492. origin_hdr = mg_get_header(conn, "Origin");
  8493. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8494. /* Cross-origin resource sharing (CORS), see
  8495. * http://www.html5rocks.com/en/tutorials/cors/,
  8496. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8497. * -
  8498. * preflight is not supported for files. */
  8499. cors1 = "Access-Control-Allow-Origin";
  8500. cors2 = cors_orig_cfg;
  8501. } else {
  8502. cors1 = cors2 = "";
  8503. }
  8504. /* Prepare Etag, and Last-Modified headers. */
  8505. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8506. construct_etag(etag, sizeof(etag), &filep->stat);
  8507. /* Create 2xx (200, 206) response */
  8508. mg_response_header_start(conn, conn->status_code);
  8509. send_static_cache_header(conn);
  8510. send_additional_header(conn);
  8511. mg_response_header_add(conn,
  8512. "Content-Type",
  8513. mime_vec.ptr,
  8514. (int)mime_vec.len);
  8515. if (cors1[0] != 0) {
  8516. mg_response_header_add(conn, cors1, cors2, -1);
  8517. }
  8518. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8519. mg_response_header_add(conn, "Etag", etag, -1);
  8520. #if defined(USE_ZLIB)
  8521. /* On the fly compression allowed */
  8522. if (allow_on_the_fly_compression) {
  8523. /* For on the fly compression, we don't know the content size in
  8524. * advance, so we have to use chunked encoding */
  8525. encoding = "gzip";
  8526. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8527. /* HTTP/2 is always using "chunks" (frames) */
  8528. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8529. }
  8530. } else
  8531. #endif
  8532. {
  8533. /* Without on-the-fly compression, we know the content-length
  8534. * and we can use ranges (with on-the-fly compression we cannot).
  8535. * So we send these response headers only in this case. */
  8536. char len[32];
  8537. int trunc = 0;
  8538. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8539. if (!trunc) {
  8540. mg_response_header_add(conn, "Content-Length", len, -1);
  8541. }
  8542. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8543. }
  8544. if (encoding) {
  8545. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8546. }
  8547. if (range[0] != 0) {
  8548. mg_response_header_add(conn, "Content-Range", range, -1);
  8549. }
  8550. /* The code above does not add any header starting with X- to make
  8551. * sure no one of the additional_headers is included twice */
  8552. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8553. mg_response_header_add_lines(conn, additional_headers);
  8554. }
  8555. /* Send all headers */
  8556. mg_response_header_send(conn);
  8557. if (!is_head_request) {
  8558. #if defined(USE_ZLIB)
  8559. if (allow_on_the_fly_compression) {
  8560. /* Compress and send */
  8561. send_compressed_data(conn, filep);
  8562. } else
  8563. #endif
  8564. {
  8565. /* Send file directly */
  8566. send_file_data(conn, filep, r1, cl);
  8567. }
  8568. }
  8569. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8570. }
  8571. int
  8572. mg_send_file_body(struct mg_connection *conn, const char *path)
  8573. {
  8574. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8575. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8576. return -1;
  8577. }
  8578. fclose_on_exec(&file.access, conn);
  8579. send_file_data(conn, &file, 0, INT64_MAX);
  8580. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8581. return 0; /* >= 0 for OK */
  8582. }
  8583. #endif /* NO_FILESYSTEMS */
  8584. #if !defined(NO_CACHING)
  8585. /* Return True if we should reply 304 Not Modified. */
  8586. static int
  8587. is_not_modified(const struct mg_connection *conn,
  8588. const struct mg_file_stat *filestat)
  8589. {
  8590. char etag[64];
  8591. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8592. const char *inm = mg_get_header(conn, "If-None-Match");
  8593. construct_etag(etag, sizeof(etag), filestat);
  8594. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8595. || ((ims != NULL)
  8596. && (filestat->last_modified <= parse_date_string(ims)));
  8597. }
  8598. static void
  8599. handle_not_modified_static_file_request(struct mg_connection *conn,
  8600. struct mg_file *filep)
  8601. {
  8602. char lm[64], etag[64];
  8603. if ((conn == NULL) || (filep == NULL)) {
  8604. return;
  8605. }
  8606. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8607. construct_etag(etag, sizeof(etag), &filep->stat);
  8608. /* Create 304 "not modified" response */
  8609. mg_response_header_start(conn, 304);
  8610. send_static_cache_header(conn);
  8611. send_additional_header(conn);
  8612. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8613. mg_response_header_add(conn, "Etag", etag, -1);
  8614. /* Send all headers */
  8615. mg_response_header_send(conn);
  8616. }
  8617. #endif
  8618. #if !defined(NO_FILESYSTEMS)
  8619. void
  8620. mg_send_file(struct mg_connection *conn, const char *path)
  8621. {
  8622. mg_send_mime_file2(conn, path, NULL, NULL);
  8623. }
  8624. void
  8625. mg_send_mime_file(struct mg_connection *conn,
  8626. const char *path,
  8627. const char *mime_type)
  8628. {
  8629. mg_send_mime_file2(conn, path, mime_type, NULL);
  8630. }
  8631. void
  8632. mg_send_mime_file2(struct mg_connection *conn,
  8633. const char *path,
  8634. const char *mime_type,
  8635. const char *additional_headers)
  8636. {
  8637. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8638. if (!conn) {
  8639. /* No conn */
  8640. return;
  8641. }
  8642. if (mg_stat(conn, path, &file.stat)) {
  8643. #if !defined(NO_CACHING)
  8644. if (is_not_modified(conn, &file.stat)) {
  8645. /* Send 304 "Not Modified" - this must not send any body data */
  8646. handle_not_modified_static_file_request(conn, &file);
  8647. } else
  8648. #endif /* NO_CACHING */
  8649. if (file.stat.is_directory) {
  8650. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8651. "yes")) {
  8652. handle_directory_request(conn, path);
  8653. } else {
  8654. mg_send_http_error(conn,
  8655. 403,
  8656. "%s",
  8657. "Error: Directory listing denied");
  8658. }
  8659. } else {
  8660. handle_static_file_request(
  8661. conn, path, &file, mime_type, additional_headers);
  8662. }
  8663. } else {
  8664. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8665. }
  8666. }
  8667. /* For a given PUT path, create all intermediate subdirectories.
  8668. * Return 0 if the path itself is a directory.
  8669. * Return 1 if the path leads to a file.
  8670. * Return -1 for if the path is too long.
  8671. * Return -2 if path can not be created.
  8672. */
  8673. static int
  8674. put_dir(struct mg_connection *conn, const char *path)
  8675. {
  8676. char buf[UTF8_PATH_MAX];
  8677. const char *s, *p;
  8678. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8679. size_t len;
  8680. int res = 1;
  8681. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8682. len = (size_t)(p - path);
  8683. if (len >= sizeof(buf)) {
  8684. /* path too long */
  8685. res = -1;
  8686. break;
  8687. }
  8688. memcpy(buf, path, len);
  8689. buf[len] = '\0';
  8690. /* Try to create intermediate directory */
  8691. DEBUG_TRACE("mkdir(%s)", buf);
  8692. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8693. /* path does not exixt and can not be created */
  8694. res = -2;
  8695. break;
  8696. }
  8697. /* Is path itself a directory? */
  8698. if (p[1] == '\0') {
  8699. res = 0;
  8700. }
  8701. }
  8702. return res;
  8703. }
  8704. static void
  8705. remove_bad_file(const struct mg_connection *conn, const char *path)
  8706. {
  8707. int r = mg_remove(conn, path);
  8708. if (r != 0) {
  8709. mg_cry_internal(conn,
  8710. "%s: Cannot remove invalid file %s",
  8711. __func__,
  8712. path);
  8713. }
  8714. }
  8715. long long
  8716. mg_store_body(struct mg_connection *conn, const char *path)
  8717. {
  8718. char buf[MG_BUF_LEN];
  8719. long long len = 0;
  8720. int ret, n;
  8721. struct mg_file fi;
  8722. if (conn->consumed_content != 0) {
  8723. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8724. return -11;
  8725. }
  8726. ret = put_dir(conn, path);
  8727. if (ret < 0) {
  8728. /* -1 for path too long,
  8729. * -2 for path can not be created. */
  8730. return ret;
  8731. }
  8732. if (ret != 1) {
  8733. /* Return 0 means, path itself is a directory. */
  8734. return 0;
  8735. }
  8736. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8737. return -12;
  8738. }
  8739. ret = mg_read(conn, buf, sizeof(buf));
  8740. while (ret > 0) {
  8741. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8742. if (n != ret) {
  8743. (void)mg_fclose(
  8744. &fi.access); /* File is bad and will be removed anyway. */
  8745. remove_bad_file(conn, path);
  8746. return -13;
  8747. }
  8748. len += ret;
  8749. ret = mg_read(conn, buf, sizeof(buf));
  8750. }
  8751. /* File is open for writing. If fclose fails, there was probably an
  8752. * error flushing the buffer to disk, so the file on disk might be
  8753. * broken. Delete it and return an error to the caller. */
  8754. if (mg_fclose(&fi.access) != 0) {
  8755. remove_bad_file(conn, path);
  8756. return -14;
  8757. }
  8758. return len;
  8759. }
  8760. #endif /* NO_FILESYSTEMS */
  8761. /* Parse a buffer:
  8762. * Forward the string pointer till the end of a word, then
  8763. * terminate it and forward till the begin of the next word.
  8764. */
  8765. static int
  8766. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8767. {
  8768. /* Forward until a space is found - use isgraph here */
  8769. /* See http://www.cplusplus.com/reference/cctype/ */
  8770. while (isgraph((unsigned char)**ppw)) {
  8771. (*ppw)++;
  8772. }
  8773. /* Check end of word */
  8774. if (eol) {
  8775. /* must be a end of line */
  8776. if ((**ppw != '\r') && (**ppw != '\n')) {
  8777. return -1;
  8778. }
  8779. } else {
  8780. /* must be a end of a word, but not a line */
  8781. if (**ppw != ' ') {
  8782. return -1;
  8783. }
  8784. }
  8785. /* Terminate and forward to the next word */
  8786. do {
  8787. **ppw = 0;
  8788. (*ppw)++;
  8789. } while (isspace((unsigned char)**ppw));
  8790. /* Check after term */
  8791. if (!eol) {
  8792. /* if it's not the end of line, there must be a next word */
  8793. if (!isgraph((unsigned char)**ppw)) {
  8794. return -1;
  8795. }
  8796. }
  8797. /* ok */
  8798. return 1;
  8799. }
  8800. /* Parse HTTP headers from the given buffer, advance buf pointer
  8801. * to the point where parsing stopped.
  8802. * All parameters must be valid pointers (not NULL).
  8803. * Return <0 on error. */
  8804. static int
  8805. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8806. {
  8807. int i;
  8808. int num_headers = 0;
  8809. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8810. char *dp = *buf;
  8811. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8812. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8813. dp++;
  8814. }
  8815. if (dp == *buf) {
  8816. /* End of headers reached. */
  8817. break;
  8818. }
  8819. /* Drop all spaces after header name before : */
  8820. while (*dp == ' ') {
  8821. *dp = 0;
  8822. dp++;
  8823. }
  8824. if (*dp != ':') {
  8825. /* This is not a valid field. */
  8826. return -1;
  8827. }
  8828. /* End of header key (*dp == ':') */
  8829. /* Truncate here and set the key name */
  8830. *dp = 0;
  8831. hdr[i].name = *buf;
  8832. /* Skip all spaces */
  8833. do {
  8834. dp++;
  8835. } while ((*dp == ' ') || (*dp == '\t'));
  8836. /* The rest of the line is the value */
  8837. hdr[i].value = dp;
  8838. /* Find end of line */
  8839. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8840. dp++;
  8841. };
  8842. /* eliminate \r */
  8843. if (*dp == '\r') {
  8844. *dp = 0;
  8845. dp++;
  8846. if (*dp != '\n') {
  8847. /* This is not a valid line. */
  8848. return -1;
  8849. }
  8850. }
  8851. /* here *dp is either 0 or '\n' */
  8852. /* in any case, we have a new header */
  8853. num_headers = i + 1;
  8854. if (*dp) {
  8855. *dp = 0;
  8856. dp++;
  8857. *buf = dp;
  8858. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8859. /* This is the end of the header */
  8860. break;
  8861. }
  8862. } else {
  8863. *buf = dp;
  8864. break;
  8865. }
  8866. }
  8867. return num_headers;
  8868. }
  8869. struct mg_http_method_info {
  8870. const char *name;
  8871. int request_has_body;
  8872. int response_has_body;
  8873. int is_safe;
  8874. int is_idempotent;
  8875. int is_cacheable;
  8876. };
  8877. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8878. static const struct mg_http_method_info http_methods[] = {
  8879. /* HTTP (RFC 2616) */
  8880. {"GET", 0, 1, 1, 1, 1},
  8881. {"POST", 1, 1, 0, 0, 0},
  8882. {"PUT", 1, 0, 0, 1, 0},
  8883. {"DELETE", 0, 0, 0, 1, 0},
  8884. {"HEAD", 0, 0, 1, 1, 1},
  8885. {"OPTIONS", 0, 0, 1, 1, 0},
  8886. {"CONNECT", 1, 1, 0, 0, 0},
  8887. /* TRACE method (RFC 2616) is not supported for security reasons */
  8888. /* PATCH method (RFC 5789) */
  8889. {"PATCH", 1, 0, 0, 0, 0},
  8890. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8891. /* WEBDAV (RFC 2518) */
  8892. {"PROPFIND", 0, 1, 1, 1, 0},
  8893. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8894. * Some PROPFIND results MAY be cached, with care,
  8895. * as there is no cache validation mechanism for
  8896. * most properties. This method is both safe and
  8897. * idempotent (see Section 9.1 of [RFC2616]). */
  8898. {"MKCOL", 0, 0, 0, 1, 0},
  8899. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8900. * When MKCOL is invoked without a request body,
  8901. * the newly created collection SHOULD have no
  8902. * members. A MKCOL request message may contain
  8903. * a message body. The precise behavior of a MKCOL
  8904. * request when the body is present is undefined,
  8905. * ... ==> We do not support MKCOL with body data.
  8906. * This method is idempotent, but not safe (see
  8907. * Section 9.1 of [RFC2616]). Responses to this
  8908. * method MUST NOT be cached. */
  8909. /* Methods for write access to files on WEBDAV (RFC 2518) */
  8910. {"LOCK", 1, 1, 0, 0, 0},
  8911. {"UNLOCK", 1, 0, 0, 0, 0},
  8912. {"PROPPATCH", 1, 1, 0, 0, 0},
  8913. /* Unsupported WEBDAV Methods: */
  8914. /* COPY, MOVE (RFC 2518) */
  8915. /* + 11 methods from RFC 3253 */
  8916. /* ORDERPATCH (RFC 3648) */
  8917. /* ACL (RFC 3744) */
  8918. /* SEARCH (RFC 5323) */
  8919. /* + MicroSoft extensions
  8920. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8921. /* REPORT method (RFC 3253) */
  8922. {"REPORT", 1, 1, 1, 1, 1},
  8923. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8924. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8925. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8926. * to be useful for REST in case a "GET request with body" is
  8927. * required. */
  8928. {NULL, 0, 0, 0, 0, 0}
  8929. /* end of list */
  8930. };
  8931. static const struct mg_http_method_info *
  8932. get_http_method_info(const char *method)
  8933. {
  8934. /* Check if the method is known to the server. The list of all known
  8935. * HTTP methods can be found here at
  8936. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8937. */
  8938. const struct mg_http_method_info *m = http_methods;
  8939. while (m->name) {
  8940. if (!strcmp(m->name, method)) {
  8941. return m;
  8942. }
  8943. m++;
  8944. }
  8945. return NULL;
  8946. }
  8947. static int
  8948. is_valid_http_method(const char *method)
  8949. {
  8950. return (get_http_method_info(method) != NULL);
  8951. }
  8952. /* Parse HTTP request, fill in mg_request_info structure.
  8953. * This function modifies the buffer by NUL-terminating
  8954. * HTTP request components, header names and header values.
  8955. * Parameters:
  8956. * buf (in/out): pointer to the HTTP header to parse and split
  8957. * len (in): length of HTTP header buffer
  8958. * re (out): parsed header as mg_request_info
  8959. * buf and ri must be valid pointers (not NULL), len>0.
  8960. * Returns <0 on error. */
  8961. static int
  8962. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8963. {
  8964. int request_length;
  8965. int init_skip = 0;
  8966. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8967. * remote_port */
  8968. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8969. NULL;
  8970. ri->num_headers = 0;
  8971. /* RFC says that all initial whitespaces should be ingored */
  8972. /* This included all leading \r and \n (isspace) */
  8973. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8974. while ((len > 0) && isspace((unsigned char)*buf)) {
  8975. buf++;
  8976. len--;
  8977. init_skip++;
  8978. }
  8979. if (len == 0) {
  8980. /* Incomplete request */
  8981. return 0;
  8982. }
  8983. /* Control characters are not allowed, including zero */
  8984. if (iscntrl((unsigned char)*buf)) {
  8985. return -1;
  8986. }
  8987. /* Find end of HTTP header */
  8988. request_length = get_http_header_len(buf, len);
  8989. if (request_length <= 0) {
  8990. return request_length;
  8991. }
  8992. buf[request_length - 1] = '\0';
  8993. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8994. return -1;
  8995. }
  8996. /* The first word has to be the HTTP method */
  8997. ri->request_method = buf;
  8998. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8999. return -1;
  9000. }
  9001. /* Check for a valid http method */
  9002. if (!is_valid_http_method(ri->request_method)) {
  9003. return -1;
  9004. }
  9005. /* The second word is the URI */
  9006. ri->request_uri = buf;
  9007. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9008. return -1;
  9009. }
  9010. /* Next would be the HTTP version */
  9011. ri->http_version = buf;
  9012. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9013. return -1;
  9014. }
  9015. /* Check for a valid HTTP version key */
  9016. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9017. /* Invalid request */
  9018. return -1;
  9019. }
  9020. ri->http_version += 5;
  9021. /* Parse all HTTP headers */
  9022. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9023. if (ri->num_headers < 0) {
  9024. /* Error while parsing headers */
  9025. return -1;
  9026. }
  9027. return request_length + init_skip;
  9028. }
  9029. static int
  9030. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9031. {
  9032. int response_length;
  9033. int init_skip = 0;
  9034. char *tmp, *tmp2;
  9035. long l;
  9036. /* Initialize elements. */
  9037. ri->http_version = ri->status_text = NULL;
  9038. ri->num_headers = ri->status_code = 0;
  9039. /* RFC says that all initial whitespaces should be ingored */
  9040. /* This included all leading \r and \n (isspace) */
  9041. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9042. while ((len > 0) && isspace((unsigned char)*buf)) {
  9043. buf++;
  9044. len--;
  9045. init_skip++;
  9046. }
  9047. if (len == 0) {
  9048. /* Incomplete request */
  9049. return 0;
  9050. }
  9051. /* Control characters are not allowed, including zero */
  9052. if (iscntrl((unsigned char)*buf)) {
  9053. return -1;
  9054. }
  9055. /* Find end of HTTP header */
  9056. response_length = get_http_header_len(buf, len);
  9057. if (response_length <= 0) {
  9058. return response_length;
  9059. }
  9060. buf[response_length - 1] = '\0';
  9061. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9062. return -1;
  9063. }
  9064. /* The first word is the HTTP version */
  9065. /* Check for a valid HTTP version key */
  9066. if (strncmp(buf, "HTTP/", 5) != 0) {
  9067. /* Invalid request */
  9068. return -1;
  9069. }
  9070. buf += 5;
  9071. if (!isgraph((unsigned char)buf[0])) {
  9072. /* Invalid request */
  9073. return -1;
  9074. }
  9075. ri->http_version = buf;
  9076. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9077. return -1;
  9078. }
  9079. /* The second word is the status as a number */
  9080. tmp = buf;
  9081. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9082. return -1;
  9083. }
  9084. l = strtol(tmp, &tmp2, 10);
  9085. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9086. /* Everything else but a 3 digit code is invalid */
  9087. return -1;
  9088. }
  9089. ri->status_code = (int)l;
  9090. /* The rest of the line is the status text */
  9091. ri->status_text = buf;
  9092. /* Find end of status text */
  9093. /* isgraph or isspace = isprint */
  9094. while (isprint((unsigned char)*buf)) {
  9095. buf++;
  9096. }
  9097. if ((*buf != '\r') && (*buf != '\n')) {
  9098. return -1;
  9099. }
  9100. /* Terminate string and forward buf to next line */
  9101. do {
  9102. *buf = 0;
  9103. buf++;
  9104. } while (isspace((unsigned char)*buf));
  9105. /* Parse all HTTP headers */
  9106. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9107. if (ri->num_headers < 0) {
  9108. /* Error while parsing headers */
  9109. return -1;
  9110. }
  9111. return response_length + init_skip;
  9112. }
  9113. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9114. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9115. * buffer (which marks the end of HTTP request). Buffer buf may already
  9116. * have some data. The length of the data is stored in nread.
  9117. * Upon every read operation, increase nread by the number of bytes read. */
  9118. static int
  9119. read_message(FILE *fp,
  9120. struct mg_connection *conn,
  9121. char *buf,
  9122. int bufsiz,
  9123. int *nread)
  9124. {
  9125. int request_len, n = 0;
  9126. struct timespec last_action_time;
  9127. double request_timeout;
  9128. if (!conn) {
  9129. return 0;
  9130. }
  9131. memset(&last_action_time, 0, sizeof(last_action_time));
  9132. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9133. /* value of request_timeout is in seconds, config in milliseconds */
  9134. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9135. } else {
  9136. request_timeout =
  9137. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9138. }
  9139. if (conn->handled_requests > 0) {
  9140. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9141. request_timeout =
  9142. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9143. }
  9144. }
  9145. request_len = get_http_header_len(buf, *nread);
  9146. while (request_len == 0) {
  9147. /* Full request not yet received */
  9148. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9149. /* Server is to be stopped. */
  9150. return -1;
  9151. }
  9152. if (*nread >= bufsiz) {
  9153. /* Request too long */
  9154. return -2;
  9155. }
  9156. n = pull_inner(
  9157. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9158. if (n == -2) {
  9159. /* Receive error */
  9160. return -1;
  9161. }
  9162. /* update clock after every read request */
  9163. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9164. if (n > 0) {
  9165. *nread += n;
  9166. request_len = get_http_header_len(buf, *nread);
  9167. }
  9168. if ((request_len == 0) && (request_timeout >= 0)) {
  9169. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9170. > request_timeout) {
  9171. /* Timeout */
  9172. return -1;
  9173. }
  9174. }
  9175. }
  9176. return request_len;
  9177. }
  9178. #if !defined(NO_CGI) || !defined(NO_FILES)
  9179. static int
  9180. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9181. {
  9182. const char *expect;
  9183. char buf[MG_BUF_LEN];
  9184. int success = 0;
  9185. if (!conn) {
  9186. return 0;
  9187. }
  9188. expect = mg_get_header(conn, "Expect");
  9189. DEBUG_ASSERT(fp != NULL);
  9190. if (!fp) {
  9191. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9192. return 0;
  9193. }
  9194. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9195. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9196. */
  9197. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9198. } else {
  9199. if (expect != NULL) {
  9200. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9201. conn->status_code = 100;
  9202. } else {
  9203. conn->status_code = 200;
  9204. }
  9205. DEBUG_ASSERT(conn->consumed_content == 0);
  9206. if (conn->consumed_content != 0) {
  9207. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9208. return 0;
  9209. }
  9210. for (;;) {
  9211. int nread = mg_read(conn, buf, sizeof(buf));
  9212. if (nread <= 0) {
  9213. success = (nread == 0);
  9214. break;
  9215. }
  9216. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9217. break;
  9218. }
  9219. }
  9220. /* Each error code path in this function must send an error */
  9221. if (!success) {
  9222. /* NOTE: Maybe some data has already been sent. */
  9223. /* TODO (low): If some data has been sent, a correct error
  9224. * reply can no longer be sent, so just close the connection */
  9225. mg_send_http_error(conn, 500, "%s", "");
  9226. }
  9227. }
  9228. return success;
  9229. }
  9230. #endif
  9231. #if defined(USE_TIMERS)
  9232. #define TIMER_API static
  9233. #include "timer.inl"
  9234. #endif /* USE_TIMERS */
  9235. #if !defined(NO_CGI)
  9236. /* This structure helps to create an environment for the spawned CGI
  9237. * program.
  9238. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9239. * last element must be NULL.
  9240. * However, on Windows there is a requirement that all these
  9241. * VARIABLE=VALUE\0
  9242. * strings must reside in a contiguous buffer. The end of the buffer is
  9243. * marked by two '\0' characters.
  9244. * We satisfy both worlds: we create an envp array (which is vars), all
  9245. * entries are actually pointers inside buf. */
  9246. struct cgi_environment {
  9247. struct mg_connection *conn;
  9248. /* Data block */
  9249. char *buf; /* Environment buffer */
  9250. size_t buflen; /* Space available in buf */
  9251. size_t bufused; /* Space taken in buf */
  9252. /* Index block */
  9253. char **var; /* char **envp */
  9254. size_t varlen; /* Number of variables available in var */
  9255. size_t varused; /* Number of variables stored in var */
  9256. };
  9257. static void addenv(struct cgi_environment *env,
  9258. PRINTF_FORMAT_STRING(const char *fmt),
  9259. ...) PRINTF_ARGS(2, 3);
  9260. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9261. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9262. static void
  9263. addenv(struct cgi_environment *env, const char *fmt, ...)
  9264. {
  9265. size_t i, n, space;
  9266. int truncated = 0;
  9267. char *added;
  9268. va_list ap;
  9269. if ((env->varlen - env->varused) < 2) {
  9270. mg_cry_internal(env->conn,
  9271. "%s: Cannot register CGI variable [%s]",
  9272. __func__,
  9273. fmt);
  9274. return;
  9275. }
  9276. /* Calculate how much space is left in the buffer */
  9277. space = (env->buflen - env->bufused);
  9278. do {
  9279. /* Space for "\0\0" is always needed. */
  9280. if (space <= 2) {
  9281. /* Allocate new buffer */
  9282. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9283. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9284. if (!added) {
  9285. /* Out of memory */
  9286. mg_cry_internal(
  9287. env->conn,
  9288. "%s: Cannot allocate memory for CGI variable [%s]",
  9289. __func__,
  9290. fmt);
  9291. return;
  9292. }
  9293. /* Retarget pointers */
  9294. env->buf = added;
  9295. env->buflen = n;
  9296. for (i = 0, n = 0; i < env->varused; i++) {
  9297. env->var[i] = added + n;
  9298. n += strlen(added + n) + 1;
  9299. }
  9300. space = (env->buflen - env->bufused);
  9301. }
  9302. /* Make a pointer to the free space int the buffer */
  9303. added = env->buf + env->bufused;
  9304. /* Copy VARIABLE=VALUE\0 string into the free space */
  9305. va_start(ap, fmt);
  9306. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9307. va_end(ap);
  9308. /* Do not add truncated strings to the environment */
  9309. if (truncated) {
  9310. /* Reallocate the buffer */
  9311. space = 0;
  9312. }
  9313. } while (truncated);
  9314. /* Calculate number of bytes added to the environment */
  9315. n = strlen(added) + 1;
  9316. env->bufused += n;
  9317. /* Append a pointer to the added string into the envp array */
  9318. env->var[env->varused] = added;
  9319. env->varused++;
  9320. }
  9321. /* Return 0 on success, non-zero if an error occurs. */
  9322. static int
  9323. prepare_cgi_environment(struct mg_connection *conn,
  9324. const char *prog,
  9325. struct cgi_environment *env,
  9326. unsigned char cgi_config_idx)
  9327. {
  9328. const char *s;
  9329. struct vec var_vec;
  9330. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9331. int i, truncated, uri_len;
  9332. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9333. return -1;
  9334. }
  9335. env->conn = conn;
  9336. env->buflen = CGI_ENVIRONMENT_SIZE;
  9337. env->bufused = 0;
  9338. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9339. if (env->buf == NULL) {
  9340. mg_cry_internal(conn,
  9341. "%s: Not enough memory for environmental buffer",
  9342. __func__);
  9343. return -1;
  9344. }
  9345. env->varlen = MAX_CGI_ENVIR_VARS;
  9346. env->varused = 0;
  9347. env->var =
  9348. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9349. if (env->var == NULL) {
  9350. mg_cry_internal(conn,
  9351. "%s: Not enough memory for environmental variables",
  9352. __func__);
  9353. mg_free(env->buf);
  9354. return -1;
  9355. }
  9356. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9357. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9358. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9359. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9360. /* Prepare the environment block */
  9361. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9362. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9363. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9364. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9365. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9366. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9367. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9368. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9369. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9370. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9371. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9372. /* SCRIPT_NAME */
  9373. uri_len = (int)strlen(conn->request_info.local_uri);
  9374. if (conn->path_info == NULL) {
  9375. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9376. /* URI: /path_to_script/script.cgi */
  9377. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9378. } else {
  9379. /* URI: /path_to_script/ ... using index.cgi */
  9380. const char *index_file = strrchr(prog, '/');
  9381. if (index_file) {
  9382. addenv(env,
  9383. "SCRIPT_NAME=%s%s",
  9384. conn->request_info.local_uri,
  9385. index_file + 1);
  9386. }
  9387. }
  9388. } else {
  9389. /* URI: /path_to_script/script.cgi/path_info */
  9390. addenv(env,
  9391. "SCRIPT_NAME=%.*s",
  9392. uri_len - (int)strlen(conn->path_info),
  9393. conn->request_info.local_uri);
  9394. }
  9395. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9396. if (conn->path_info == NULL) {
  9397. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9398. } else {
  9399. addenv(env,
  9400. "PATH_TRANSLATED=%s%s",
  9401. conn->dom_ctx->config[DOCUMENT_ROOT],
  9402. conn->path_info);
  9403. }
  9404. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9405. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9406. addenv(env, "CONTENT_TYPE=%s", s);
  9407. }
  9408. if (conn->request_info.query_string != NULL) {
  9409. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9410. }
  9411. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9412. addenv(env, "CONTENT_LENGTH=%s", s);
  9413. }
  9414. if ((s = getenv("PATH")) != NULL) {
  9415. addenv(env, "PATH=%s", s);
  9416. }
  9417. if (conn->path_info != NULL) {
  9418. addenv(env, "PATH_INFO=%s", conn->path_info);
  9419. }
  9420. if (conn->status_code > 0) {
  9421. /* CGI error handler should show the status code */
  9422. addenv(env, "STATUS=%d", conn->status_code);
  9423. }
  9424. #if defined(_WIN32)
  9425. if ((s = getenv("COMSPEC")) != NULL) {
  9426. addenv(env, "COMSPEC=%s", s);
  9427. }
  9428. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9429. addenv(env, "SYSTEMROOT=%s", s);
  9430. }
  9431. if ((s = getenv("SystemDrive")) != NULL) {
  9432. addenv(env, "SystemDrive=%s", s);
  9433. }
  9434. if ((s = getenv("ProgramFiles")) != NULL) {
  9435. addenv(env, "ProgramFiles=%s", s);
  9436. }
  9437. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9438. addenv(env, "ProgramFiles(x86)=%s", s);
  9439. }
  9440. #else
  9441. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9442. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9443. }
  9444. #endif /* _WIN32 */
  9445. if ((s = getenv("PERLLIB")) != NULL) {
  9446. addenv(env, "PERLLIB=%s", s);
  9447. }
  9448. if (conn->request_info.remote_user != NULL) {
  9449. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9450. addenv(env, "%s", "AUTH_TYPE=Digest");
  9451. }
  9452. /* Add all headers as HTTP_* variables */
  9453. for (i = 0; i < conn->request_info.num_headers; i++) {
  9454. (void)mg_snprintf(conn,
  9455. &truncated,
  9456. http_var_name,
  9457. sizeof(http_var_name),
  9458. "HTTP_%s",
  9459. conn->request_info.http_headers[i].name);
  9460. if (truncated) {
  9461. mg_cry_internal(conn,
  9462. "%s: HTTP header variable too long [%s]",
  9463. __func__,
  9464. conn->request_info.http_headers[i].name);
  9465. continue;
  9466. }
  9467. /* Convert variable name into uppercase, and change - to _ */
  9468. for (p = http_var_name; *p != '\0'; p++) {
  9469. if (*p == '-') {
  9470. *p = '_';
  9471. }
  9472. *p = (char)toupper((unsigned char)*p);
  9473. }
  9474. addenv(env,
  9475. "%s=%s",
  9476. http_var_name,
  9477. conn->request_info.http_headers[i].value);
  9478. }
  9479. /* Add user-specified variables */
  9480. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9481. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9482. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9483. }
  9484. env->var[env->varused] = NULL;
  9485. env->buf[env->bufused] = '\0';
  9486. return 0;
  9487. }
  9488. /* Data for CGI process control: PID and number of references */
  9489. struct process_control_data {
  9490. pid_t pid;
  9491. ptrdiff_t references;
  9492. };
  9493. static int
  9494. abort_cgi_process(void *data)
  9495. {
  9496. /* Waitpid checks for child status and won't work for a pid that does
  9497. * not identify a child of the current process. Thus, if the pid is
  9498. * reused, we will not affect a different process. */
  9499. struct process_control_data *proc = (struct process_control_data *)data;
  9500. int status = 0;
  9501. ptrdiff_t refs;
  9502. pid_t ret_pid;
  9503. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9504. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9505. /* Stop child process */
  9506. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9507. kill(proc->pid, SIGABRT);
  9508. /* Wait until process is terminated (don't leave zombies) */
  9509. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9510. ;
  9511. } else {
  9512. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9513. }
  9514. /* Dec reference counter */
  9515. refs = mg_atomic_dec(&proc->references);
  9516. if (refs == 0) {
  9517. /* no more references - free data */
  9518. mg_free(data);
  9519. }
  9520. return 0;
  9521. }
  9522. /* Local (static) function assumes all arguments are valid. */
  9523. static void
  9524. handle_cgi_request(struct mg_connection *conn,
  9525. const char *prog,
  9526. unsigned char cgi_config_idx)
  9527. {
  9528. char *buf;
  9529. size_t buflen;
  9530. int headers_len, data_len, i, truncated;
  9531. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9532. const char *status, *status_text, *connection_state;
  9533. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9534. struct mg_request_info ri;
  9535. struct cgi_environment blk;
  9536. FILE *in = NULL, *out = NULL, *err = NULL;
  9537. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9538. pid_t pid = (pid_t)-1;
  9539. struct process_control_data *proc = NULL;
  9540. #if defined(USE_TIMERS)
  9541. double cgi_timeout;
  9542. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9543. /* Get timeout in seconds */
  9544. cgi_timeout =
  9545. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9546. } else {
  9547. cgi_timeout =
  9548. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9549. }
  9550. #endif
  9551. buf = NULL;
  9552. buflen = conn->phys_ctx->max_request_size;
  9553. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9554. if (i != 0) {
  9555. blk.buf = NULL;
  9556. blk.var = NULL;
  9557. goto done;
  9558. }
  9559. /* CGI must be executed in its own directory. 'dir' must point to the
  9560. * directory containing executable program, 'p' must point to the
  9561. * executable program name relative to 'dir'. */
  9562. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9563. if (truncated) {
  9564. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9565. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9566. goto done;
  9567. }
  9568. if ((p = strrchr(dir, '/')) != NULL) {
  9569. *p++ = '\0';
  9570. } else {
  9571. dir[0] = '.';
  9572. dir[1] = '\0';
  9573. p = (char *)prog;
  9574. }
  9575. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9576. status = strerror(ERRNO);
  9577. mg_cry_internal(
  9578. conn,
  9579. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9580. prog,
  9581. status);
  9582. mg_send_http_error(conn,
  9583. 500,
  9584. "Error: Cannot create CGI pipe: %s",
  9585. status);
  9586. goto done;
  9587. }
  9588. proc = (struct process_control_data *)
  9589. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9590. if (proc == NULL) {
  9591. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9592. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9593. goto done;
  9594. }
  9595. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9596. pid = spawn_process(
  9597. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9598. if (pid == (pid_t)-1) {
  9599. status = strerror(ERRNO);
  9600. mg_cry_internal(
  9601. conn,
  9602. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9603. prog,
  9604. status);
  9605. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9606. mg_free(proc);
  9607. proc = NULL;
  9608. goto done;
  9609. }
  9610. /* Store data in shared process_control_data */
  9611. proc->pid = pid;
  9612. proc->references = 1;
  9613. #if defined(USE_TIMERS)
  9614. if (cgi_timeout > 0.0) {
  9615. proc->references = 2;
  9616. // Start a timer for CGI
  9617. timer_add(conn->phys_ctx,
  9618. cgi_timeout /* in seconds */,
  9619. 0.0,
  9620. 1,
  9621. abort_cgi_process,
  9622. (void *)proc,
  9623. NULL);
  9624. }
  9625. #endif
  9626. /* Parent closes only one side of the pipes.
  9627. * If we don't mark them as closed, close() attempt before
  9628. * return from this function throws an exception on Windows.
  9629. * Windows does not like when closed descriptor is closed again. */
  9630. (void)close(fdin[0]);
  9631. (void)close(fdout[1]);
  9632. (void)close(fderr[1]);
  9633. fdin[0] = fdout[1] = fderr[1] = -1;
  9634. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9635. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9636. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9637. status = strerror(ERRNO);
  9638. mg_cry_internal(conn,
  9639. "Error: CGI program \"%s\": Can not open fd: %s",
  9640. prog,
  9641. status);
  9642. mg_send_http_error(conn,
  9643. 500,
  9644. "Error: CGI can not open fd\nfdopen: %s",
  9645. status);
  9646. goto done;
  9647. }
  9648. setbuf(in, NULL);
  9649. setbuf(out, NULL);
  9650. setbuf(err, NULL);
  9651. fout.access.fp = out;
  9652. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9653. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9654. conn->content_len);
  9655. /* This is a POST/PUT request, or another request with body data. */
  9656. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9657. /* Error sending the body data */
  9658. mg_cry_internal(
  9659. conn,
  9660. "Error: CGI program \"%s\": Forward body data failed",
  9661. prog);
  9662. goto done;
  9663. }
  9664. }
  9665. /* Close so child gets an EOF. */
  9666. fclose(in);
  9667. in = NULL;
  9668. fdin[1] = -1;
  9669. /* Now read CGI reply into a buffer. We need to set correct
  9670. * status code, thus we need to see all HTTP headers first.
  9671. * Do not send anything back to client, until we buffer in all
  9672. * HTTP headers. */
  9673. data_len = 0;
  9674. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9675. if (buf == NULL) {
  9676. mg_send_http_error(conn,
  9677. 500,
  9678. "Error: Not enough memory for CGI buffer (%u bytes)",
  9679. (unsigned int)buflen);
  9680. mg_cry_internal(
  9681. conn,
  9682. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9683. "bytes)",
  9684. prog,
  9685. (unsigned int)buflen);
  9686. goto done;
  9687. }
  9688. DEBUG_TRACE("CGI: %s", "wait for response");
  9689. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9690. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9691. if (headers_len <= 0) {
  9692. /* Could not parse the CGI response. Check if some error message on
  9693. * stderr. */
  9694. i = pull_all(err, conn, buf, (int)buflen);
  9695. if (i > 0) {
  9696. /* CGI program explicitly sent an error */
  9697. /* Write the error message to the internal log */
  9698. mg_cry_internal(conn,
  9699. "Error: CGI program \"%s\" sent error "
  9700. "message: [%.*s]",
  9701. prog,
  9702. i,
  9703. buf);
  9704. /* Don't send the error message back to the client */
  9705. mg_send_http_error(conn,
  9706. 500,
  9707. "Error: CGI program \"%s\" failed.",
  9708. prog);
  9709. } else {
  9710. /* CGI program did not explicitly send an error, but a broken
  9711. * respon header */
  9712. mg_cry_internal(conn,
  9713. "Error: CGI program sent malformed or too big "
  9714. "(>%u bytes) HTTP headers: [%.*s]",
  9715. (unsigned)buflen,
  9716. data_len,
  9717. buf);
  9718. mg_send_http_error(conn,
  9719. 500,
  9720. "Error: CGI program sent malformed or too big "
  9721. "(>%u bytes) HTTP headers: [%.*s]",
  9722. (unsigned)buflen,
  9723. data_len,
  9724. buf);
  9725. }
  9726. /* in both cases, abort processing CGI */
  9727. goto done;
  9728. }
  9729. pbuf = buf;
  9730. buf[headers_len - 1] = '\0';
  9731. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9732. /* Make up and send the status line */
  9733. status_text = "OK";
  9734. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9735. != NULL) {
  9736. conn->status_code = atoi(status);
  9737. status_text = status;
  9738. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9739. status_text++;
  9740. }
  9741. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9742. != NULL) {
  9743. conn->status_code = 307;
  9744. } else {
  9745. conn->status_code = 200;
  9746. }
  9747. connection_state =
  9748. get_header(ri.http_headers, ri.num_headers, "Connection");
  9749. if (!header_has_option(connection_state, "keep-alive")) {
  9750. conn->must_close = 1;
  9751. }
  9752. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9753. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9754. /* Send headers */
  9755. for (i = 0; i < ri.num_headers; i++) {
  9756. DEBUG_TRACE("CGI header: %s: %s",
  9757. ri.http_headers[i].name,
  9758. ri.http_headers[i].value);
  9759. mg_printf(conn,
  9760. "%s: %s\r\n",
  9761. ri.http_headers[i].name,
  9762. ri.http_headers[i].value);
  9763. }
  9764. mg_write(conn, "\r\n", 2);
  9765. /* Send chunk of data that may have been read after the headers */
  9766. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9767. /* Read the rest of CGI output and send to the client */
  9768. DEBUG_TRACE("CGI: %s", "forward all data");
  9769. send_file_data(conn, &fout, 0, INT64_MAX);
  9770. DEBUG_TRACE("CGI: %s", "all data sent");
  9771. done:
  9772. mg_free(blk.var);
  9773. mg_free(blk.buf);
  9774. if (pid != (pid_t)-1) {
  9775. abort_cgi_process((void *)proc);
  9776. }
  9777. if (fdin[0] != -1) {
  9778. close(fdin[0]);
  9779. }
  9780. if (fdout[1] != -1) {
  9781. close(fdout[1]);
  9782. }
  9783. if (fderr[1] != -1) {
  9784. close(fderr[1]);
  9785. }
  9786. if (in != NULL) {
  9787. fclose(in);
  9788. } else if (fdin[1] != -1) {
  9789. close(fdin[1]);
  9790. }
  9791. if (out != NULL) {
  9792. fclose(out);
  9793. } else if (fdout[0] != -1) {
  9794. close(fdout[0]);
  9795. }
  9796. if (err != NULL) {
  9797. fclose(err);
  9798. } else if (fderr[0] != -1) {
  9799. close(fderr[0]);
  9800. }
  9801. mg_free(buf);
  9802. }
  9803. #endif /* !NO_CGI */
  9804. #if !defined(NO_FILES)
  9805. static void
  9806. mkcol(struct mg_connection *conn, const char *path)
  9807. {
  9808. int rc, body_len;
  9809. struct de de;
  9810. if (conn == NULL) {
  9811. return;
  9812. }
  9813. /* TODO (mid): Check the mg_send_http_error situations in this function
  9814. */
  9815. memset(&de.file, 0, sizeof(de.file));
  9816. if (!mg_stat(conn, path, &de.file)) {
  9817. mg_cry_internal(conn,
  9818. "%s: mg_stat(%s) failed: %s",
  9819. __func__,
  9820. path,
  9821. strerror(ERRNO));
  9822. }
  9823. if (de.file.last_modified) {
  9824. /* TODO (mid): This check does not seem to make any sense ! */
  9825. /* TODO (mid): Add a webdav unit test first, before changing
  9826. * anything here. */
  9827. mg_send_http_error(
  9828. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9829. return;
  9830. }
  9831. body_len = conn->data_len - conn->request_len;
  9832. if (body_len > 0) {
  9833. mg_send_http_error(
  9834. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9835. return;
  9836. }
  9837. rc = mg_mkdir(conn, path, 0755);
  9838. if (rc == 0) {
  9839. /* Create 201 "Created" response */
  9840. mg_response_header_start(conn, 201);
  9841. send_static_cache_header(conn);
  9842. send_additional_header(conn);
  9843. mg_response_header_add(conn, "Content-Length", "0", -1);
  9844. /* Send all headers - there is no body */
  9845. mg_response_header_send(conn);
  9846. } else {
  9847. if (errno == EEXIST) {
  9848. mg_send_http_error(
  9849. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9850. } else if (errno == EACCES) {
  9851. mg_send_http_error(
  9852. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9853. } else if (errno == ENOENT) {
  9854. mg_send_http_error(
  9855. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9856. } else {
  9857. mg_send_http_error(
  9858. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9859. }
  9860. }
  9861. }
  9862. static void
  9863. put_file(struct mg_connection *conn, const char *path)
  9864. {
  9865. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9866. const char *range;
  9867. int64_t r1, r2;
  9868. int rc;
  9869. if (conn == NULL) {
  9870. return;
  9871. }
  9872. if (mg_stat(conn, path, &file.stat)) {
  9873. /* File already exists */
  9874. conn->status_code = 200;
  9875. if (file.stat.is_directory) {
  9876. /* This is an already existing directory,
  9877. * so there is nothing to do for the server. */
  9878. rc = 0;
  9879. } else {
  9880. /* File exists and is not a directory. */
  9881. /* Can it be replaced? */
  9882. /* Check if the server may write this file */
  9883. if (access(path, W_OK) == 0) {
  9884. /* Access granted */
  9885. rc = 1;
  9886. } else {
  9887. mg_send_http_error(
  9888. conn,
  9889. 403,
  9890. "Error: Put not possible\nReplacing %s is not allowed",
  9891. path);
  9892. return;
  9893. }
  9894. }
  9895. } else {
  9896. /* File should be created */
  9897. conn->status_code = 201;
  9898. rc = put_dir(conn, path);
  9899. }
  9900. if (rc == 0) {
  9901. /* put_dir returns 0 if path is a directory */
  9902. /* Create response */
  9903. mg_response_header_start(conn, conn->status_code);
  9904. send_no_cache_header(conn);
  9905. send_additional_header(conn);
  9906. mg_response_header_add(conn, "Content-Length", "0", -1);
  9907. /* Send all headers - there is no body */
  9908. mg_response_header_send(conn);
  9909. /* Request to create a directory has been fulfilled successfully.
  9910. * No need to put a file. */
  9911. return;
  9912. }
  9913. if (rc == -1) {
  9914. /* put_dir returns -1 if the path is too long */
  9915. mg_send_http_error(conn,
  9916. 414,
  9917. "Error: Path too long\nput_dir(%s): %s",
  9918. path,
  9919. strerror(ERRNO));
  9920. return;
  9921. }
  9922. if (rc == -2) {
  9923. /* put_dir returns -2 if the directory can not be created */
  9924. mg_send_http_error(conn,
  9925. 500,
  9926. "Error: Can not create directory\nput_dir(%s): %s",
  9927. path,
  9928. strerror(ERRNO));
  9929. return;
  9930. }
  9931. /* A file should be created or overwritten. */
  9932. /* Currently CivetWeb does not nead read+write access. */
  9933. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9934. || file.access.fp == NULL) {
  9935. (void)mg_fclose(&file.access);
  9936. mg_send_http_error(conn,
  9937. 500,
  9938. "Error: Can not create file\nfopen(%s): %s",
  9939. path,
  9940. strerror(ERRNO));
  9941. return;
  9942. }
  9943. fclose_on_exec(&file.access, conn);
  9944. range = mg_get_header(conn, "Content-Range");
  9945. r1 = r2 = 0;
  9946. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9947. conn->status_code = 206; /* Partial content */
  9948. fseeko(file.access.fp, r1, SEEK_SET);
  9949. }
  9950. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9951. /* forward_body_data failed.
  9952. * The error code has already been sent to the client,
  9953. * and conn->status_code is already set. */
  9954. (void)mg_fclose(&file.access);
  9955. return;
  9956. }
  9957. if (mg_fclose(&file.access) != 0) {
  9958. /* fclose failed. This might have different reasons, but a likely
  9959. * one is "no space on disk", http 507. */
  9960. conn->status_code = 507;
  9961. }
  9962. /* Create response (status_code has been set before) */
  9963. mg_response_header_start(conn, conn->status_code);
  9964. send_no_cache_header(conn);
  9965. send_additional_header(conn);
  9966. mg_response_header_add(conn, "Content-Length", "0", -1);
  9967. /* Send all headers - there is no body */
  9968. mg_response_header_send(conn);
  9969. }
  9970. static void
  9971. delete_file(struct mg_connection *conn, const char *path)
  9972. {
  9973. struct de de;
  9974. memset(&de.file, 0, sizeof(de.file));
  9975. if (!mg_stat(conn, path, &de.file)) {
  9976. /* mg_stat returns 0 if the file does not exist */
  9977. mg_send_http_error(conn,
  9978. 404,
  9979. "Error: Cannot delete file\nFile %s not found",
  9980. path);
  9981. return;
  9982. }
  9983. if (de.file.is_directory) {
  9984. if (remove_directory(conn, path)) {
  9985. /* Delete is successful: Return 204 without content. */
  9986. mg_send_http_error(conn, 204, "%s", "");
  9987. } else {
  9988. /* Delete is not successful: Return 500 (Server error). */
  9989. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9990. }
  9991. return;
  9992. }
  9993. /* This is an existing file (not a directory).
  9994. * Check if write permission is granted. */
  9995. if (access(path, W_OK) != 0) {
  9996. /* File is read only */
  9997. mg_send_http_error(
  9998. conn,
  9999. 403,
  10000. "Error: Delete not possible\nDeleting %s is not allowed",
  10001. path);
  10002. return;
  10003. }
  10004. /* Try to delete it. */
  10005. if (mg_remove(conn, path) == 0) {
  10006. /* Delete was successful: Return 204 without content. */
  10007. mg_response_header_start(conn, 204);
  10008. send_no_cache_header(conn);
  10009. send_additional_header(conn);
  10010. mg_response_header_add(conn, "Content-Length", "0", -1);
  10011. mg_response_header_send(conn);
  10012. } else {
  10013. /* Delete not successful (file locked). */
  10014. mg_send_http_error(conn,
  10015. 423,
  10016. "Error: Cannot delete file\nremove(%s): %s",
  10017. path,
  10018. strerror(ERRNO));
  10019. }
  10020. }
  10021. #endif /* !NO_FILES */
  10022. #if !defined(NO_FILESYSTEMS)
  10023. static void
  10024. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10025. static void
  10026. do_ssi_include(struct mg_connection *conn,
  10027. const char *ssi,
  10028. char *tag,
  10029. int include_level)
  10030. {
  10031. char file_name[MG_BUF_LEN], path[512], *p;
  10032. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10033. size_t len;
  10034. int truncated = 0;
  10035. if (conn == NULL) {
  10036. return;
  10037. }
  10038. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10039. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10040. * always < MG_BUF_LEN. */
  10041. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10042. /* File name is relative to the webserver root */
  10043. file_name[511] = 0;
  10044. (void)mg_snprintf(conn,
  10045. &truncated,
  10046. path,
  10047. sizeof(path),
  10048. "%s/%s",
  10049. conn->dom_ctx->config[DOCUMENT_ROOT],
  10050. file_name);
  10051. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10052. /* File name is relative to the webserver working directory
  10053. * or it is absolute system path */
  10054. file_name[511] = 0;
  10055. (void)
  10056. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10057. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10058. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10059. /* File name is relative to the currect document */
  10060. file_name[511] = 0;
  10061. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10062. if (!truncated) {
  10063. if ((p = strrchr(path, '/')) != NULL) {
  10064. p[1] = '\0';
  10065. }
  10066. len = strlen(path);
  10067. (void)mg_snprintf(conn,
  10068. &truncated,
  10069. path + len,
  10070. sizeof(path) - len,
  10071. "%s",
  10072. file_name);
  10073. }
  10074. } else {
  10075. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10076. return;
  10077. }
  10078. if (truncated) {
  10079. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10080. return;
  10081. }
  10082. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10083. mg_cry_internal(conn,
  10084. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10085. tag,
  10086. path,
  10087. strerror(ERRNO));
  10088. } else {
  10089. fclose_on_exec(&file.access, conn);
  10090. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10091. > 0) {
  10092. send_ssi_file(conn, path, &file, include_level + 1);
  10093. } else {
  10094. send_file_data(conn, &file, 0, INT64_MAX);
  10095. }
  10096. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10097. }
  10098. }
  10099. #if !defined(NO_POPEN)
  10100. static void
  10101. do_ssi_exec(struct mg_connection *conn, char *tag)
  10102. {
  10103. char cmd[1024] = "";
  10104. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10105. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10106. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10107. } else {
  10108. cmd[1023] = 0;
  10109. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10110. mg_cry_internal(conn,
  10111. "Cannot SSI #exec: [%s]: %s",
  10112. cmd,
  10113. strerror(ERRNO));
  10114. } else {
  10115. send_file_data(conn, &file, 0, INT64_MAX);
  10116. pclose(file.access.fp);
  10117. }
  10118. }
  10119. }
  10120. #endif /* !NO_POPEN */
  10121. static int
  10122. mg_fgetc(struct mg_file *filep)
  10123. {
  10124. if (filep == NULL) {
  10125. return EOF;
  10126. }
  10127. if (filep->access.fp != NULL) {
  10128. return fgetc(filep->access.fp);
  10129. } else {
  10130. return EOF;
  10131. }
  10132. }
  10133. static void
  10134. send_ssi_file(struct mg_connection *conn,
  10135. const char *path,
  10136. struct mg_file *filep,
  10137. int include_level)
  10138. {
  10139. char buf[MG_BUF_LEN];
  10140. int ch, len, in_tag, in_ssi_tag;
  10141. if (include_level > 10) {
  10142. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10143. return;
  10144. }
  10145. in_tag = in_ssi_tag = len = 0;
  10146. /* Read file, byte by byte, and look for SSI include tags */
  10147. while ((ch = mg_fgetc(filep)) != EOF) {
  10148. if (in_tag) {
  10149. /* We are in a tag, either SSI tag or html tag */
  10150. if (ch == '>') {
  10151. /* Tag is closing */
  10152. buf[len++] = '>';
  10153. if (in_ssi_tag) {
  10154. /* Handle SSI tag */
  10155. buf[len] = 0;
  10156. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10157. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10158. #if !defined(NO_POPEN)
  10159. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10160. do_ssi_exec(conn, buf + 9);
  10161. #endif /* !NO_POPEN */
  10162. } else {
  10163. mg_cry_internal(conn,
  10164. "%s: unknown SSI "
  10165. "command: \"%s\"",
  10166. path,
  10167. buf);
  10168. }
  10169. len = 0;
  10170. in_ssi_tag = in_tag = 0;
  10171. } else {
  10172. /* Not an SSI tag */
  10173. /* Flush buffer */
  10174. (void)mg_write(conn, buf, (size_t)len);
  10175. len = 0;
  10176. in_tag = 0;
  10177. }
  10178. } else {
  10179. /* Tag is still open */
  10180. buf[len++] = (char)(ch & 0xff);
  10181. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10182. /* All SSI tags start with <!--# */
  10183. in_ssi_tag = 1;
  10184. }
  10185. if ((len + 2) > (int)sizeof(buf)) {
  10186. /* Tag to long for buffer */
  10187. mg_cry_internal(conn, "%s: tag is too large", path);
  10188. return;
  10189. }
  10190. }
  10191. } else {
  10192. /* We are not in a tag yet. */
  10193. if (ch == '<') {
  10194. /* Tag is opening */
  10195. in_tag = 1;
  10196. if (len > 0) {
  10197. /* Flush current buffer.
  10198. * Buffer is filled with "len" bytes. */
  10199. (void)mg_write(conn, buf, (size_t)len);
  10200. }
  10201. /* Store the < */
  10202. len = 1;
  10203. buf[0] = '<';
  10204. } else {
  10205. /* No Tag */
  10206. /* Add data to buffer */
  10207. buf[len++] = (char)(ch & 0xff);
  10208. /* Flush if buffer is full */
  10209. if (len == (int)sizeof(buf)) {
  10210. mg_write(conn, buf, (size_t)len);
  10211. len = 0;
  10212. }
  10213. }
  10214. }
  10215. }
  10216. /* Send the rest of buffered data */
  10217. if (len > 0) {
  10218. mg_write(conn, buf, (size_t)len);
  10219. }
  10220. }
  10221. static void
  10222. handle_ssi_file_request(struct mg_connection *conn,
  10223. const char *path,
  10224. struct mg_file *filep)
  10225. {
  10226. char date[64];
  10227. time_t curtime = time(NULL);
  10228. const char *cors_orig_cfg;
  10229. const char *cors1, *cors2;
  10230. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10231. return;
  10232. }
  10233. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10234. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10235. /* Cross-origin resource sharing (CORS). */
  10236. cors1 = "Access-Control-Allow-Origin";
  10237. cors2 = cors_orig_cfg;
  10238. } else {
  10239. cors1 = cors2 = "";
  10240. }
  10241. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10242. /* File exists (precondition for calling this function),
  10243. * but can not be opened by the server. */
  10244. mg_send_http_error(conn,
  10245. 500,
  10246. "Error: Cannot read file\nfopen(%s): %s",
  10247. path,
  10248. strerror(ERRNO));
  10249. } else {
  10250. /* Set "must_close" for HTTP/1.x, since we do not know the
  10251. * content length */
  10252. conn->must_close = 1;
  10253. gmt_time_string(date, sizeof(date), &curtime);
  10254. fclose_on_exec(&filep->access, conn);
  10255. /* 200 OK response */
  10256. mg_response_header_start(conn, 200);
  10257. send_no_cache_header(conn);
  10258. send_additional_header(conn);
  10259. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10260. if (cors1[0]) {
  10261. mg_response_header_add(conn, cors1, cors2, -1);
  10262. }
  10263. mg_response_header_send(conn);
  10264. /* Header sent, now send body */
  10265. send_ssi_file(conn, path, filep, 0);
  10266. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10267. }
  10268. }
  10269. #endif /* NO_FILESYSTEMS */
  10270. #if !defined(NO_FILES)
  10271. static void
  10272. send_options(struct mg_connection *conn)
  10273. {
  10274. if (!conn) {
  10275. return;
  10276. }
  10277. /* We do not set a "Cache-Control" header here, but leave the default.
  10278. * Since browsers do not send an OPTIONS request, we can not test the
  10279. * effect anyway. */
  10280. mg_response_header_start(conn, 200);
  10281. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10282. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10283. /* Use the same as before */
  10284. mg_response_header_add(
  10285. conn,
  10286. "Allow",
  10287. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10288. -1);
  10289. mg_response_header_add(conn, "DAV", "1", -1);
  10290. } else {
  10291. /* TODO: Check this later for HTTP/2 */
  10292. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10293. }
  10294. send_additional_header(conn);
  10295. mg_response_header_send(conn);
  10296. }
  10297. /* Writes PROPFIND properties for a collection element */
  10298. static int
  10299. print_props(struct mg_connection *conn,
  10300. const char *uri,
  10301. const char *name,
  10302. struct mg_file_stat *filep)
  10303. {
  10304. size_t href_size, i, j;
  10305. int len;
  10306. char *href, mtime[64];
  10307. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10308. return 0;
  10309. }
  10310. /* Estimate worst case size for encoding */
  10311. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10312. href = (char *)mg_malloc(href_size);
  10313. if (href == NULL) {
  10314. return 0;
  10315. }
  10316. len = mg_url_encode(uri, href, href_size);
  10317. if (len >= 0) {
  10318. /* Append an extra string */
  10319. mg_url_encode(name, href + len, href_size - (size_t)len);
  10320. }
  10321. /* Directory separator should be preserved. */
  10322. for (i = j = 0; href[i]; j++) {
  10323. if (!strncmp(href + i, "%2f", 3)) {
  10324. href[j] = '/';
  10325. i += 3;
  10326. } else {
  10327. href[j] = href[i++];
  10328. }
  10329. }
  10330. href[j] = '\0';
  10331. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10332. mg_printf(conn,
  10333. "<d:response>"
  10334. "<d:href>%s</d:href>"
  10335. "<d:propstat>"
  10336. "<d:prop>"
  10337. "<d:resourcetype>%s</d:resourcetype>"
  10338. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10339. "<d:getlastmodified>%s</d:getlastmodified>"
  10340. "</d:prop>"
  10341. "<d:status>HTTP/1.1 200 OK</d:status>"
  10342. "</d:propstat>"
  10343. "</d:response>\n",
  10344. href,
  10345. filep->is_directory ? "<d:collection/>" : "",
  10346. filep->size,
  10347. mtime);
  10348. mg_free(href);
  10349. return 1;
  10350. }
  10351. static int
  10352. print_dav_dir_entry(struct de *de, void *data)
  10353. {
  10354. struct mg_connection *conn = (struct mg_connection *)data;
  10355. if (!de || !conn
  10356. || !print_props(
  10357. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10358. /* stop scan */
  10359. return 1;
  10360. }
  10361. return 0;
  10362. }
  10363. static void
  10364. handle_propfind(struct mg_connection *conn,
  10365. const char *path,
  10366. struct mg_file_stat *filep)
  10367. {
  10368. const char *depth = mg_get_header(conn, "Depth");
  10369. char date[64];
  10370. time_t curtime = time(NULL);
  10371. gmt_time_string(date, sizeof(date), &curtime);
  10372. if (!conn || !path || !filep || !conn->dom_ctx) {
  10373. return;
  10374. }
  10375. conn->must_close = 1;
  10376. /* return 207 "Multi-Status" */
  10377. mg_response_header_start(conn, 207);
  10378. send_static_cache_header(conn);
  10379. send_additional_header(conn);
  10380. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10381. mg_response_header_send(conn);
  10382. /* Content */
  10383. mg_printf(conn,
  10384. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10385. "<d:multistatus xmlns:d='DAV:'>\n");
  10386. /* Print properties for the requested resource itself */
  10387. print_props(conn, conn->request_info.local_uri, "", filep);
  10388. /* If it is a directory, print directory entries too if Depth is not 0
  10389. */
  10390. if (filep->is_directory
  10391. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10392. "yes")
  10393. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10394. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10395. }
  10396. mg_printf(conn, "%s\n", "</d:multistatus>");
  10397. }
  10398. #endif
  10399. void
  10400. mg_lock_connection(struct mg_connection *conn)
  10401. {
  10402. if (conn) {
  10403. (void)pthread_mutex_lock(&conn->mutex);
  10404. }
  10405. }
  10406. void
  10407. mg_unlock_connection(struct mg_connection *conn)
  10408. {
  10409. if (conn) {
  10410. (void)pthread_mutex_unlock(&conn->mutex);
  10411. }
  10412. }
  10413. void
  10414. mg_lock_context(struct mg_context *ctx)
  10415. {
  10416. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10417. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10418. }
  10419. }
  10420. void
  10421. mg_unlock_context(struct mg_context *ctx)
  10422. {
  10423. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10424. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10425. }
  10426. }
  10427. #if defined(USE_LUA)
  10428. #include "mod_lua.inl"
  10429. #endif /* USE_LUA */
  10430. #if defined(USE_DUKTAPE)
  10431. #include "mod_duktape.inl"
  10432. #endif /* USE_DUKTAPE */
  10433. #if defined(USE_WEBSOCKET)
  10434. #if !defined(NO_SSL_DL)
  10435. #define SHA_API static
  10436. #include "sha1.inl"
  10437. #endif
  10438. static int
  10439. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10440. {
  10441. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10442. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10443. SHA_CTX sha_ctx;
  10444. int truncated;
  10445. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10446. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10447. if (truncated) {
  10448. conn->must_close = 1;
  10449. return 0;
  10450. }
  10451. DEBUG_TRACE("%s", "Send websocket handshake");
  10452. SHA1_Init(&sha_ctx);
  10453. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10454. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10455. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10456. mg_printf(conn,
  10457. "HTTP/1.1 101 Switching Protocols\r\n"
  10458. "Upgrade: websocket\r\n"
  10459. "Connection: Upgrade\r\n"
  10460. "Sec-WebSocket-Accept: %s\r\n",
  10461. b64_sha);
  10462. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10463. // Send negotiated compression extension parameters
  10464. websocket_deflate_response(conn);
  10465. #endif
  10466. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10467. mg_printf(conn,
  10468. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10469. conn->request_info.acceptedWebSocketSubprotocol);
  10470. } else {
  10471. mg_printf(conn, "%s", "\r\n");
  10472. }
  10473. return 1;
  10474. }
  10475. #if !defined(MG_MAX_UNANSWERED_PING)
  10476. /* Configuration of the maximum number of websocket PINGs that might
  10477. * stay unanswered before the connection is considered broken.
  10478. * Note: The name of this define may still change (until it is
  10479. * defined as a compile parameter in a documentation).
  10480. */
  10481. #define MG_MAX_UNANSWERED_PING (5)
  10482. #endif
  10483. static void
  10484. read_websocket(struct mg_connection *conn,
  10485. mg_websocket_data_handler ws_data_handler,
  10486. void *callback_data)
  10487. {
  10488. /* Pointer to the beginning of the portion of the incoming websocket
  10489. * message queue.
  10490. * The original websocket upgrade request is never removed, so the queue
  10491. * begins after it. */
  10492. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10493. int n, error, exit_by_callback;
  10494. int ret;
  10495. /* body_len is the length of the entire queue in bytes
  10496. * len is the length of the current message
  10497. * data_len is the length of the current message's data payload
  10498. * header_len is the length of the current message's header */
  10499. size_t i, len, mask_len = 0, header_len, body_len;
  10500. uint64_t data_len = 0;
  10501. /* "The masking key is a 32-bit value chosen at random by the client."
  10502. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10503. */
  10504. unsigned char mask[4];
  10505. /* data points to the place where the message is stored when passed to
  10506. * the websocket_data callback. This is either mem on the stack, or a
  10507. * dynamically allocated buffer if it is too large. */
  10508. unsigned char mem[4096];
  10509. unsigned char mop; /* mask flag and opcode */
  10510. /* Variables used for connection monitoring */
  10511. double timeout = -1.0;
  10512. int enable_ping_pong = 0;
  10513. int ping_count = 0;
  10514. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10515. enable_ping_pong =
  10516. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10517. "yes");
  10518. }
  10519. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10520. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10521. }
  10522. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10523. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10524. }
  10525. if (timeout <= 0.0) {
  10526. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10527. }
  10528. /* Enter data processing loop */
  10529. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10530. conn->request_info.remote_addr,
  10531. conn->request_info.remote_port);
  10532. conn->in_websocket_handling = 1;
  10533. mg_set_thread_name("wsock");
  10534. /* Loop continuously, reading messages from the socket, invoking the
  10535. * callback, and waiting repeatedly until an error occurs. */
  10536. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10537. && (!conn->must_close)) {
  10538. header_len = 0;
  10539. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10540. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10541. len = buf[1] & 127;
  10542. mask_len = (buf[1] & 128) ? 4 : 0;
  10543. if ((len < 126) && (body_len >= mask_len)) {
  10544. /* inline 7-bit length field */
  10545. data_len = len;
  10546. header_len = 2 + mask_len;
  10547. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10548. /* 16-bit length field */
  10549. header_len = 4 + mask_len;
  10550. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10551. } else if (body_len >= (10 + mask_len)) {
  10552. /* 64-bit length field */
  10553. uint32_t l1, l2;
  10554. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10555. memcpy(&l2, &buf[6], 4);
  10556. header_len = 10 + mask_len;
  10557. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10558. if (data_len > (uint64_t)0x7FFF0000ul) {
  10559. /* no can do */
  10560. mg_cry_internal(
  10561. conn,
  10562. "%s",
  10563. "websocket out of memory; closing connection");
  10564. break;
  10565. }
  10566. }
  10567. }
  10568. if ((header_len > 0) && (body_len >= header_len)) {
  10569. /* Allocate space to hold websocket payload */
  10570. unsigned char *data = mem;
  10571. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10572. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10573. conn->phys_ctx);
  10574. if (data == NULL) {
  10575. /* Allocation failed, exit the loop and then close the
  10576. * connection */
  10577. mg_cry_internal(
  10578. conn,
  10579. "%s",
  10580. "websocket out of memory; closing connection");
  10581. break;
  10582. }
  10583. }
  10584. /* Copy the mask before we shift the queue and destroy it */
  10585. if (mask_len > 0) {
  10586. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10587. } else {
  10588. memset(mask, 0, sizeof(mask));
  10589. }
  10590. /* Read frame payload from the first message in the queue into
  10591. * data and advance the queue by moving the memory in place. */
  10592. DEBUG_ASSERT(body_len >= header_len);
  10593. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10594. mop = buf[0]; /* current mask and opcode */
  10595. /* Overflow case */
  10596. len = body_len - header_len;
  10597. memcpy(data, buf + header_len, len);
  10598. error = 0;
  10599. while ((uint64_t)len < data_len) {
  10600. n = pull_inner(NULL,
  10601. conn,
  10602. (char *)(data + len),
  10603. (int)(data_len - len),
  10604. timeout);
  10605. if (n <= -2) {
  10606. error = 1;
  10607. break;
  10608. } else if (n > 0) {
  10609. len += (size_t)n;
  10610. } else {
  10611. /* Timeout: should retry */
  10612. /* TODO: retry condition */
  10613. }
  10614. }
  10615. if (error) {
  10616. mg_cry_internal(
  10617. conn,
  10618. "%s",
  10619. "Websocket pull failed; closing connection");
  10620. if (data != mem) {
  10621. mg_free(data);
  10622. }
  10623. break;
  10624. }
  10625. conn->data_len = conn->request_len;
  10626. } else {
  10627. mop = buf[0]; /* current mask and opcode, overwritten by
  10628. * memmove() */
  10629. /* Length of the message being read at the front of the
  10630. * queue. Cast to 31 bit is OK, since we limited
  10631. * data_len before. */
  10632. len = (size_t)data_len + header_len;
  10633. /* Copy the data payload into the data pointer for the
  10634. * callback. Cast to 31 bit is OK, since we
  10635. * limited data_len */
  10636. memcpy(data, buf + header_len, (size_t)data_len);
  10637. /* Move the queue forward len bytes */
  10638. memmove(buf, buf + len, body_len - len);
  10639. /* Mark the queue as advanced */
  10640. conn->data_len -= (int)len;
  10641. }
  10642. /* Apply mask if necessary */
  10643. if (mask_len > 0) {
  10644. for (i = 0; i < (size_t)data_len; i++) {
  10645. data[i] ^= mask[i & 3];
  10646. }
  10647. }
  10648. exit_by_callback = 0;
  10649. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10650. /* filter PONG messages */
  10651. DEBUG_TRACE("PONG from %s:%u",
  10652. conn->request_info.remote_addr,
  10653. conn->request_info.remote_port);
  10654. /* No unanwered PINGs left */
  10655. ping_count = 0;
  10656. } else if (enable_ping_pong
  10657. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10658. /* reply PING messages */
  10659. DEBUG_TRACE("Reply PING from %s:%u",
  10660. conn->request_info.remote_addr,
  10661. conn->request_info.remote_port);
  10662. ret = mg_websocket_write(conn,
  10663. MG_WEBSOCKET_OPCODE_PONG,
  10664. (char *)data,
  10665. (size_t)data_len);
  10666. if (ret <= 0) {
  10667. /* Error: send failed */
  10668. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10669. break;
  10670. }
  10671. } else {
  10672. /* Exit the loop if callback signals to exit (server side),
  10673. * or "connection close" opcode received (client side). */
  10674. if (ws_data_handler != NULL) {
  10675. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10676. if (mop & 0x40) {
  10677. /* Inflate the data received if bit RSV1 is set. */
  10678. if (!conn->websocket_deflate_initialized) {
  10679. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10680. exit_by_callback = 1;
  10681. }
  10682. if (!exit_by_callback) {
  10683. size_t inflate_buf_size_old = 0;
  10684. size_t inflate_buf_size =
  10685. data_len
  10686. * 4; // Initial guess of the inflated message
  10687. // size. We double the memory when needed.
  10688. Bytef *inflated;
  10689. Bytef *new_mem;
  10690. conn->websocket_inflate_state.avail_in =
  10691. (uInt)(data_len + 4);
  10692. conn->websocket_inflate_state.next_in = data;
  10693. // Add trailing 0x00 0x00 0xff 0xff bytes
  10694. data[data_len] = '\x00';
  10695. data[data_len + 1] = '\x00';
  10696. data[data_len + 2] = '\xff';
  10697. data[data_len + 3] = '\xff';
  10698. do {
  10699. if (inflate_buf_size_old == 0) {
  10700. new_mem = mg_calloc(inflate_buf_size,
  10701. sizeof(Bytef));
  10702. } else {
  10703. inflate_buf_size *= 2;
  10704. new_mem =
  10705. mg_realloc(inflated, inflate_buf_size);
  10706. }
  10707. if (new_mem == NULL) {
  10708. mg_cry_internal(
  10709. conn,
  10710. "Out of memory: Cannot allocate "
  10711. "inflate buffer of %lu bytes",
  10712. (unsigned long)inflate_buf_size);
  10713. exit_by_callback = 1;
  10714. break;
  10715. }
  10716. inflated = new_mem;
  10717. conn->websocket_inflate_state.avail_out =
  10718. (uInt)(inflate_buf_size
  10719. - inflate_buf_size_old);
  10720. conn->websocket_inflate_state.next_out =
  10721. inflated + inflate_buf_size_old;
  10722. ret = inflate(&conn->websocket_inflate_state,
  10723. Z_SYNC_FLUSH);
  10724. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  10725. || ret == Z_MEM_ERROR) {
  10726. mg_cry_internal(
  10727. conn,
  10728. "ZLIB inflate error: %i %s",
  10729. ret,
  10730. (conn->websocket_inflate_state.msg
  10731. ? conn->websocket_inflate_state.msg
  10732. : "<no error message>"));
  10733. exit_by_callback = 1;
  10734. break;
  10735. }
  10736. inflate_buf_size_old = inflate_buf_size;
  10737. } while (conn->websocket_inflate_state.avail_out
  10738. == 0);
  10739. inflate_buf_size -=
  10740. conn->websocket_inflate_state.avail_out;
  10741. if (!ws_data_handler(conn,
  10742. mop,
  10743. (char *)inflated,
  10744. inflate_buf_size,
  10745. callback_data)) {
  10746. exit_by_callback = 1;
  10747. }
  10748. mg_free(inflated);
  10749. }
  10750. } else
  10751. #endif
  10752. if (!ws_data_handler(conn,
  10753. mop,
  10754. (char *)data,
  10755. (size_t)data_len,
  10756. callback_data)) {
  10757. exit_by_callback = 1;
  10758. }
  10759. }
  10760. }
  10761. /* It a buffer has been allocated, free it again */
  10762. if (data != mem) {
  10763. mg_free(data);
  10764. }
  10765. if (exit_by_callback) {
  10766. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10767. conn->request_info.remote_addr,
  10768. conn->request_info.remote_port);
  10769. break;
  10770. }
  10771. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10772. /* Opcode == 8, connection close */
  10773. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10774. conn->request_info.remote_addr,
  10775. conn->request_info.remote_port);
  10776. break;
  10777. }
  10778. /* Not breaking the loop, process next websocket frame. */
  10779. } else {
  10780. /* Read from the socket into the next available location in the
  10781. * message queue. */
  10782. n = pull_inner(NULL,
  10783. conn,
  10784. conn->buf + conn->data_len,
  10785. conn->buf_size - conn->data_len,
  10786. timeout);
  10787. if (n <= -2) {
  10788. /* Error, no bytes read */
  10789. DEBUG_TRACE("PULL from %s:%u failed",
  10790. conn->request_info.remote_addr,
  10791. conn->request_info.remote_port);
  10792. break;
  10793. }
  10794. if (n > 0) {
  10795. conn->data_len += n;
  10796. /* Reset open PING count */
  10797. ping_count = 0;
  10798. } else {
  10799. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10800. && (!conn->must_close)) {
  10801. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10802. /* Stop sending PING */
  10803. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10804. "- closing connection",
  10805. ping_count,
  10806. conn->request_info.remote_addr,
  10807. conn->request_info.remote_port);
  10808. break;
  10809. }
  10810. if (enable_ping_pong) {
  10811. /* Send Websocket PING message */
  10812. DEBUG_TRACE("PING to %s:%u",
  10813. conn->request_info.remote_addr,
  10814. conn->request_info.remote_port);
  10815. ret = mg_websocket_write(conn,
  10816. MG_WEBSOCKET_OPCODE_PING,
  10817. NULL,
  10818. 0);
  10819. if (ret <= 0) {
  10820. /* Error: send failed */
  10821. DEBUG_TRACE("Send PING failed (%i)", ret);
  10822. break;
  10823. }
  10824. ping_count++;
  10825. }
  10826. }
  10827. /* Timeout: should retry */
  10828. /* TODO: get timeout def */
  10829. }
  10830. }
  10831. }
  10832. /* Leave data processing loop */
  10833. mg_set_thread_name("worker");
  10834. conn->in_websocket_handling = 0;
  10835. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10836. conn->request_info.remote_addr,
  10837. conn->request_info.remote_port);
  10838. }
  10839. static int
  10840. mg_websocket_write_exec(struct mg_connection *conn,
  10841. int opcode,
  10842. const char *data,
  10843. size_t dataLen,
  10844. uint32_t masking_key)
  10845. {
  10846. unsigned char header[14];
  10847. size_t headerLen;
  10848. int retval;
  10849. #if defined(GCC_DIAGNOSTIC)
  10850. /* Disable spurious conversion warning for GCC */
  10851. #pragma GCC diagnostic push
  10852. #pragma GCC diagnostic ignored "-Wconversion"
  10853. #endif
  10854. /* Note that POSIX/Winsock's send() is threadsafe
  10855. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10856. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10857. * push(), although that is only a problem if the packet is large or
  10858. * outgoing buffer is full). */
  10859. /* TODO: Check if this lock should be moved to user land.
  10860. * Currently the server sets this lock for websockets, but
  10861. * not for any other connection. It must be set for every
  10862. * conn read/written by more than one thread, no matter if
  10863. * it is a websocket or regular connection. */
  10864. (void)mg_lock_connection(conn);
  10865. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10866. size_t deflated_size = 0;
  10867. Bytef *deflated = 0;
  10868. // Deflate websocket messages over 100kb
  10869. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  10870. if (use_deflate) {
  10871. if (!conn->websocket_deflate_initialized) {
  10872. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10873. return 0;
  10874. }
  10875. // Deflating the message
  10876. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  10877. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  10878. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  10879. deflated_size = compressBound((uLong)dataLen);
  10880. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  10881. if (deflated == NULL) {
  10882. mg_cry_internal(
  10883. conn,
  10884. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  10885. (unsigned long)deflated_size);
  10886. mg_unlock_connection(conn);
  10887. return -1;
  10888. }
  10889. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  10890. conn->websocket_deflate_state.next_out = deflated;
  10891. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  10892. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  10893. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  10894. } else
  10895. #endif
  10896. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10897. #if defined(GCC_DIAGNOSTIC)
  10898. #pragma GCC diagnostic pop
  10899. #endif
  10900. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10901. if (dataLen < 126) {
  10902. /* inline 7-bit length field */
  10903. header[1] = (unsigned char)dataLen;
  10904. headerLen = 2;
  10905. } else if (dataLen <= 0xFFFF) {
  10906. /* 16-bit length field */
  10907. uint16_t len = htons((uint16_t)dataLen);
  10908. header[1] = 126;
  10909. memcpy(header + 2, &len, 2);
  10910. headerLen = 4;
  10911. } else {
  10912. /* 64-bit length field */
  10913. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10914. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10915. header[1] = 127;
  10916. memcpy(header + 2, &len1, 4);
  10917. memcpy(header + 6, &len2, 4);
  10918. headerLen = 10;
  10919. }
  10920. if (masking_key) {
  10921. /* add mask */
  10922. header[1] |= 0x80;
  10923. memcpy(header + headerLen, &masking_key, 4);
  10924. headerLen += 4;
  10925. }
  10926. retval = mg_write(conn, header, headerLen);
  10927. if (retval != (int)headerLen) {
  10928. /* Did not send complete header */
  10929. retval = -1;
  10930. } else {
  10931. if (dataLen > 0) {
  10932. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10933. if (use_deflate) {
  10934. retval = mg_write(conn, deflated, dataLen);
  10935. mg_free(deflated);
  10936. } else
  10937. #endif
  10938. retval = mg_write(conn, data, dataLen);
  10939. }
  10940. /* if dataLen == 0, the header length (2) is returned */
  10941. }
  10942. /* TODO: Remove this unlock as well, when lock is removed. */
  10943. mg_unlock_connection(conn);
  10944. return retval;
  10945. }
  10946. int
  10947. mg_websocket_write(struct mg_connection *conn,
  10948. int opcode,
  10949. const char *data,
  10950. size_t dataLen)
  10951. {
  10952. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10953. }
  10954. static void
  10955. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10956. {
  10957. size_t i = 0;
  10958. i = 0;
  10959. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10960. /* Convert in 32 bit words, if data is 4 byte aligned */
  10961. while (i < (in_len - 3)) {
  10962. *(uint32_t *)(void *)(out + i) =
  10963. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10964. i += 4;
  10965. }
  10966. }
  10967. if (i != in_len) {
  10968. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10969. while (i < in_len) {
  10970. *(uint8_t *)(void *)(out + i) =
  10971. *(uint8_t *)(void *)(in + i)
  10972. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10973. i++;
  10974. }
  10975. }
  10976. }
  10977. int
  10978. mg_websocket_client_write(struct mg_connection *conn,
  10979. int opcode,
  10980. const char *data,
  10981. size_t dataLen)
  10982. {
  10983. int retval = -1;
  10984. char *masked_data =
  10985. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10986. uint32_t masking_key = 0;
  10987. if (masked_data == NULL) {
  10988. /* Return -1 in an error case */
  10989. mg_cry_internal(conn,
  10990. "%s",
  10991. "Cannot allocate buffer for masked websocket response: "
  10992. "Out of memory");
  10993. return -1;
  10994. }
  10995. do {
  10996. /* Get a masking key - but not 0 */
  10997. masking_key = (uint32_t)get_random();
  10998. } while (masking_key == 0);
  10999. mask_data(data, dataLen, masking_key, masked_data);
  11000. retval = mg_websocket_write_exec(
  11001. conn, opcode, masked_data, dataLen, masking_key);
  11002. mg_free(masked_data);
  11003. return retval;
  11004. }
  11005. static void
  11006. handle_websocket_request(struct mg_connection *conn,
  11007. const char *path,
  11008. int is_callback_resource,
  11009. struct mg_websocket_subprotocols *subprotocols,
  11010. mg_websocket_connect_handler ws_connect_handler,
  11011. mg_websocket_ready_handler ws_ready_handler,
  11012. mg_websocket_data_handler ws_data_handler,
  11013. mg_websocket_close_handler ws_close_handler,
  11014. void *cbData)
  11015. {
  11016. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11017. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11018. ptrdiff_t lua_websock = 0;
  11019. #if !defined(USE_LUA)
  11020. (void)path;
  11021. #endif
  11022. /* Step 1: Check websocket protocol version. */
  11023. /* Step 1.1: Check Sec-WebSocket-Key. */
  11024. if (!websock_key) {
  11025. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11026. * requires a Sec-WebSocket-Key header.
  11027. */
  11028. /* It could be the hixie draft version
  11029. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11030. */
  11031. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11032. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11033. char key3[8];
  11034. if ((key1 != NULL) && (key2 != NULL)) {
  11035. /* This version uses 8 byte body data in a GET request */
  11036. conn->content_len = 8;
  11037. if (8 == mg_read(conn, key3, 8)) {
  11038. /* This is the hixie version */
  11039. mg_send_http_error(conn,
  11040. 426,
  11041. "%s",
  11042. "Protocol upgrade to RFC 6455 required");
  11043. return;
  11044. }
  11045. }
  11046. /* This is an unknown version */
  11047. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11048. return;
  11049. }
  11050. /* Step 1.2: Check websocket protocol version. */
  11051. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11052. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11053. /* Reject wrong versions */
  11054. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11055. return;
  11056. }
  11057. /* Step 1.3: Could check for "Host", but we do not really nead this
  11058. * value for anything, so just ignore it. */
  11059. /* Step 2: If a callback is responsible, call it. */
  11060. if (is_callback_resource) {
  11061. /* Step 2.1 check and select subprotocol */
  11062. const char *protocols[64]; // max 64 headers
  11063. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11064. "Sec-WebSocket-Protocol",
  11065. protocols,
  11066. 64);
  11067. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11068. int cnt = 0;
  11069. int idx;
  11070. unsigned long len;
  11071. const char *sep, *curSubProtocol,
  11072. *acceptedWebSocketSubprotocol = NULL;
  11073. /* look for matching subprotocol */
  11074. do {
  11075. const char *protocol = protocols[cnt];
  11076. do {
  11077. sep = strchr(protocol, ',');
  11078. curSubProtocol = protocol;
  11079. len = sep ? (unsigned long)(sep - protocol)
  11080. : (unsigned long)strlen(protocol);
  11081. while (sep && isspace((unsigned char)*++sep))
  11082. ; // ignore leading whitespaces
  11083. protocol = sep;
  11084. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11085. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11086. && (strncmp(curSubProtocol,
  11087. subprotocols->subprotocols[idx],
  11088. len)
  11089. == 0)) {
  11090. acceptedWebSocketSubprotocol =
  11091. subprotocols->subprotocols[idx];
  11092. break;
  11093. }
  11094. }
  11095. } while (sep && !acceptedWebSocketSubprotocol);
  11096. } while (++cnt < nbSubprotocolHeader
  11097. && !acceptedWebSocketSubprotocol);
  11098. conn->request_info.acceptedWebSocketSubprotocol =
  11099. acceptedWebSocketSubprotocol;
  11100. } else if (nbSubprotocolHeader > 0) {
  11101. /* keep legacy behavior */
  11102. const char *protocol = protocols[0];
  11103. /* The protocol is a comma separated list of names. */
  11104. /* The server must only return one value from this list. */
  11105. /* First check if it is a list or just a single value. */
  11106. const char *sep = strrchr(protocol, ',');
  11107. if (sep == NULL) {
  11108. /* Just a single protocol -> accept it. */
  11109. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11110. } else {
  11111. /* Multiple protocols -> accept the last one. */
  11112. /* This is just a quick fix if the client offers multiple
  11113. * protocols. The handler should have a list of accepted
  11114. * protocols on his own
  11115. * and use it to select one protocol among those the client
  11116. * has
  11117. * offered.
  11118. */
  11119. while (isspace((unsigned char)*++sep)) {
  11120. ; /* ignore leading whitespaces */
  11121. }
  11122. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11123. }
  11124. }
  11125. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11126. websocket_deflate_negotiate(conn);
  11127. #endif
  11128. if ((ws_connect_handler != NULL)
  11129. && (ws_connect_handler(conn, cbData) != 0)) {
  11130. /* C callback has returned non-zero, do not proceed with
  11131. * handshake.
  11132. */
  11133. /* Note that C callbacks are no longer called when Lua is
  11134. * responsible, so C can no longer filter callbacks for Lua. */
  11135. return;
  11136. }
  11137. }
  11138. #if defined(USE_LUA)
  11139. /* Step 3: No callback. Check if Lua is responsible. */
  11140. else {
  11141. /* Step 3.1: Check if Lua is responsible. */
  11142. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11143. lua_websock = match_prefix_strlen(
  11144. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11145. }
  11146. if (lua_websock) {
  11147. /* Step 3.2: Lua is responsible: call it. */
  11148. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11149. if (!conn->lua_websocket_state) {
  11150. /* Lua rejected the new client */
  11151. return;
  11152. }
  11153. }
  11154. }
  11155. #endif
  11156. /* Step 4: Check if there is a responsible websocket handler. */
  11157. if (!is_callback_resource && !lua_websock) {
  11158. /* There is no callback, and Lua is not responsible either. */
  11159. /* Reply with a 404 Not Found. We are still at a standard
  11160. * HTTP request here, before the websocket handshake, so
  11161. * we can still send standard HTTP error replies. */
  11162. mg_send_http_error(conn, 404, "%s", "Not found");
  11163. return;
  11164. }
  11165. /* Step 5: The websocket connection has been accepted */
  11166. if (!send_websocket_handshake(conn, websock_key)) {
  11167. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11168. return;
  11169. }
  11170. /* Step 6: Call the ready handler */
  11171. if (is_callback_resource) {
  11172. if (ws_ready_handler != NULL) {
  11173. ws_ready_handler(conn, cbData);
  11174. }
  11175. #if defined(USE_LUA)
  11176. } else if (lua_websock) {
  11177. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11178. /* the ready handler returned false */
  11179. return;
  11180. }
  11181. #endif
  11182. }
  11183. /* Step 7: Enter the read loop */
  11184. if (is_callback_resource) {
  11185. read_websocket(conn, ws_data_handler, cbData);
  11186. #if defined(USE_LUA)
  11187. } else if (lua_websock) {
  11188. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11189. #endif
  11190. }
  11191. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11192. /* Step 8: Close the deflate & inflate buffers */
  11193. if (conn->websocket_deflate_initialized) {
  11194. deflateEnd(&conn->websocket_deflate_state);
  11195. inflateEnd(&conn->websocket_inflate_state);
  11196. }
  11197. #endif
  11198. /* Step 9: Call the close handler */
  11199. if (ws_close_handler) {
  11200. ws_close_handler(conn, cbData);
  11201. }
  11202. }
  11203. #endif /* !USE_WEBSOCKET */
  11204. /* Is upgrade request:
  11205. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11206. * 1 = upgrade to websocket
  11207. * 2 = upgrade to HTTP/2
  11208. * -1 = upgrade to unknown protocol
  11209. */
  11210. static int
  11211. should_switch_to_protocol(const struct mg_connection *conn)
  11212. {
  11213. const char *upgrade, *connection;
  11214. /* A websocket protocoll has the following HTTP headers:
  11215. *
  11216. * Connection: Upgrade
  11217. * Upgrade: Websocket
  11218. */
  11219. connection = mg_get_header(conn, "Connection");
  11220. if (connection == NULL) {
  11221. return PROTOCOL_TYPE_HTTP1;
  11222. }
  11223. if (!mg_strcasestr(connection, "upgrade")) {
  11224. return PROTOCOL_TYPE_HTTP1;
  11225. }
  11226. upgrade = mg_get_header(conn, "Upgrade");
  11227. if (upgrade == NULL) {
  11228. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11229. return -1;
  11230. }
  11231. /* Upgrade to ... */
  11232. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11233. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11234. * "Sec-WebSocket-Version" are also required.
  11235. * Don't check them here, since even an unsupported websocket protocol
  11236. * request still IS a websocket request (in contrast to a standard HTTP
  11237. * request). It will fail later in handle_websocket_request.
  11238. */
  11239. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11240. }
  11241. if (0 != mg_strcasestr(upgrade, "h2")) {
  11242. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11243. }
  11244. /* Upgrade to another protocol */
  11245. return -1;
  11246. }
  11247. static int
  11248. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11249. {
  11250. int n;
  11251. unsigned int a, b, c, d, slash;
  11252. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11253. slash = 32;
  11254. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11255. n = 0;
  11256. }
  11257. }
  11258. if ((n > 0) && ((size_t)n == vec->len)) {
  11259. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11260. /* IPv4 format */
  11261. if (sa->sa.sa_family == AF_INET) {
  11262. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11263. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11264. | ((uint32_t)c << 8) | (uint32_t)d;
  11265. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11266. return (ip & mask) == net;
  11267. }
  11268. return 0;
  11269. }
  11270. }
  11271. #if defined(USE_IPV6)
  11272. else {
  11273. char ad[50];
  11274. const char *p;
  11275. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11276. slash = 128;
  11277. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11278. n = 0;
  11279. }
  11280. }
  11281. if ((n <= 0) && no_strict) {
  11282. /* no square brackets? */
  11283. p = strchr(vec->ptr, '/');
  11284. if (p && (p < (vec->ptr + vec->len))) {
  11285. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11286. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11287. n += (int)(p - vec->ptr);
  11288. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11289. } else {
  11290. n = 0;
  11291. }
  11292. } else if (vec->len < sizeof(ad)) {
  11293. n = (int)vec->len;
  11294. slash = 128;
  11295. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11296. }
  11297. }
  11298. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11299. p = ad;
  11300. c = 0;
  11301. /* zone indexes are unsupported, at least two colons are needed */
  11302. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11303. if (*(p++) == ':') {
  11304. c++;
  11305. }
  11306. }
  11307. if ((*p == '\0') && (c >= 2)) {
  11308. struct sockaddr_in6 sin6;
  11309. unsigned int i;
  11310. /* for strict validation, an actual IPv6 argument is needed */
  11311. if (sa->sa.sa_family != AF_INET6) {
  11312. return 0;
  11313. }
  11314. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11315. /* IPv6 format */
  11316. for (i = 0; i < 16; i++) {
  11317. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11318. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11319. uint8_t mask = 0;
  11320. if (8 * i + 8 < slash) {
  11321. mask = 0xFFu;
  11322. } else if (8 * i < slash) {
  11323. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11324. }
  11325. if ((ip & mask) != net) {
  11326. return 0;
  11327. }
  11328. }
  11329. return 1;
  11330. }
  11331. }
  11332. }
  11333. }
  11334. #else
  11335. (void)no_strict;
  11336. #endif
  11337. /* malformed */
  11338. return -1;
  11339. }
  11340. static int
  11341. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11342. {
  11343. int throttle = 0;
  11344. struct vec vec, val;
  11345. char mult;
  11346. double v;
  11347. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11348. mult = ',';
  11349. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11350. || (v < 0)
  11351. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11352. && (mult != ','))) {
  11353. continue;
  11354. }
  11355. v *= (lowercase(&mult) == 'k')
  11356. ? 1024
  11357. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11358. if (vec.len == 1 && vec.ptr[0] == '*') {
  11359. throttle = (int)v;
  11360. } else {
  11361. int matched = parse_match_net(&vec, rsa, 0);
  11362. if (matched >= 0) {
  11363. /* a valid IP subnet */
  11364. if (matched) {
  11365. throttle = (int)v;
  11366. }
  11367. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11368. throttle = (int)v;
  11369. }
  11370. }
  11371. }
  11372. return throttle;
  11373. }
  11374. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11375. #include "handle_form.inl"
  11376. static int
  11377. get_first_ssl_listener_index(const struct mg_context *ctx)
  11378. {
  11379. unsigned int i;
  11380. int idx = -1;
  11381. if (ctx) {
  11382. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11383. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11384. }
  11385. }
  11386. return idx;
  11387. }
  11388. /* Return host (without port) */
  11389. static void
  11390. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11391. {
  11392. const char *host_header =
  11393. get_header(ri->http_headers, ri->num_headers, "Host");
  11394. host->ptr = NULL;
  11395. host->len = 0;
  11396. if (host_header != NULL) {
  11397. const char *pos;
  11398. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11399. * is found. */
  11400. if (*host_header == '[') {
  11401. pos = strchr(host_header, ']');
  11402. if (!pos) {
  11403. /* Malformed hostname starts with '[', but no ']' found */
  11404. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11405. return;
  11406. }
  11407. /* terminate after ']' */
  11408. host->ptr = host_header;
  11409. host->len = (size_t)(pos + 1 - host_header);
  11410. } else {
  11411. /* Otherwise, a ':' separates hostname and port number */
  11412. pos = strchr(host_header, ':');
  11413. if (pos != NULL) {
  11414. host->len = (size_t)(pos - host_header);
  11415. } else {
  11416. host->len = strlen(host_header);
  11417. }
  11418. host->ptr = host_header;
  11419. }
  11420. }
  11421. }
  11422. static int
  11423. switch_domain_context(struct mg_connection *conn)
  11424. {
  11425. struct vec host;
  11426. get_host_from_request_info(&host, &conn->request_info);
  11427. if (host.ptr) {
  11428. if (conn->ssl) {
  11429. /* This is a HTTPS connection, maybe we have a hostname
  11430. * from SNI (set in ssl_servername_callback). */
  11431. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11432. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11433. /* We are not using the default domain */
  11434. if ((strlen(sslhost) != host.len)
  11435. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11436. /* Mismatch between SNI domain and HTTP domain */
  11437. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11438. sslhost,
  11439. (int)host.len,
  11440. host.ptr);
  11441. return 0;
  11442. }
  11443. }
  11444. } else {
  11445. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11446. while (dom) {
  11447. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  11448. size_t domNameLen = strlen(domName);
  11449. if ((domNameLen == host.len)
  11450. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  11451. /* Found matching domain */
  11452. DEBUG_TRACE("HTTP domain %s found",
  11453. dom->config[AUTHENTICATION_DOMAIN]);
  11454. /* TODO: Check if this is a HTTP or HTTPS domain */
  11455. conn->dom_ctx = dom;
  11456. break;
  11457. }
  11458. mg_lock_context(conn->phys_ctx);
  11459. dom = dom->next;
  11460. mg_unlock_context(conn->phys_ctx);
  11461. }
  11462. }
  11463. DEBUG_TRACE("HTTP%s Host: %.*s",
  11464. conn->ssl ? "S" : "",
  11465. (int)host.len,
  11466. host.ptr);
  11467. } else {
  11468. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11469. return 1;
  11470. }
  11471. return 1;
  11472. }
  11473. static int mg_construct_local_link(const struct mg_connection *conn,
  11474. char *buf,
  11475. size_t buflen,
  11476. const char *define_proto,
  11477. int define_port,
  11478. const char *define_uri);
  11479. static void
  11480. redirect_to_https_port(struct mg_connection *conn, int port)
  11481. {
  11482. char target_url[MG_BUF_LEN];
  11483. int truncated = 0;
  11484. const char *expect_proto =
  11485. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11486. /* Use "308 Permanent Redirect" */
  11487. int redirect_code = 308;
  11488. /* In any case, close the current connection */
  11489. conn->must_close = 1;
  11490. /* Send host, port, uri and (if it exists) ?query_string */
  11491. if (mg_construct_local_link(
  11492. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11493. < 0) {
  11494. truncated = 1;
  11495. } else if (conn->request_info.query_string != NULL) {
  11496. size_t slen1 = strlen(target_url);
  11497. size_t slen2 = strlen(conn->request_info.query_string);
  11498. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11499. target_url[slen1] = '?';
  11500. memcpy(target_url + slen1 + 1,
  11501. conn->request_info.query_string,
  11502. slen2);
  11503. target_url[slen1 + slen2 + 1] = 0;
  11504. } else {
  11505. truncated = 1;
  11506. }
  11507. }
  11508. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11509. * is used as buffer size) */
  11510. if (truncated) {
  11511. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11512. return;
  11513. }
  11514. /* Use redirect helper function */
  11515. mg_send_http_redirect(conn, target_url, redirect_code);
  11516. }
  11517. static void
  11518. mg_set_handler_type(struct mg_context *phys_ctx,
  11519. struct mg_domain_context *dom_ctx,
  11520. const char *uri,
  11521. int handler_type,
  11522. int is_delete_request,
  11523. mg_request_handler handler,
  11524. struct mg_websocket_subprotocols *subprotocols,
  11525. mg_websocket_connect_handler connect_handler,
  11526. mg_websocket_ready_handler ready_handler,
  11527. mg_websocket_data_handler data_handler,
  11528. mg_websocket_close_handler close_handler,
  11529. mg_authorization_handler auth_handler,
  11530. void *cbdata)
  11531. {
  11532. struct mg_handler_info *tmp_rh, **lastref;
  11533. size_t urilen = strlen(uri);
  11534. if (handler_type == WEBSOCKET_HANDLER) {
  11535. DEBUG_ASSERT(handler == NULL);
  11536. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11537. || ready_handler != NULL || data_handler != NULL
  11538. || close_handler != NULL);
  11539. DEBUG_ASSERT(auth_handler == NULL);
  11540. if (handler != NULL) {
  11541. return;
  11542. }
  11543. if (!is_delete_request && (connect_handler == NULL)
  11544. && (ready_handler == NULL) && (data_handler == NULL)
  11545. && (close_handler == NULL)) {
  11546. return;
  11547. }
  11548. if (auth_handler != NULL) {
  11549. return;
  11550. }
  11551. } else if (handler_type == REQUEST_HANDLER) {
  11552. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11553. && data_handler == NULL && close_handler == NULL);
  11554. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11555. DEBUG_ASSERT(auth_handler == NULL);
  11556. if ((connect_handler != NULL) || (ready_handler != NULL)
  11557. || (data_handler != NULL) || (close_handler != NULL)) {
  11558. return;
  11559. }
  11560. if (!is_delete_request && (handler == NULL)) {
  11561. return;
  11562. }
  11563. if (auth_handler != NULL) {
  11564. return;
  11565. }
  11566. } else if (handler_type == AUTH_HANDLER) {
  11567. DEBUG_ASSERT(handler == NULL);
  11568. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11569. && data_handler == NULL && close_handler == NULL);
  11570. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  11571. if (handler != NULL) {
  11572. return;
  11573. }
  11574. if ((connect_handler != NULL) || (ready_handler != NULL)
  11575. || (data_handler != NULL) || (close_handler != NULL)) {
  11576. return;
  11577. }
  11578. if (!is_delete_request && (auth_handler == NULL)) {
  11579. return;
  11580. }
  11581. } else {
  11582. /* Unknown handler type. */
  11583. return;
  11584. }
  11585. if (!phys_ctx || !dom_ctx) {
  11586. /* no context available */
  11587. return;
  11588. }
  11589. mg_lock_context(phys_ctx);
  11590. /* first try to find an existing handler */
  11591. do {
  11592. lastref = &(dom_ctx->handlers);
  11593. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11594. tmp_rh = tmp_rh->next) {
  11595. if (tmp_rh->handler_type == handler_type
  11596. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11597. if (!is_delete_request) {
  11598. /* update existing handler */
  11599. if (handler_type == REQUEST_HANDLER) {
  11600. /* Wait for end of use before updating */
  11601. if (tmp_rh->refcount) {
  11602. mg_unlock_context(phys_ctx);
  11603. mg_sleep(1);
  11604. mg_lock_context(phys_ctx);
  11605. /* tmp_rh might have been freed, search again. */
  11606. break;
  11607. }
  11608. /* Ok, the handler is no more use -> Update it */
  11609. tmp_rh->handler = handler;
  11610. } else if (handler_type == WEBSOCKET_HANDLER) {
  11611. tmp_rh->subprotocols = subprotocols;
  11612. tmp_rh->connect_handler = connect_handler;
  11613. tmp_rh->ready_handler = ready_handler;
  11614. tmp_rh->data_handler = data_handler;
  11615. tmp_rh->close_handler = close_handler;
  11616. } else { /* AUTH_HANDLER */
  11617. tmp_rh->auth_handler = auth_handler;
  11618. }
  11619. tmp_rh->cbdata = cbdata;
  11620. } else {
  11621. /* remove existing handler */
  11622. if (handler_type == REQUEST_HANDLER) {
  11623. /* Wait for end of use before removing */
  11624. if (tmp_rh->refcount) {
  11625. tmp_rh->removing = 1;
  11626. mg_unlock_context(phys_ctx);
  11627. mg_sleep(1);
  11628. mg_lock_context(phys_ctx);
  11629. /* tmp_rh might have been freed, search again. */
  11630. break;
  11631. }
  11632. /* Ok, the handler is no more used */
  11633. }
  11634. *lastref = tmp_rh->next;
  11635. mg_free(tmp_rh->uri);
  11636. mg_free(tmp_rh);
  11637. }
  11638. mg_unlock_context(phys_ctx);
  11639. return;
  11640. }
  11641. lastref = &(tmp_rh->next);
  11642. }
  11643. } while (tmp_rh != NULL);
  11644. if (is_delete_request) {
  11645. /* no handler to set, this was a remove request to a non-existing
  11646. * handler */
  11647. mg_unlock_context(phys_ctx);
  11648. return;
  11649. }
  11650. tmp_rh =
  11651. (struct mg_handler_info *)mg_calloc_ctx(1,
  11652. sizeof(struct mg_handler_info),
  11653. phys_ctx);
  11654. if (tmp_rh == NULL) {
  11655. mg_unlock_context(phys_ctx);
  11656. mg_cry_ctx_internal(phys_ctx,
  11657. "%s",
  11658. "Cannot create new request handler struct, OOM");
  11659. return;
  11660. }
  11661. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11662. if (!tmp_rh->uri) {
  11663. mg_unlock_context(phys_ctx);
  11664. mg_free(tmp_rh);
  11665. mg_cry_ctx_internal(phys_ctx,
  11666. "%s",
  11667. "Cannot create new request handler struct, OOM");
  11668. return;
  11669. }
  11670. tmp_rh->uri_len = urilen;
  11671. if (handler_type == REQUEST_HANDLER) {
  11672. tmp_rh->refcount = 0;
  11673. tmp_rh->removing = 0;
  11674. tmp_rh->handler = handler;
  11675. } else if (handler_type == WEBSOCKET_HANDLER) {
  11676. tmp_rh->subprotocols = subprotocols;
  11677. tmp_rh->connect_handler = connect_handler;
  11678. tmp_rh->ready_handler = ready_handler;
  11679. tmp_rh->data_handler = data_handler;
  11680. tmp_rh->close_handler = close_handler;
  11681. } else { /* AUTH_HANDLER */
  11682. tmp_rh->auth_handler = auth_handler;
  11683. }
  11684. tmp_rh->cbdata = cbdata;
  11685. tmp_rh->handler_type = handler_type;
  11686. tmp_rh->next = NULL;
  11687. *lastref = tmp_rh;
  11688. mg_unlock_context(phys_ctx);
  11689. }
  11690. void
  11691. mg_set_request_handler(struct mg_context *ctx,
  11692. const char *uri,
  11693. mg_request_handler handler,
  11694. void *cbdata)
  11695. {
  11696. mg_set_handler_type(ctx,
  11697. &(ctx->dd),
  11698. uri,
  11699. REQUEST_HANDLER,
  11700. handler == NULL,
  11701. handler,
  11702. NULL,
  11703. NULL,
  11704. NULL,
  11705. NULL,
  11706. NULL,
  11707. NULL,
  11708. cbdata);
  11709. }
  11710. void
  11711. mg_set_websocket_handler(struct mg_context *ctx,
  11712. const char *uri,
  11713. mg_websocket_connect_handler connect_handler,
  11714. mg_websocket_ready_handler ready_handler,
  11715. mg_websocket_data_handler data_handler,
  11716. mg_websocket_close_handler close_handler,
  11717. void *cbdata)
  11718. {
  11719. mg_set_websocket_handler_with_subprotocols(ctx,
  11720. uri,
  11721. NULL,
  11722. connect_handler,
  11723. ready_handler,
  11724. data_handler,
  11725. close_handler,
  11726. cbdata);
  11727. }
  11728. void
  11729. mg_set_websocket_handler_with_subprotocols(
  11730. struct mg_context *ctx,
  11731. const char *uri,
  11732. struct mg_websocket_subprotocols *subprotocols,
  11733. mg_websocket_connect_handler connect_handler,
  11734. mg_websocket_ready_handler ready_handler,
  11735. mg_websocket_data_handler data_handler,
  11736. mg_websocket_close_handler close_handler,
  11737. void *cbdata)
  11738. {
  11739. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11740. && (data_handler == NULL)
  11741. && (close_handler == NULL);
  11742. mg_set_handler_type(ctx,
  11743. &(ctx->dd),
  11744. uri,
  11745. WEBSOCKET_HANDLER,
  11746. is_delete_request,
  11747. NULL,
  11748. subprotocols,
  11749. connect_handler,
  11750. ready_handler,
  11751. data_handler,
  11752. close_handler,
  11753. NULL,
  11754. cbdata);
  11755. }
  11756. void
  11757. mg_set_auth_handler(struct mg_context *ctx,
  11758. const char *uri,
  11759. mg_authorization_handler handler,
  11760. void *cbdata)
  11761. {
  11762. mg_set_handler_type(ctx,
  11763. &(ctx->dd),
  11764. uri,
  11765. AUTH_HANDLER,
  11766. handler == NULL,
  11767. NULL,
  11768. NULL,
  11769. NULL,
  11770. NULL,
  11771. NULL,
  11772. NULL,
  11773. handler,
  11774. cbdata);
  11775. }
  11776. static int
  11777. get_request_handler(struct mg_connection *conn,
  11778. int handler_type,
  11779. mg_request_handler *handler,
  11780. struct mg_websocket_subprotocols **subprotocols,
  11781. mg_websocket_connect_handler *connect_handler,
  11782. mg_websocket_ready_handler *ready_handler,
  11783. mg_websocket_data_handler *data_handler,
  11784. mg_websocket_close_handler *close_handler,
  11785. mg_authorization_handler *auth_handler,
  11786. void **cbdata,
  11787. struct mg_handler_info **handler_info)
  11788. {
  11789. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11790. if (request_info) {
  11791. const char *uri = request_info->local_uri;
  11792. size_t urilen = strlen(uri);
  11793. struct mg_handler_info *tmp_rh;
  11794. int step, matched;
  11795. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11796. return 0;
  11797. }
  11798. mg_lock_context(conn->phys_ctx);
  11799. for (step = 0; step < 3; step++) {
  11800. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11801. tmp_rh = tmp_rh->next) {
  11802. if (tmp_rh->handler_type != handler_type) {
  11803. continue;
  11804. }
  11805. if (step == 0) {
  11806. /* first try for an exact match */
  11807. matched = (tmp_rh->uri_len == urilen)
  11808. && (strcmp(tmp_rh->uri, uri) == 0);
  11809. } else if (step == 1) {
  11810. /* next try for a partial match, we will accept
  11811. uri/something */
  11812. matched =
  11813. (tmp_rh->uri_len < urilen)
  11814. && (uri[tmp_rh->uri_len] == '/')
  11815. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  11816. } else {
  11817. /* finally try for pattern match */
  11818. matched =
  11819. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  11820. }
  11821. if (matched) {
  11822. if (handler_type == WEBSOCKET_HANDLER) {
  11823. *subprotocols = tmp_rh->subprotocols;
  11824. *connect_handler = tmp_rh->connect_handler;
  11825. *ready_handler = tmp_rh->ready_handler;
  11826. *data_handler = tmp_rh->data_handler;
  11827. *close_handler = tmp_rh->close_handler;
  11828. } else if (handler_type == REQUEST_HANDLER) {
  11829. if (tmp_rh->removing) {
  11830. /* Treat as none found */
  11831. step = 2;
  11832. break;
  11833. }
  11834. *handler = tmp_rh->handler;
  11835. /* Acquire handler and give it back */
  11836. tmp_rh->refcount++;
  11837. *handler_info = tmp_rh;
  11838. } else { /* AUTH_HANDLER */
  11839. *auth_handler = tmp_rh->auth_handler;
  11840. }
  11841. *cbdata = tmp_rh->cbdata;
  11842. mg_unlock_context(conn->phys_ctx);
  11843. return 1;
  11844. }
  11845. }
  11846. }
  11847. mg_unlock_context(conn->phys_ctx);
  11848. }
  11849. return 0; /* none found */
  11850. }
  11851. /* Check if the script file is in a path, allowed for script files.
  11852. * This can be used if uploading files is possible not only for the server
  11853. * admin, and the upload mechanism does not check the file extension.
  11854. */
  11855. static int
  11856. is_in_script_path(const struct mg_connection *conn, const char *path)
  11857. {
  11858. /* TODO (Feature): Add config value for allowed script path.
  11859. * Default: All allowed. */
  11860. (void)conn;
  11861. (void)path;
  11862. return 1;
  11863. }
  11864. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  11865. static int
  11866. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  11867. int bits,
  11868. char *data,
  11869. size_t len,
  11870. void *cbdata)
  11871. {
  11872. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11873. if (pcallbacks->websocket_data) {
  11874. return pcallbacks->websocket_data(conn, bits, data, len);
  11875. }
  11876. /* No handler set - assume "OK" */
  11877. return 1;
  11878. }
  11879. static void
  11880. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  11881. void *cbdata)
  11882. {
  11883. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11884. if (pcallbacks->connection_close) {
  11885. pcallbacks->connection_close(conn);
  11886. }
  11887. }
  11888. #endif
  11889. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  11890. */
  11891. static void
  11892. release_handler_ref(struct mg_connection *conn,
  11893. struct mg_handler_info *handler_info)
  11894. {
  11895. if (handler_info != NULL) {
  11896. /* Use context lock for ref counter */
  11897. mg_lock_context(conn->phys_ctx);
  11898. handler_info->refcount--;
  11899. mg_unlock_context(conn->phys_ctx);
  11900. }
  11901. }
  11902. /* This is the heart of the Civetweb's logic.
  11903. * This function is called when the request is read, parsed and validated,
  11904. * and Civetweb must decide what action to take: serve a file, or
  11905. * a directory, or call embedded function, etcetera. */
  11906. static void
  11907. handle_request(struct mg_connection *conn)
  11908. {
  11909. struct mg_request_info *ri = &conn->request_info;
  11910. char path[UTF8_PATH_MAX];
  11911. int uri_len, ssl_index;
  11912. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11913. is_put_or_delete_request = 0, is_callback_resource = 0,
  11914. is_template_text_file = 0;
  11915. int i;
  11916. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11917. mg_request_handler callback_handler = NULL;
  11918. struct mg_handler_info *handler_info = NULL;
  11919. struct mg_websocket_subprotocols *subprotocols;
  11920. mg_websocket_connect_handler ws_connect_handler = NULL;
  11921. mg_websocket_ready_handler ws_ready_handler = NULL;
  11922. mg_websocket_data_handler ws_data_handler = NULL;
  11923. mg_websocket_close_handler ws_close_handler = NULL;
  11924. void *callback_data = NULL;
  11925. mg_authorization_handler auth_handler = NULL;
  11926. void *auth_callback_data = NULL;
  11927. int handler_type;
  11928. time_t curtime = time(NULL);
  11929. char date[64];
  11930. char *tmp;
  11931. path[0] = 0;
  11932. /* 0. Reset internal state (required for HTTP/2 proxy) */
  11933. conn->request_state = 0;
  11934. /* 1. get the request url */
  11935. /* 1.1. split into url and query string */
  11936. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11937. != NULL) {
  11938. *((char *)conn->request_info.query_string++) = '\0';
  11939. }
  11940. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11941. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11942. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11943. if (ssl_index >= 0) {
  11944. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  11945. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  11946. redirect_to_https_port(conn, port);
  11947. } else {
  11948. /* A http to https forward port has been specified,
  11949. * but no https port to forward to. */
  11950. mg_send_http_error(conn,
  11951. 503,
  11952. "%s",
  11953. "Error: SSL forward not configured properly");
  11954. mg_cry_internal(conn,
  11955. "%s",
  11956. "Can not redirect to SSL, no SSL port available");
  11957. }
  11958. return;
  11959. }
  11960. uri_len = (int)strlen(ri->local_uri);
  11961. /* 1.3. decode url (if config says so) */
  11962. if (should_decode_url(conn)) {
  11963. mg_url_decode(
  11964. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11965. if (conn->request_info.query_string) {
  11966. url_decode_in_place((char *)conn->request_info.query_string);
  11967. }
  11968. }
  11969. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  11970. * possible. The fact that we cleaned the URI is stored in that the
  11971. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  11972. * ri->local_uri_raw still points to memory allocated in
  11973. * worker_thread_run(). ri->local_uri is private to the request so we
  11974. * don't have to use preallocated memory here. */
  11975. tmp = mg_strdup(ri->local_uri_raw);
  11976. if (!tmp) {
  11977. /* Out of memory. We cannot do anything reasonable here. */
  11978. return;
  11979. }
  11980. remove_dot_segments(tmp);
  11981. ri->local_uri = tmp;
  11982. /* step 1. completed, the url is known now */
  11983. uri_len = (int)strlen(ri->local_uri);
  11984. DEBUG_TRACE("URL: %s", ri->local_uri);
  11985. /* 2. if this ip has limited speed, set it for this connection */
  11986. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11987. &conn->client.rsa,
  11988. ri->local_uri);
  11989. /* 3. call a "handle everything" callback, if registered */
  11990. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11991. /* Note that since V1.7 the "begin_request" function is called
  11992. * before an authorization check. If an authorization check is
  11993. * required, use a request_handler instead. */
  11994. i = conn->phys_ctx->callbacks.begin_request(conn);
  11995. if (i > 0) {
  11996. /* callback already processed the request. Store the
  11997. return value as a status code for the access log. */
  11998. conn->status_code = i;
  11999. if (!conn->must_close) {
  12000. discard_unread_request_data(conn);
  12001. }
  12002. return;
  12003. } else if (i == 0) {
  12004. /* civetweb should process the request */
  12005. } else {
  12006. /* unspecified - may change with the next version */
  12007. return;
  12008. }
  12009. }
  12010. /* request not yet handled by a handler or redirect, so the request
  12011. * is processed here */
  12012. /* 4. Check for CORS preflight requests and handle them (if configured).
  12013. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12014. */
  12015. if (!strcmp(ri->request_method, "OPTIONS")) {
  12016. /* Send a response to CORS preflights only if
  12017. * access_control_allow_methods is not NULL and not an empty string.
  12018. * In this case, scripts can still handle CORS. */
  12019. const char *cors_meth_cfg =
  12020. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12021. const char *cors_orig_cfg =
  12022. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12023. const char *cors_origin =
  12024. get_header(ri->http_headers, ri->num_headers, "Origin");
  12025. const char *cors_acrm = get_header(ri->http_headers,
  12026. ri->num_headers,
  12027. "Access-Control-Request-Method");
  12028. /* Todo: check if cors_origin is in cors_orig_cfg.
  12029. * Or, let the client check this. */
  12030. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12031. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12032. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12033. /* This is a valid CORS preflight, and the server is configured
  12034. * to handle it automatically. */
  12035. const char *cors_acrh =
  12036. get_header(ri->http_headers,
  12037. ri->num_headers,
  12038. "Access-Control-Request-Headers");
  12039. gmt_time_string(date, sizeof(date), &curtime);
  12040. mg_printf(conn,
  12041. "HTTP/1.1 200 OK\r\n"
  12042. "Date: %s\r\n"
  12043. "Access-Control-Allow-Origin: %s\r\n"
  12044. "Access-Control-Allow-Methods: %s\r\n"
  12045. "Content-Length: 0\r\n"
  12046. "Connection: %s\r\n",
  12047. date,
  12048. cors_orig_cfg,
  12049. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12050. suggest_connection_header(conn));
  12051. if (cors_acrh != NULL) {
  12052. /* CORS request is asking for additional headers */
  12053. const char *cors_hdr_cfg =
  12054. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12055. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12056. /* Allow only if access_control_allow_headers is
  12057. * not NULL and not an empty string. If this
  12058. * configuration is set to *, allow everything.
  12059. * Otherwise this configuration must be a list
  12060. * of allowed HTTP header names. */
  12061. mg_printf(conn,
  12062. "Access-Control-Allow-Headers: %s\r\n",
  12063. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12064. : cors_hdr_cfg));
  12065. }
  12066. }
  12067. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12068. mg_printf(conn, "\r\n");
  12069. return;
  12070. }
  12071. }
  12072. /* 5. interpret the url to find out how the request must be handled
  12073. */
  12074. /* 5.1. first test, if the request targets the regular http(s)://
  12075. * protocol namespace or the websocket ws(s):// protocol namespace.
  12076. */
  12077. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12078. #if defined(USE_WEBSOCKET)
  12079. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12080. #else
  12081. handler_type = REQUEST_HANDLER;
  12082. #endif /* defined(USE_WEBSOCKET) */
  12083. if (is_websocket_request) {
  12084. HTTP1_only;
  12085. }
  12086. /* 5.2. check if the request will be handled by a callback */
  12087. if (get_request_handler(conn,
  12088. handler_type,
  12089. &callback_handler,
  12090. &subprotocols,
  12091. &ws_connect_handler,
  12092. &ws_ready_handler,
  12093. &ws_data_handler,
  12094. &ws_close_handler,
  12095. NULL,
  12096. &callback_data,
  12097. &handler_info)) {
  12098. /* 5.2.1. A callback will handle this request. All requests
  12099. * handled by a callback have to be considered as requests
  12100. * to a script resource. */
  12101. is_callback_resource = 1;
  12102. is_script_resource = 1;
  12103. is_put_or_delete_request = is_put_or_delete_method(conn);
  12104. } else {
  12105. no_callback_resource:
  12106. /* 5.2.2. No callback is responsible for this request. The URI
  12107. * addresses a file based resource (static content or Lua/cgi
  12108. * scripts in the file system). */
  12109. is_callback_resource = 0;
  12110. interpret_uri(conn,
  12111. path,
  12112. sizeof(path),
  12113. &file.stat,
  12114. &is_found,
  12115. &is_script_resource,
  12116. &is_websocket_request,
  12117. &is_put_or_delete_request,
  12118. &is_template_text_file);
  12119. }
  12120. /* 6. authorization check */
  12121. /* 6.1. a custom authorization handler is installed */
  12122. if (get_request_handler(conn,
  12123. AUTH_HANDLER,
  12124. NULL,
  12125. NULL,
  12126. NULL,
  12127. NULL,
  12128. NULL,
  12129. NULL,
  12130. &auth_handler,
  12131. &auth_callback_data,
  12132. NULL)) {
  12133. if (!auth_handler(conn, auth_callback_data)) {
  12134. /* Callback handler will not be used anymore. Release it */
  12135. release_handler_ref(conn, handler_info);
  12136. return;
  12137. }
  12138. } else if (is_put_or_delete_request && !is_script_resource
  12139. && !is_callback_resource) {
  12140. HTTP1_only;
  12141. /* 6.2. this request is a PUT/DELETE to a real file */
  12142. /* 6.2.1. thus, the server must have real files */
  12143. #if defined(NO_FILES)
  12144. if (1) {
  12145. #else
  12146. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12147. #endif
  12148. /* This code path will not be called for request handlers */
  12149. DEBUG_ASSERT(handler_info == NULL);
  12150. /* This server does not have any real files, thus the
  12151. * PUT/DELETE methods are not valid. */
  12152. mg_send_http_error(conn,
  12153. 405,
  12154. "%s method not allowed",
  12155. conn->request_info.request_method);
  12156. return;
  12157. }
  12158. #if !defined(NO_FILES)
  12159. /* 6.2.2. Check if put authorization for static files is
  12160. * available.
  12161. */
  12162. if (!is_authorized_for_put(conn)) {
  12163. send_authorization_request(conn, NULL);
  12164. return;
  12165. }
  12166. #endif
  12167. } else {
  12168. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12169. * or it is a PUT or DELETE request to a resource that does not
  12170. * correspond to a file. Check authorization. */
  12171. if (!check_authorization(conn, path)) {
  12172. send_authorization_request(conn, NULL);
  12173. /* Callback handler will not be used anymore. Release it */
  12174. release_handler_ref(conn, handler_info);
  12175. return;
  12176. }
  12177. }
  12178. /* request is authorized or does not need authorization */
  12179. /* 7. check if there are request handlers for this uri */
  12180. if (is_callback_resource) {
  12181. HTTP1_only;
  12182. if (!is_websocket_request) {
  12183. i = callback_handler(conn, callback_data);
  12184. /* Callback handler will not be used anymore. Release it */
  12185. release_handler_ref(conn, handler_info);
  12186. if (i > 0) {
  12187. /* Do nothing, callback has served the request. Store
  12188. * then return value as status code for the log and discard
  12189. * all data from the client not used by the callback. */
  12190. conn->status_code = i;
  12191. if (!conn->must_close) {
  12192. discard_unread_request_data(conn);
  12193. }
  12194. } else {
  12195. /* The handler did NOT handle the request. */
  12196. /* Some proper reactions would be:
  12197. * a) close the connections without sending anything
  12198. * b) send a 404 not found
  12199. * c) try if there is a file matching the URI
  12200. * It would be possible to do a, b or c in the callback
  12201. * implementation, and return 1 - we cannot do anything
  12202. * here, that is not possible in the callback.
  12203. *
  12204. * TODO: What would be the best reaction here?
  12205. * (Note: The reaction may change, if there is a better
  12206. * idea.)
  12207. */
  12208. /* For the moment, use option c: We look for a proper file,
  12209. * but since a file request is not always a script resource,
  12210. * the authorization check might be different. */
  12211. interpret_uri(conn,
  12212. path,
  12213. sizeof(path),
  12214. &file.stat,
  12215. &is_found,
  12216. &is_script_resource,
  12217. &is_websocket_request,
  12218. &is_put_or_delete_request,
  12219. &is_template_text_file);
  12220. callback_handler = NULL;
  12221. /* Here we are at a dead end:
  12222. * According to URI matching, a callback should be
  12223. * responsible for handling the request,
  12224. * we called it, but the callback declared itself
  12225. * not responsible.
  12226. * We use a goto here, to get out of this dead end,
  12227. * and continue with the default handling.
  12228. * A goto here is simpler and better to understand
  12229. * than some curious loop. */
  12230. goto no_callback_resource;
  12231. }
  12232. } else {
  12233. #if defined(USE_WEBSOCKET)
  12234. handle_websocket_request(conn,
  12235. path,
  12236. is_callback_resource,
  12237. subprotocols,
  12238. ws_connect_handler,
  12239. ws_ready_handler,
  12240. ws_data_handler,
  12241. ws_close_handler,
  12242. callback_data);
  12243. #endif
  12244. }
  12245. return;
  12246. }
  12247. /* 8. handle websocket requests */
  12248. #if defined(USE_WEBSOCKET)
  12249. if (is_websocket_request) {
  12250. HTTP1_only;
  12251. if (is_script_resource) {
  12252. if (is_in_script_path(conn, path)) {
  12253. /* Websocket Lua script */
  12254. handle_websocket_request(conn,
  12255. path,
  12256. 0 /* Lua Script */,
  12257. NULL,
  12258. NULL,
  12259. NULL,
  12260. NULL,
  12261. NULL,
  12262. conn->phys_ctx->user_data);
  12263. } else {
  12264. /* Script was in an illegal path */
  12265. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12266. }
  12267. } else {
  12268. mg_send_http_error(conn, 404, "%s", "Not found");
  12269. }
  12270. return;
  12271. } else
  12272. #endif
  12273. #if defined(NO_FILES)
  12274. /* 9a. In case the server uses only callbacks, this uri is
  12275. * unknown.
  12276. * Then, all request handling ends here. */
  12277. mg_send_http_error(conn, 404, "%s", "Not Found");
  12278. #else
  12279. /* 9b. This request is either for a static file or resource handled
  12280. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12281. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12282. mg_send_http_error(conn, 404, "%s", "Not Found");
  12283. return;
  12284. }
  12285. /* 10. Request is handled by a script */
  12286. if (is_script_resource) {
  12287. HTTP1_only;
  12288. handle_file_based_request(conn, path, &file);
  12289. return;
  12290. }
  12291. /* 11. Handle put/delete/mkcol requests */
  12292. if (is_put_or_delete_request) {
  12293. HTTP1_only;
  12294. /* 11.1. PUT method */
  12295. if (!strcmp(ri->request_method, "PUT")) {
  12296. put_file(conn, path);
  12297. return;
  12298. }
  12299. /* 11.2. DELETE method */
  12300. if (!strcmp(ri->request_method, "DELETE")) {
  12301. delete_file(conn, path);
  12302. return;
  12303. }
  12304. /* 11.3. MKCOL method */
  12305. if (!strcmp(ri->request_method, "MKCOL")) {
  12306. mkcol(conn, path);
  12307. return;
  12308. }
  12309. /* 11.4. PATCH method
  12310. * This method is not supported for static resources,
  12311. * only for scripts (Lua, CGI) and callbacks. */
  12312. mg_send_http_error(conn,
  12313. 405,
  12314. "%s method not allowed",
  12315. conn->request_info.request_method);
  12316. return;
  12317. }
  12318. /* 11. File does not exist, or it was configured that it should be
  12319. * hidden */
  12320. if (!is_found || (must_hide_file(conn, path))) {
  12321. mg_send_http_error(conn, 404, "%s", "Not found");
  12322. return;
  12323. }
  12324. /* 12. Directory uris should end with a slash */
  12325. if (file.stat.is_directory && (uri_len > 0)
  12326. && (ri->local_uri[uri_len - 1] != '/')) {
  12327. size_t len = strlen(ri->request_uri);
  12328. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12329. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12330. if (!new_path) {
  12331. mg_send_http_error(conn, 500, "out or memory");
  12332. } else {
  12333. memcpy(new_path, ri->request_uri, len);
  12334. new_path[len] = '/';
  12335. new_path[len + 1] = 0;
  12336. if (ri->query_string) {
  12337. new_path[len + 1] = '?';
  12338. /* Copy query string including terminating zero */
  12339. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12340. }
  12341. mg_send_http_redirect(conn, new_path, 301);
  12342. }
  12343. return;
  12344. }
  12345. /* 13. Handle other methods than GET/HEAD */
  12346. /* 13.1. Handle PROPFIND */
  12347. if (!strcmp(ri->request_method, "PROPFIND")) {
  12348. handle_propfind(conn, path, &file.stat);
  12349. return;
  12350. }
  12351. /* 13.2. Handle OPTIONS for files */
  12352. if (!strcmp(ri->request_method, "OPTIONS")) {
  12353. /* This standard handler is only used for real files.
  12354. * Scripts should support the OPTIONS method themselves, to allow a
  12355. * maximum flexibility.
  12356. * Lua and CGI scripts may fully support CORS this way (including
  12357. * preflights). */
  12358. send_options(conn);
  12359. return;
  12360. }
  12361. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12362. if ((0 != strcmp(ri->request_method, "GET"))
  12363. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12364. mg_send_http_error(conn,
  12365. 405,
  12366. "%s method not allowed",
  12367. conn->request_info.request_method);
  12368. return;
  12369. }
  12370. /* 14. directories */
  12371. if (file.stat.is_directory) {
  12372. /* Substitute files have already been handled above. */
  12373. /* Here we can either generate and send a directory listing,
  12374. * or send an "access denied" error. */
  12375. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12376. "yes")) {
  12377. handle_directory_request(conn, path);
  12378. } else {
  12379. mg_send_http_error(conn,
  12380. 403,
  12381. "%s",
  12382. "Error: Directory listing denied");
  12383. }
  12384. return;
  12385. }
  12386. /* 15. Files with search/replace patterns: LSP and SSI */
  12387. if (is_template_text_file) {
  12388. HTTP1_only;
  12389. handle_file_based_request(conn, path, &file);
  12390. return;
  12391. }
  12392. /* 16. Static file - maybe cached */
  12393. #if !defined(NO_CACHING)
  12394. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12395. /* Send 304 "Not Modified" - this must not send any body data */
  12396. handle_not_modified_static_file_request(conn, &file);
  12397. return;
  12398. }
  12399. #endif /* !NO_CACHING */
  12400. /* 17. Static file - not cached */
  12401. handle_static_file_request(conn, path, &file, NULL, NULL);
  12402. #endif /* !defined(NO_FILES) */
  12403. }
  12404. #if !defined(NO_FILESYSTEMS)
  12405. static void
  12406. handle_file_based_request(struct mg_connection *conn,
  12407. const char *path,
  12408. struct mg_file *file)
  12409. {
  12410. #if !defined(NO_CGI)
  12411. unsigned char cgi_config_idx, inc, max;
  12412. #endif
  12413. if (!conn || !conn->dom_ctx) {
  12414. return;
  12415. }
  12416. #if defined(USE_LUA)
  12417. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12418. path)
  12419. > 0) {
  12420. if (is_in_script_path(conn, path)) {
  12421. /* Lua server page: an SSI like page containing mostly plain
  12422. * html code plus some tags with server generated contents. */
  12423. handle_lsp_request(conn, path, file, NULL);
  12424. } else {
  12425. /* Script was in an illegal path */
  12426. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12427. }
  12428. return;
  12429. }
  12430. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  12431. > 0) {
  12432. if (is_in_script_path(conn, path)) {
  12433. /* Lua in-server module script: a CGI like script used to
  12434. * generate the entire reply. */
  12435. mg_exec_lua_script(conn, path, NULL);
  12436. } else {
  12437. /* Script was in an illegal path */
  12438. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12439. }
  12440. return;
  12441. }
  12442. #endif
  12443. #if defined(USE_DUKTAPE)
  12444. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12445. path)
  12446. > 0) {
  12447. if (is_in_script_path(conn, path)) {
  12448. /* Call duktape to generate the page */
  12449. mg_exec_duktape_script(conn, path);
  12450. } else {
  12451. /* Script was in an illegal path */
  12452. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12453. }
  12454. return;
  12455. }
  12456. #endif
  12457. #if !defined(NO_CGI)
  12458. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  12459. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  12460. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  12461. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  12462. if (match_prefix_strlen(
  12463. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  12464. path)
  12465. > 0) {
  12466. if (is_in_script_path(conn, path)) {
  12467. /* CGI scripts may support all HTTP methods */
  12468. handle_cgi_request(conn, path, 0);
  12469. } else {
  12470. /* Script was in an illegal path */
  12471. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12472. }
  12473. return;
  12474. }
  12475. }
  12476. }
  12477. #endif /* !NO_CGI */
  12478. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  12479. if (is_in_script_path(conn, path)) {
  12480. handle_ssi_file_request(conn, path, file);
  12481. } else {
  12482. /* Script was in an illegal path */
  12483. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12484. }
  12485. return;
  12486. }
  12487. #if !defined(NO_CACHING)
  12488. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  12489. /* Send 304 "Not Modified" - this must not send any body data */
  12490. handle_not_modified_static_file_request(conn, file);
  12491. return;
  12492. }
  12493. #endif /* !NO_CACHING */
  12494. handle_static_file_request(conn, path, file, NULL, NULL);
  12495. }
  12496. #endif /* NO_FILESYSTEMS */
  12497. static void
  12498. close_all_listening_sockets(struct mg_context *ctx)
  12499. {
  12500. unsigned int i;
  12501. if (!ctx) {
  12502. return;
  12503. }
  12504. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12505. closesocket(ctx->listening_sockets[i].sock);
  12506. #if defined(USE_X_DOM_SOCKET)
  12507. /* For unix domain sockets, the socket name represents a file that has
  12508. * to be deleted. */
  12509. /* See
  12510. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12511. */
  12512. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12513. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12514. IGNORE_UNUSED_RESULT(
  12515. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12516. }
  12517. #endif
  12518. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12519. }
  12520. mg_free(ctx->listening_sockets);
  12521. ctx->listening_sockets = NULL;
  12522. mg_free(ctx->listening_socket_fds);
  12523. ctx->listening_socket_fds = NULL;
  12524. }
  12525. /* Valid listening port specification is: [ip_address:]port[s]
  12526. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12527. * Examples for IPv6: [::]:80, [::1]:80,
  12528. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12529. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12530. * In order to bind to both, IPv4 and IPv6, you can either add
  12531. * both ports using 8080,[::]:8080, or the short form +8080.
  12532. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12533. * one only accepting IPv4 the other only IPv6. +8080 creates
  12534. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12535. * environment, they might work differently, or might not work
  12536. * at all - it must be tested what options work best in the
  12537. * relevant network environment.
  12538. */
  12539. static int
  12540. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12541. {
  12542. unsigned int a, b, c, d;
  12543. unsigned port;
  12544. unsigned long portUL;
  12545. int ch, len;
  12546. const char *cb;
  12547. char *endptr;
  12548. #if defined(USE_IPV6)
  12549. char buf[100] = {0};
  12550. #endif
  12551. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12552. * Also, all-zeroes in the socket address means binding to all addresses
  12553. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12554. memset(so, 0, sizeof(*so));
  12555. so->lsa.sin.sin_family = AF_INET;
  12556. *ip_version = 0;
  12557. /* Initialize len as invalid. */
  12558. port = 0;
  12559. len = 0;
  12560. /* Test for different ways to format this string */
  12561. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12562. == 5) {
  12563. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12564. so->lsa.sin.sin_addr.s_addr =
  12565. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12566. so->lsa.sin.sin_port = htons((uint16_t)port);
  12567. *ip_version = 4;
  12568. #if defined(USE_IPV6)
  12569. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12570. && ((size_t)len <= vec->len)
  12571. && mg_inet_pton(
  12572. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12573. /* IPv6 address, examples: see above */
  12574. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12575. */
  12576. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12577. *ip_version = 6;
  12578. #endif
  12579. } else if ((vec->ptr[0] == '+')
  12580. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12581. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12582. /* Add 1 to len for the + character we skipped before */
  12583. len++;
  12584. #if defined(USE_IPV6)
  12585. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12586. so->lsa.sin6.sin6_family = AF_INET6;
  12587. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12588. *ip_version = 4 + 6;
  12589. #else
  12590. /* Bind to IPv4 only, since IPv6 is not built in. */
  12591. so->lsa.sin.sin_port = htons((uint16_t)port);
  12592. *ip_version = 4;
  12593. #endif
  12594. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12595. && (vec->ptr != endptr)) {
  12596. len = (int)(endptr - vec->ptr);
  12597. port = (uint16_t)portUL;
  12598. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12599. so->lsa.sin.sin_port = htons((uint16_t)port);
  12600. *ip_version = 4;
  12601. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12602. /* String could be a hostname. This check algotithm
  12603. * will only work for RFC 952 compliant hostnames,
  12604. * starting with a letter, containing only letters,
  12605. * digits and hyphen ('-'). Newer specs may allow
  12606. * more, but this is not guaranteed here, since it
  12607. * may interfere with rules for port option lists. */
  12608. /* According to RFC 1035, hostnames are restricted to 255 characters
  12609. * in total (63 between two dots). */
  12610. char hostname[256];
  12611. size_t hostnlen = (size_t)(cb - vec->ptr);
  12612. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12613. /* This would be invalid in any case */
  12614. *ip_version = 0;
  12615. return 0;
  12616. }
  12617. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12618. if (mg_inet_pton(
  12619. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12620. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12621. *ip_version = 4;
  12622. so->lsa.sin.sin_port = htons((uint16_t)port);
  12623. len += (int)(hostnlen + 1);
  12624. } else {
  12625. len = 0;
  12626. }
  12627. #if defined(USE_IPV6)
  12628. } else if (mg_inet_pton(AF_INET6,
  12629. hostname,
  12630. &so->lsa.sin6,
  12631. sizeof(so->lsa.sin6),
  12632. 1)) {
  12633. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12634. *ip_version = 6;
  12635. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12636. len += (int)(hostnlen + 1);
  12637. } else {
  12638. len = 0;
  12639. }
  12640. #endif
  12641. } else {
  12642. len = 0;
  12643. }
  12644. #if defined(USE_X_DOM_SOCKET)
  12645. } else if (vec->ptr[0] == 'x') {
  12646. /* unix (linux) domain socket */
  12647. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  12648. len = vec->len;
  12649. so->lsa.sun.sun_family = AF_UNIX;
  12650. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  12651. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  12652. port = 0;
  12653. *ip_version = 99;
  12654. } else {
  12655. /* String too long */
  12656. len = 0;
  12657. }
  12658. #endif
  12659. } else {
  12660. /* Parsing failure. */
  12661. len = 0;
  12662. }
  12663. /* sscanf and the option splitting code ensure the following condition
  12664. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12665. if ((len > 0) && is_valid_port(port)
  12666. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  12667. /* Next character after the port number */
  12668. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12669. so->is_ssl = (ch == 's');
  12670. so->ssl_redir = (ch == 'r');
  12671. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12672. return 1;
  12673. }
  12674. }
  12675. /* Reset ip_version to 0 if there is an error */
  12676. *ip_version = 0;
  12677. return 0;
  12678. }
  12679. /* Is there any SSL port in use? */
  12680. static int
  12681. is_ssl_port_used(const char *ports)
  12682. {
  12683. if (ports) {
  12684. /* There are several different allowed syntax variants:
  12685. * - "80" for a single port using every network interface
  12686. * - "localhost:80" for a single port using only localhost
  12687. * - "80,localhost:8080" for two ports, one bound to localhost
  12688. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12689. * to IPv4 localhost, one to IPv6 localhost
  12690. * - "+80" use port 80 for IPv4 and IPv6
  12691. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12692. * for both: IPv4 and IPv4
  12693. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12694. * additionally port 8080 bound to localhost connections
  12695. *
  12696. * If we just look for 's' anywhere in the string, "localhost:80"
  12697. * will be detected as SSL (false positive).
  12698. * Looking for 's' after a digit may cause false positives in
  12699. * "my24service:8080".
  12700. * Looking from 's' backward if there are only ':' and numbers
  12701. * before will not work for "24service:8080" (non SSL, port 8080)
  12702. * or "24s" (SSL, port 24).
  12703. *
  12704. * Remark: Initially hostnames were not allowed to start with a
  12705. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12706. * Section 2.1).
  12707. *
  12708. * To get this correct, the entire string must be parsed as a whole,
  12709. * reading it as a list element for element and parsing with an
  12710. * algorithm equivalent to parse_port_string.
  12711. *
  12712. * In fact, we use local interface names here, not arbitrary
  12713. * hostnames, so in most cases the only name will be "localhost".
  12714. *
  12715. * So, for now, we use this simple algorithm, that may still return
  12716. * a false positive in bizarre cases.
  12717. */
  12718. int i;
  12719. int portslen = (int)strlen(ports);
  12720. char prevIsNumber = 0;
  12721. for (i = 0; i < portslen; i++) {
  12722. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12723. return 1;
  12724. }
  12725. if (ports[i] >= '0' && ports[i] <= '9') {
  12726. prevIsNumber = 1;
  12727. } else {
  12728. prevIsNumber = 0;
  12729. }
  12730. }
  12731. }
  12732. return 0;
  12733. }
  12734. static int
  12735. set_ports_option(struct mg_context *phys_ctx)
  12736. {
  12737. const char *list;
  12738. int on = 1;
  12739. #if defined(USE_IPV6)
  12740. int off = 0;
  12741. #endif
  12742. struct vec vec;
  12743. struct socket so, *ptr;
  12744. struct mg_pollfd *pfd;
  12745. union usa usa;
  12746. socklen_t len;
  12747. int ip_version;
  12748. int portsTotal = 0;
  12749. int portsOk = 0;
  12750. const char *opt_txt;
  12751. long opt_listen_backlog;
  12752. if (!phys_ctx) {
  12753. return 0;
  12754. }
  12755. memset(&so, 0, sizeof(so));
  12756. memset(&usa, 0, sizeof(usa));
  12757. len = sizeof(usa);
  12758. list = phys_ctx->dd.config[LISTENING_PORTS];
  12759. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12760. portsTotal++;
  12761. if (!parse_port_string(&vec, &so, &ip_version)) {
  12762. mg_cry_ctx_internal(
  12763. phys_ctx,
  12764. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12765. (int)vec.len,
  12766. vec.ptr,
  12767. portsTotal,
  12768. "[IP_ADDRESS:]PORT[s|r]");
  12769. continue;
  12770. }
  12771. #if !defined(NO_SSL)
  12772. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12773. mg_cry_ctx_internal(phys_ctx,
  12774. "Cannot add SSL socket (entry %i)",
  12775. portsTotal);
  12776. continue;
  12777. }
  12778. #endif
  12779. /* Create socket. */
  12780. /* For a list of protocol numbers (e.g., TCP==6) see:
  12781. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  12782. */
  12783. if ((so.sock =
  12784. socket(so.lsa.sa.sa_family,
  12785. SOCK_STREAM,
  12786. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  12787. == INVALID_SOCKET) {
  12788. mg_cry_ctx_internal(phys_ctx,
  12789. "cannot create socket (entry %i)",
  12790. portsTotal);
  12791. continue;
  12792. }
  12793. #if defined(_WIN32)
  12794. /* Windows SO_REUSEADDR lets many procs binds to a
  12795. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12796. * if someone already has the socket -- DTL */
  12797. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12798. * Windows might need a few seconds before
  12799. * the same port can be used again in the
  12800. * same process, so a short Sleep may be
  12801. * required between mg_stop and mg_start.
  12802. */
  12803. if (setsockopt(so.sock,
  12804. SOL_SOCKET,
  12805. SO_EXCLUSIVEADDRUSE,
  12806. (SOCK_OPT_TYPE)&on,
  12807. sizeof(on))
  12808. != 0) {
  12809. /* Set reuse option, but don't abort on errors. */
  12810. mg_cry_ctx_internal(
  12811. phys_ctx,
  12812. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12813. portsTotal);
  12814. }
  12815. #else
  12816. if (setsockopt(so.sock,
  12817. SOL_SOCKET,
  12818. SO_REUSEADDR,
  12819. (SOCK_OPT_TYPE)&on,
  12820. sizeof(on))
  12821. != 0) {
  12822. /* Set reuse option, but don't abort on errors. */
  12823. mg_cry_ctx_internal(
  12824. phys_ctx,
  12825. "cannot set socket option SO_REUSEADDR (entry %i)",
  12826. portsTotal);
  12827. }
  12828. #endif
  12829. #if defined(USE_X_DOM_SOCKET)
  12830. if (ip_version == 99) {
  12831. /* Unix domain socket */
  12832. } else
  12833. #endif
  12834. if (ip_version > 4) {
  12835. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12836. #if defined(USE_IPV6)
  12837. if (ip_version > 6) {
  12838. if (so.lsa.sa.sa_family == AF_INET6
  12839. && setsockopt(so.sock,
  12840. IPPROTO_IPV6,
  12841. IPV6_V6ONLY,
  12842. (void *)&off,
  12843. sizeof(off))
  12844. != 0) {
  12845. /* Set IPv6 only option, but don't abort on errors. */
  12846. mg_cry_ctx_internal(phys_ctx,
  12847. "cannot set socket option "
  12848. "IPV6_V6ONLY=off (entry %i)",
  12849. portsTotal);
  12850. }
  12851. } else {
  12852. if (so.lsa.sa.sa_family == AF_INET6
  12853. && setsockopt(so.sock,
  12854. IPPROTO_IPV6,
  12855. IPV6_V6ONLY,
  12856. (void *)&on,
  12857. sizeof(on))
  12858. != 0) {
  12859. /* Set IPv6 only option, but don't abort on errors. */
  12860. mg_cry_ctx_internal(phys_ctx,
  12861. "cannot set socket option "
  12862. "IPV6_V6ONLY=on (entry %i)",
  12863. portsTotal);
  12864. }
  12865. }
  12866. #else
  12867. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12868. closesocket(so.sock);
  12869. so.sock = INVALID_SOCKET;
  12870. continue;
  12871. #endif
  12872. }
  12873. if (so.lsa.sa.sa_family == AF_INET) {
  12874. len = sizeof(so.lsa.sin);
  12875. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12876. mg_cry_ctx_internal(phys_ctx,
  12877. "cannot bind to %.*s: %d (%s)",
  12878. (int)vec.len,
  12879. vec.ptr,
  12880. (int)ERRNO,
  12881. strerror(errno));
  12882. closesocket(so.sock);
  12883. so.sock = INVALID_SOCKET;
  12884. continue;
  12885. }
  12886. }
  12887. #if defined(USE_IPV6)
  12888. else if (so.lsa.sa.sa_family == AF_INET6) {
  12889. len = sizeof(so.lsa.sin6);
  12890. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12891. mg_cry_ctx_internal(phys_ctx,
  12892. "cannot bind to IPv6 %.*s: %d (%s)",
  12893. (int)vec.len,
  12894. vec.ptr,
  12895. (int)ERRNO,
  12896. strerror(errno));
  12897. closesocket(so.sock);
  12898. so.sock = INVALID_SOCKET;
  12899. continue;
  12900. }
  12901. }
  12902. #endif
  12903. #if defined(USE_X_DOM_SOCKET)
  12904. else if (so.lsa.sa.sa_family == AF_UNIX) {
  12905. len = sizeof(so.lsa.sun);
  12906. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12907. mg_cry_ctx_internal(phys_ctx,
  12908. "cannot bind to unix socket %s: %d (%s)",
  12909. so.lsa.sun.sun_path,
  12910. (int)ERRNO,
  12911. strerror(errno));
  12912. closesocket(so.sock);
  12913. so.sock = INVALID_SOCKET;
  12914. continue;
  12915. }
  12916. }
  12917. #endif
  12918. else {
  12919. mg_cry_ctx_internal(
  12920. phys_ctx,
  12921. "cannot bind: address family not supported (entry %i)",
  12922. portsTotal);
  12923. closesocket(so.sock);
  12924. so.sock = INVALID_SOCKET;
  12925. continue;
  12926. }
  12927. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  12928. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  12929. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  12930. mg_cry_ctx_internal(phys_ctx,
  12931. "%s value \"%s\" is invalid",
  12932. config_options[LISTEN_BACKLOG_SIZE].name,
  12933. opt_txt);
  12934. closesocket(so.sock);
  12935. so.sock = INVALID_SOCKET;
  12936. continue;
  12937. }
  12938. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  12939. mg_cry_ctx_internal(phys_ctx,
  12940. "cannot listen to %.*s: %d (%s)",
  12941. (int)vec.len,
  12942. vec.ptr,
  12943. (int)ERRNO,
  12944. strerror(errno));
  12945. closesocket(so.sock);
  12946. so.sock = INVALID_SOCKET;
  12947. continue;
  12948. }
  12949. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12950. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12951. int err = (int)ERRNO;
  12952. mg_cry_ctx_internal(phys_ctx,
  12953. "call to getsockname failed %.*s: %d (%s)",
  12954. (int)vec.len,
  12955. vec.ptr,
  12956. err,
  12957. strerror(errno));
  12958. closesocket(so.sock);
  12959. so.sock = INVALID_SOCKET;
  12960. continue;
  12961. }
  12962. /* Update lsa port in case of random free ports */
  12963. #if defined(USE_IPV6)
  12964. if (so.lsa.sa.sa_family == AF_INET6) {
  12965. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12966. } else
  12967. #endif
  12968. {
  12969. so.lsa.sin.sin_port = usa.sin.sin_port;
  12970. }
  12971. if ((ptr = (struct socket *)
  12972. mg_realloc_ctx(phys_ctx->listening_sockets,
  12973. (phys_ctx->num_listening_sockets + 1)
  12974. * sizeof(phys_ctx->listening_sockets[0]),
  12975. phys_ctx))
  12976. == NULL) {
  12977. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12978. closesocket(so.sock);
  12979. so.sock = INVALID_SOCKET;
  12980. continue;
  12981. }
  12982. if ((pfd = (struct mg_pollfd *)
  12983. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12984. (phys_ctx->num_listening_sockets + 1)
  12985. * sizeof(phys_ctx->listening_socket_fds[0]),
  12986. phys_ctx))
  12987. == NULL) {
  12988. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12989. closesocket(so.sock);
  12990. so.sock = INVALID_SOCKET;
  12991. mg_free(ptr);
  12992. continue;
  12993. }
  12994. set_close_on_exec(so.sock, NULL, phys_ctx);
  12995. phys_ctx->listening_sockets = ptr;
  12996. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12997. phys_ctx->listening_socket_fds = pfd;
  12998. phys_ctx->num_listening_sockets++;
  12999. portsOk++;
  13000. }
  13001. if (portsOk != portsTotal) {
  13002. close_all_listening_sockets(phys_ctx);
  13003. portsOk = 0;
  13004. }
  13005. return portsOk;
  13006. }
  13007. static const char *
  13008. header_val(const struct mg_connection *conn, const char *header)
  13009. {
  13010. const char *header_value;
  13011. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13012. return "-";
  13013. } else {
  13014. return header_value;
  13015. }
  13016. }
  13017. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13018. #include "external_log_access.inl"
  13019. #elif !defined(NO_FILESYSTEMS)
  13020. static void
  13021. log_access(const struct mg_connection *conn)
  13022. {
  13023. const struct mg_request_info *ri;
  13024. struct mg_file fi;
  13025. char date[64], src_addr[IP_ADDR_STR_LEN];
  13026. struct tm *tm;
  13027. const char *referer;
  13028. const char *user_agent;
  13029. char log_buf[4096];
  13030. if (!conn || !conn->dom_ctx) {
  13031. return;
  13032. }
  13033. /* Set log message to "empty" */
  13034. log_buf[0] = 0;
  13035. #if defined(USE_LUA)
  13036. if (conn->phys_ctx->lua_bg_log_available) {
  13037. int ret;
  13038. struct mg_context *ctx = conn->phys_ctx;
  13039. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13040. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13041. /* call "log()" in Lua */
  13042. lua_getglobal(lstate, "log");
  13043. prepare_lua_request_info_inner(conn, lstate);
  13044. push_lua_response_log_data(conn, lstate);
  13045. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13046. if (ret == 0) {
  13047. int t = lua_type(lstate, -1);
  13048. if (t == LUA_TBOOLEAN) {
  13049. if (lua_toboolean(lstate, -1) == 0) {
  13050. /* log() returned false: do not log */
  13051. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13052. return;
  13053. }
  13054. /* log returned true: continue logging */
  13055. } else if (t == LUA_TSTRING) {
  13056. size_t len;
  13057. const char *txt = lua_tolstring(lstate, -1, &len);
  13058. if ((len == 0) || (*txt == 0)) {
  13059. /* log() returned empty string: do not log */
  13060. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13061. return;
  13062. }
  13063. /* Copy test from Lua into log_buf */
  13064. if (len >= sizeof(log_buf)) {
  13065. len = sizeof(log_buf) - 1;
  13066. }
  13067. memcpy(log_buf, txt, len);
  13068. log_buf[len] = 0;
  13069. }
  13070. } else {
  13071. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13072. }
  13073. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13074. }
  13075. #endif
  13076. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13077. if (mg_fopen(conn,
  13078. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13079. MG_FOPEN_MODE_APPEND,
  13080. &fi)
  13081. == 0) {
  13082. fi.access.fp = NULL;
  13083. }
  13084. } else {
  13085. fi.access.fp = NULL;
  13086. }
  13087. /* Log is written to a file and/or a callback. If both are not set,
  13088. * executing the rest of the function is pointless. */
  13089. if ((fi.access.fp == NULL)
  13090. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13091. return;
  13092. }
  13093. /* If we did not get a log message from Lua, create it here. */
  13094. if (!log_buf[0]) {
  13095. tm = localtime(&conn->conn_birth_time);
  13096. if (tm != NULL) {
  13097. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13098. } else {
  13099. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13100. date[sizeof(date) - 1] = '\0';
  13101. }
  13102. ri = &conn->request_info;
  13103. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13104. referer = header_val(conn, "Referer");
  13105. user_agent = header_val(conn, "User-Agent");
  13106. mg_snprintf(conn,
  13107. NULL, /* Ignore truncation in access log */
  13108. log_buf,
  13109. sizeof(log_buf),
  13110. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13111. " %s %s",
  13112. src_addr,
  13113. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13114. date,
  13115. ri->request_method ? ri->request_method : "-",
  13116. ri->request_uri ? ri->request_uri : "-",
  13117. ri->query_string ? "?" : "",
  13118. ri->query_string ? ri->query_string : "",
  13119. ri->http_version,
  13120. conn->status_code,
  13121. conn->num_bytes_sent,
  13122. referer,
  13123. user_agent);
  13124. }
  13125. /* Here we have a log message in log_buf. Call the callback */
  13126. if (conn->phys_ctx->callbacks.log_access) {
  13127. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13128. /* do not log if callack returns non-zero */
  13129. if (fi.access.fp) {
  13130. mg_fclose(&fi.access);
  13131. }
  13132. return;
  13133. }
  13134. }
  13135. /* Store in file */
  13136. if (fi.access.fp) {
  13137. int ok = 1;
  13138. flockfile(fi.access.fp);
  13139. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13140. ok = 0;
  13141. }
  13142. if (fflush(fi.access.fp) != 0) {
  13143. ok = 0;
  13144. }
  13145. funlockfile(fi.access.fp);
  13146. if (mg_fclose(&fi.access) != 0) {
  13147. ok = 0;
  13148. }
  13149. if (!ok) {
  13150. mg_cry_internal(conn,
  13151. "Error writing log file %s",
  13152. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13153. }
  13154. }
  13155. }
  13156. #else
  13157. #error "Either enable filesystems or provide a custom log_access implementation"
  13158. #endif /* Externally provided function */
  13159. /* Verify given socket address against the ACL.
  13160. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13161. */
  13162. static int
  13163. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13164. {
  13165. int allowed, flag, matched;
  13166. struct vec vec;
  13167. if (phys_ctx) {
  13168. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13169. /* If any ACL is set, deny by default */
  13170. allowed = (list == NULL) ? '+' : '-';
  13171. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13172. flag = vec.ptr[0];
  13173. matched = -1;
  13174. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13175. vec.ptr++;
  13176. vec.len--;
  13177. matched = parse_match_net(&vec, sa, 1);
  13178. }
  13179. if (matched < 0) {
  13180. mg_cry_ctx_internal(phys_ctx,
  13181. "%s: subnet must be [+|-]IP-addr[/x]",
  13182. __func__);
  13183. return -1;
  13184. }
  13185. if (matched) {
  13186. allowed = flag;
  13187. }
  13188. }
  13189. return allowed == '+';
  13190. }
  13191. return -1;
  13192. }
  13193. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13194. static int
  13195. set_uid_option(struct mg_context *phys_ctx)
  13196. {
  13197. int success = 0;
  13198. if (phys_ctx) {
  13199. /* We are currently running as curr_uid. */
  13200. const uid_t curr_uid = getuid();
  13201. /* If set, we want to run as run_as_user. */
  13202. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13203. const struct passwd *to_pw = NULL;
  13204. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13205. /* run_as_user does not exist on the system. We can't proceed
  13206. * further. */
  13207. mg_cry_ctx_internal(phys_ctx,
  13208. "%s: unknown user [%s]",
  13209. __func__,
  13210. run_as_user);
  13211. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13212. /* There was either no request to change user, or we're already
  13213. * running as run_as_user. Nothing else to do.
  13214. */
  13215. success = 1;
  13216. } else {
  13217. /* Valid change request. */
  13218. if (setgid(to_pw->pw_gid) == -1) {
  13219. mg_cry_ctx_internal(phys_ctx,
  13220. "%s: setgid(%s): %s",
  13221. __func__,
  13222. run_as_user,
  13223. strerror(errno));
  13224. } else if (setgroups(0, NULL) == -1) {
  13225. mg_cry_ctx_internal(phys_ctx,
  13226. "%s: setgroups(): %s",
  13227. __func__,
  13228. strerror(errno));
  13229. } else if (setuid(to_pw->pw_uid) == -1) {
  13230. mg_cry_ctx_internal(phys_ctx,
  13231. "%s: setuid(%s): %s",
  13232. __func__,
  13233. run_as_user,
  13234. strerror(errno));
  13235. } else {
  13236. success = 1;
  13237. }
  13238. }
  13239. }
  13240. return success;
  13241. }
  13242. #endif /* !_WIN32 */
  13243. static void
  13244. tls_dtor(void *key)
  13245. {
  13246. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13247. /* key == pthread_getspecific(sTlsKey); */
  13248. if (tls) {
  13249. if (tls->is_master == 2) {
  13250. tls->is_master = -3; /* Mark memory as dead */
  13251. mg_free(tls);
  13252. }
  13253. }
  13254. pthread_setspecific(sTlsKey, NULL);
  13255. }
  13256. #if defined(USE_MBEDTLS)
  13257. /* Check if SSL is required.
  13258. * If so, set up ctx->ssl_ctx pointer. */
  13259. static int
  13260. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13261. {
  13262. if (!phys_ctx) {
  13263. return 0;
  13264. }
  13265. if (!dom_ctx) {
  13266. dom_ctx = &(phys_ctx->dd);
  13267. }
  13268. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13269. /* No SSL port is set. No need to setup SSL. */
  13270. return 1;
  13271. }
  13272. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13273. if (dom_ctx->ssl_ctx == NULL) {
  13274. fprintf(stderr, "ssl_ctx malloc failed\n");
  13275. return 0;
  13276. }
  13277. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13278. == 0
  13279. ? 1
  13280. : 0;
  13281. }
  13282. #elif !defined(NO_SSL)
  13283. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13284. struct mg_domain_context *dom_ctx,
  13285. const char *pem,
  13286. const char *chain);
  13287. static const char *ssl_error(void);
  13288. static int
  13289. refresh_trust(struct mg_connection *conn)
  13290. {
  13291. struct stat cert_buf;
  13292. int64_t t = 0;
  13293. const char *pem;
  13294. const char *chain;
  13295. int should_verify_peer;
  13296. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13297. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13298. * refresh_trust still can not work. */
  13299. return 0;
  13300. }
  13301. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13302. if (chain == NULL) {
  13303. /* pem is not NULL here */
  13304. chain = pem;
  13305. }
  13306. if (*chain == 0) {
  13307. chain = NULL;
  13308. }
  13309. if (stat(pem, &cert_buf) != -1) {
  13310. t = (int64_t)cert_buf.st_mtime;
  13311. }
  13312. mg_lock_context(conn->phys_ctx);
  13313. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13314. conn->dom_ctx->ssl_cert_last_mtime = t;
  13315. should_verify_peer = 0;
  13316. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13317. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13318. == 0) {
  13319. should_verify_peer = 1;
  13320. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13321. "optional")
  13322. == 0) {
  13323. should_verify_peer = 1;
  13324. }
  13325. }
  13326. if (should_verify_peer) {
  13327. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13328. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13329. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13330. ca_file,
  13331. ca_path)
  13332. != 1) {
  13333. mg_unlock_context(conn->phys_ctx);
  13334. mg_cry_ctx_internal(
  13335. conn->phys_ctx,
  13336. "SSL_CTX_load_verify_locations error: %s "
  13337. "ssl_verify_peer requires setting "
  13338. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13339. "present in "
  13340. "the .conf file?",
  13341. ssl_error());
  13342. return 0;
  13343. }
  13344. }
  13345. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13346. mg_unlock_context(conn->phys_ctx);
  13347. return 0;
  13348. }
  13349. }
  13350. mg_unlock_context(conn->phys_ctx);
  13351. return 1;
  13352. }
  13353. #if defined(OPENSSL_API_1_1)
  13354. #else
  13355. static pthread_mutex_t *ssl_mutexes;
  13356. #endif /* OPENSSL_API_1_1 */
  13357. static int
  13358. sslize(struct mg_connection *conn,
  13359. int (*func)(SSL *),
  13360. const struct mg_client_options *client_options)
  13361. {
  13362. int ret, err;
  13363. int short_trust;
  13364. unsigned timeout = 1024;
  13365. unsigned i;
  13366. if (!conn) {
  13367. return 0;
  13368. }
  13369. short_trust =
  13370. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13371. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13372. if (short_trust) {
  13373. int trust_ret = refresh_trust(conn);
  13374. if (!trust_ret) {
  13375. return trust_ret;
  13376. }
  13377. }
  13378. mg_lock_context(conn->phys_ctx);
  13379. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13380. mg_unlock_context(conn->phys_ctx);
  13381. if (conn->ssl == NULL) {
  13382. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13383. OPENSSL_REMOVE_THREAD_STATE();
  13384. return 0;
  13385. }
  13386. SSL_set_app_data(conn->ssl, (char *)conn);
  13387. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13388. if (ret != 1) {
  13389. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13390. SSL_free(conn->ssl);
  13391. conn->ssl = NULL;
  13392. OPENSSL_REMOVE_THREAD_STATE();
  13393. return 0;
  13394. }
  13395. if (client_options) {
  13396. if (client_options->host_name) {
  13397. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13398. }
  13399. }
  13400. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13401. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13402. /* NOTE: The loop below acts as a back-off, so we can end
  13403. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13404. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13405. if (to >= 0) {
  13406. timeout = (unsigned)to;
  13407. }
  13408. }
  13409. /* SSL functions may fail and require to be called again:
  13410. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13411. * Here "func" could be SSL_connect or SSL_accept. */
  13412. for (i = 0; i <= timeout; i += 50) {
  13413. ERR_clear_error();
  13414. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13415. ret = func(conn->ssl);
  13416. if (ret != 1) {
  13417. err = SSL_get_error(conn->ssl, ret);
  13418. if ((err == SSL_ERROR_WANT_CONNECT)
  13419. || (err == SSL_ERROR_WANT_ACCEPT)
  13420. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13421. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13422. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13423. /* Don't wait if the server is going to be stopped. */
  13424. break;
  13425. }
  13426. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13427. /* Simply retry the function call. */
  13428. mg_sleep(50);
  13429. } else {
  13430. /* Need to retry the function call "later".
  13431. * See https://linux.die.net/man/3/ssl_get_error
  13432. * This is typical for non-blocking sockets. */
  13433. struct mg_pollfd pfd;
  13434. int pollres;
  13435. pfd.fd = conn->client.sock;
  13436. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13437. || (err == SSL_ERROR_WANT_WRITE))
  13438. ? POLLOUT
  13439. : POLLIN;
  13440. pollres =
  13441. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13442. if (pollres < 0) {
  13443. /* Break if error occured (-1)
  13444. * or server shutdown (-2) */
  13445. break;
  13446. }
  13447. }
  13448. } else if (err == SSL_ERROR_SYSCALL) {
  13449. /* This is an IO error. Look at errno. */
  13450. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13451. break;
  13452. } else {
  13453. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13454. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13455. break;
  13456. }
  13457. } else {
  13458. /* success */
  13459. break;
  13460. }
  13461. }
  13462. ERR_clear_error();
  13463. if (ret != 1) {
  13464. SSL_free(conn->ssl);
  13465. conn->ssl = NULL;
  13466. OPENSSL_REMOVE_THREAD_STATE();
  13467. return 0;
  13468. }
  13469. return 1;
  13470. }
  13471. /* Return OpenSSL error message (from CRYPTO lib) */
  13472. static const char *
  13473. ssl_error(void)
  13474. {
  13475. unsigned long err;
  13476. err = ERR_get_error();
  13477. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13478. }
  13479. static int
  13480. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13481. {
  13482. int i;
  13483. const char hexdigit[] = "0123456789abcdef";
  13484. if ((memlen <= 0) || (buflen <= 0)) {
  13485. return 0;
  13486. }
  13487. if (buflen < (3 * memlen)) {
  13488. return 0;
  13489. }
  13490. for (i = 0; i < memlen; i++) {
  13491. if (i > 0) {
  13492. buf[3 * i - 1] = ' ';
  13493. }
  13494. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13495. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13496. }
  13497. buf[3 * memlen - 1] = 0;
  13498. return 1;
  13499. }
  13500. static int
  13501. ssl_get_client_cert_info(const struct mg_connection *conn,
  13502. struct mg_client_cert *client_cert)
  13503. {
  13504. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13505. if (cert) {
  13506. char str_buf[1024];
  13507. unsigned char buf[256];
  13508. char *str_serial = NULL;
  13509. unsigned int ulen;
  13510. int ilen;
  13511. unsigned char *tmp_buf;
  13512. unsigned char *tmp_p;
  13513. /* Handle to algorithm used for fingerprint */
  13514. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13515. /* Get Subject and issuer */
  13516. X509_NAME *subj = X509_get_subject_name(cert);
  13517. X509_NAME *iss = X509_get_issuer_name(cert);
  13518. /* Get serial number */
  13519. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13520. /* Translate serial number to a hex string */
  13521. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13522. if (serial_bn) {
  13523. str_serial = BN_bn2hex(serial_bn);
  13524. BN_free(serial_bn);
  13525. }
  13526. client_cert->serial =
  13527. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13528. /* Translate subject and issuer to a string */
  13529. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13530. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13531. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13532. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13533. /* Calculate SHA1 fingerprint and store as a hex string */
  13534. ulen = 0;
  13535. /* ASN1_digest is deprecated. Do the calculation manually,
  13536. * using EVP_Digest. */
  13537. ilen = i2d_X509(cert, NULL);
  13538. tmp_buf = (ilen > 0)
  13539. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13540. conn->phys_ctx)
  13541. : NULL;
  13542. if (tmp_buf) {
  13543. tmp_p = tmp_buf;
  13544. (void)i2d_X509(cert, &tmp_p);
  13545. if (!EVP_Digest(
  13546. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13547. ulen = 0;
  13548. }
  13549. mg_free(tmp_buf);
  13550. }
  13551. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13552. *str_buf = 0;
  13553. }
  13554. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13555. client_cert->peer_cert = (void *)cert;
  13556. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13557. * see https://linux.die.net/man/3/bn_bn2hex */
  13558. OPENSSL_free(str_serial);
  13559. return 1;
  13560. }
  13561. return 0;
  13562. }
  13563. #if defined(OPENSSL_API_1_1)
  13564. #else
  13565. static void
  13566. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13567. {
  13568. (void)line;
  13569. (void)file;
  13570. if (mode & 1) {
  13571. /* 1 is CRYPTO_LOCK */
  13572. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13573. } else {
  13574. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13575. }
  13576. }
  13577. #endif /* OPENSSL_API_1_1 */
  13578. #if !defined(NO_SSL_DL)
  13579. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13580. static void *
  13581. load_tls_dll(char *ebuf,
  13582. size_t ebuf_len,
  13583. const char *dll_name,
  13584. struct ssl_func *sw,
  13585. int *feature_missing)
  13586. {
  13587. union {
  13588. void *p;
  13589. void (*fp)(void);
  13590. } u;
  13591. void *dll_handle;
  13592. struct ssl_func *fp;
  13593. int ok;
  13594. int truncated = 0;
  13595. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13596. mg_snprintf(NULL,
  13597. NULL, /* No truncation check for ebuf */
  13598. ebuf,
  13599. ebuf_len,
  13600. "%s: cannot load %s",
  13601. __func__,
  13602. dll_name);
  13603. return NULL;
  13604. }
  13605. ok = 1;
  13606. for (fp = sw; fp->name != NULL; fp++) {
  13607. #if defined(_WIN32)
  13608. /* GetProcAddress() returns pointer to function */
  13609. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13610. #else
  13611. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13612. * pointers to function pointers. We need to use a union to make a
  13613. * cast. */
  13614. u.p = dlsym(dll_handle, fp->name);
  13615. #endif /* _WIN32 */
  13616. /* Set pointer (might be NULL) */
  13617. fp->ptr = u.fp;
  13618. if (u.fp == NULL) {
  13619. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13620. if (feature_missing) {
  13621. feature_missing[fp->required]++;
  13622. }
  13623. if (fp->required == TLS_Mandatory) {
  13624. /* Mandatory function is missing */
  13625. if (ok) {
  13626. /* This is the first missing function.
  13627. * Create a new error message. */
  13628. mg_snprintf(NULL,
  13629. &truncated,
  13630. ebuf,
  13631. ebuf_len,
  13632. "%s: %s: cannot find %s",
  13633. __func__,
  13634. dll_name,
  13635. fp->name);
  13636. ok = 0;
  13637. } else {
  13638. /* This is yet anothermissing function.
  13639. * Append existing error message. */
  13640. size_t cur_len = strlen(ebuf);
  13641. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13642. mg_snprintf(NULL,
  13643. &truncated,
  13644. ebuf + cur_len,
  13645. ebuf_len - cur_len - 3,
  13646. ", %s",
  13647. fp->name);
  13648. if (truncated) {
  13649. /* If truncated, add "..." */
  13650. strcat(ebuf, "...");
  13651. }
  13652. }
  13653. }
  13654. }
  13655. }
  13656. }
  13657. if (!ok) {
  13658. (void)dlclose(dll_handle);
  13659. return NULL;
  13660. }
  13661. return dll_handle;
  13662. }
  13663. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13664. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13665. #endif /* NO_SSL_DL */
  13666. #if defined(SSL_ALREADY_INITIALIZED)
  13667. static volatile ptrdiff_t cryptolib_users =
  13668. 1; /* Reference counter for crypto library. */
  13669. #else
  13670. static volatile ptrdiff_t cryptolib_users =
  13671. 0; /* Reference counter for crypto library. */
  13672. #endif
  13673. static int
  13674. initialize_openssl(char *ebuf, size_t ebuf_len)
  13675. {
  13676. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13677. int i, num_locks;
  13678. size_t size;
  13679. #endif
  13680. if (ebuf_len > 0) {
  13681. ebuf[0] = 0;
  13682. }
  13683. #if !defined(NO_SSL_DL)
  13684. if (!cryptolib_dll_handle) {
  13685. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13686. cryptolib_dll_handle = load_tls_dll(
  13687. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13688. if (!cryptolib_dll_handle) {
  13689. mg_snprintf(NULL,
  13690. NULL, /* No truncation check for ebuf */
  13691. ebuf,
  13692. ebuf_len,
  13693. "%s: error loading library %s",
  13694. __func__,
  13695. CRYPTO_LIB);
  13696. DEBUG_TRACE("%s", ebuf);
  13697. return 0;
  13698. }
  13699. }
  13700. #endif /* NO_SSL_DL */
  13701. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13702. return 1;
  13703. }
  13704. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13705. /* Initialize locking callbacks, needed for thread safety.
  13706. * http://www.openssl.org/support/faq.html#PROG1
  13707. */
  13708. num_locks = CRYPTO_num_locks();
  13709. if (num_locks < 0) {
  13710. num_locks = 0;
  13711. }
  13712. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13713. /* allocate mutex array, if required */
  13714. if (num_locks == 0) {
  13715. /* No mutex array required */
  13716. ssl_mutexes = NULL;
  13717. } else {
  13718. /* Mutex array required - allocate it */
  13719. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13720. /* Check OOM */
  13721. if (ssl_mutexes == NULL) {
  13722. mg_snprintf(NULL,
  13723. NULL, /* No truncation check for ebuf */
  13724. ebuf,
  13725. ebuf_len,
  13726. "%s: cannot allocate mutexes: %s",
  13727. __func__,
  13728. ssl_error());
  13729. DEBUG_TRACE("%s", ebuf);
  13730. return 0;
  13731. }
  13732. /* initialize mutex array */
  13733. for (i = 0; i < num_locks; i++) {
  13734. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13735. mg_snprintf(NULL,
  13736. NULL, /* No truncation check for ebuf */
  13737. ebuf,
  13738. ebuf_len,
  13739. "%s: error initializing mutex %i of %i",
  13740. __func__,
  13741. i,
  13742. num_locks);
  13743. DEBUG_TRACE("%s", ebuf);
  13744. mg_free(ssl_mutexes);
  13745. return 0;
  13746. }
  13747. }
  13748. }
  13749. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13750. CRYPTO_set_id_callback(&mg_current_thread_id);
  13751. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  13752. #if !defined(NO_SSL_DL)
  13753. if (!ssllib_dll_handle) {
  13754. ssllib_dll_handle =
  13755. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13756. if (!ssllib_dll_handle) {
  13757. #if !defined(OPENSSL_API_1_1)
  13758. mg_free(ssl_mutexes);
  13759. #endif
  13760. DEBUG_TRACE("%s", ebuf);
  13761. return 0;
  13762. }
  13763. }
  13764. #endif /* NO_SSL_DL */
  13765. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  13766. /* Initialize SSL library */
  13767. OPENSSL_init_ssl(0, NULL);
  13768. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13769. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13770. NULL);
  13771. #else
  13772. /* Initialize SSL library */
  13773. SSL_library_init();
  13774. SSL_load_error_strings();
  13775. #endif
  13776. return 1;
  13777. }
  13778. static int
  13779. ssl_use_pem_file(struct mg_context *phys_ctx,
  13780. struct mg_domain_context *dom_ctx,
  13781. const char *pem,
  13782. const char *chain)
  13783. {
  13784. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13785. mg_cry_ctx_internal(phys_ctx,
  13786. "%s: cannot open certificate file %s: %s",
  13787. __func__,
  13788. pem,
  13789. ssl_error());
  13790. return 0;
  13791. }
  13792. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13793. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13794. mg_cry_ctx_internal(phys_ctx,
  13795. "%s: cannot open private key file %s: %s",
  13796. __func__,
  13797. pem,
  13798. ssl_error());
  13799. return 0;
  13800. }
  13801. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13802. mg_cry_ctx_internal(phys_ctx,
  13803. "%s: certificate and private key do not match: %s",
  13804. __func__,
  13805. pem);
  13806. return 0;
  13807. }
  13808. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13809. * chain files that contain private keys and certificates in
  13810. * SSL_CTX_use_certificate_chain_file.
  13811. * The CivetWeb-Server used pem-Files that contained both information.
  13812. * In order to make wolfSSL work, it is split in two files.
  13813. * One file that contains key and certificate used by the server and
  13814. * an optional chain file for the ssl stack.
  13815. */
  13816. if (chain) {
  13817. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13818. mg_cry_ctx_internal(phys_ctx,
  13819. "%s: cannot use certificate chain file %s: %s",
  13820. __func__,
  13821. chain,
  13822. ssl_error());
  13823. return 0;
  13824. }
  13825. }
  13826. return 1;
  13827. }
  13828. #if defined(OPENSSL_API_1_1)
  13829. static unsigned long
  13830. ssl_get_protocol(int version_id)
  13831. {
  13832. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13833. if (version_id > 0)
  13834. ret |= SSL_OP_NO_SSLv2;
  13835. if (version_id > 1)
  13836. ret |= SSL_OP_NO_SSLv3;
  13837. if (version_id > 2)
  13838. ret |= SSL_OP_NO_TLSv1;
  13839. if (version_id > 3)
  13840. ret |= SSL_OP_NO_TLSv1_1;
  13841. if (version_id > 4)
  13842. ret |= SSL_OP_NO_TLSv1_2;
  13843. #if defined(SSL_OP_NO_TLSv1_3)
  13844. if (version_id > 5)
  13845. ret |= SSL_OP_NO_TLSv1_3;
  13846. #endif
  13847. return ret;
  13848. }
  13849. #else
  13850. static long
  13851. ssl_get_protocol(int version_id)
  13852. {
  13853. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13854. if (version_id > 0)
  13855. ret |= SSL_OP_NO_SSLv2;
  13856. if (version_id > 1)
  13857. ret |= SSL_OP_NO_SSLv3;
  13858. if (version_id > 2)
  13859. ret |= SSL_OP_NO_TLSv1;
  13860. if (version_id > 3)
  13861. ret |= SSL_OP_NO_TLSv1_1;
  13862. if (version_id > 4)
  13863. ret |= SSL_OP_NO_TLSv1_2;
  13864. #if defined(SSL_OP_NO_TLSv1_3)
  13865. if (version_id > 5)
  13866. ret |= SSL_OP_NO_TLSv1_3;
  13867. #endif
  13868. return (long)ret;
  13869. }
  13870. #endif /* OPENSSL_API_1_1 */
  13871. /* SSL callback documentation:
  13872. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13873. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13874. * https://linux.die.net/man/3/ssl_set_info_callback */
  13875. /* Note: There is no "const" for the first argument in the documentation
  13876. * examples, however some (maybe most, but not all) headers of OpenSSL
  13877. * versions / OpenSSL compatibility layers have it. Having a different
  13878. * definition will cause a warning in C and an error in C++. Use "const SSL
  13879. * *", while automatical conversion from "SSL *" works for all compilers,
  13880. * but not other way around */
  13881. static void
  13882. ssl_info_callback(const SSL *ssl, int what, int ret)
  13883. {
  13884. (void)ret;
  13885. if (what & SSL_CB_HANDSHAKE_START) {
  13886. SSL_get_app_data(ssl);
  13887. }
  13888. if (what & SSL_CB_HANDSHAKE_DONE) {
  13889. /* TODO: check for openSSL 1.1 */
  13890. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13891. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13892. }
  13893. }
  13894. static int
  13895. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13896. {
  13897. #if defined(GCC_DIAGNOSTIC)
  13898. #pragma GCC diagnostic push
  13899. #pragma GCC diagnostic ignored "-Wcast-align"
  13900. #endif /* defined(GCC_DIAGNOSTIC) */
  13901. /* We used an aligned pointer in SSL_set_app_data */
  13902. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13903. #if defined(GCC_DIAGNOSTIC)
  13904. #pragma GCC diagnostic pop
  13905. #endif /* defined(GCC_DIAGNOSTIC) */
  13906. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13907. (void)ad;
  13908. (void)arg;
  13909. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13910. DEBUG_ASSERT(0);
  13911. return SSL_TLSEXT_ERR_NOACK;
  13912. }
  13913. conn->dom_ctx = &(conn->phys_ctx->dd);
  13914. /* Old clients (Win XP) will not support SNI. Then, there
  13915. * is no server name available in the request - we can
  13916. * only work with the default certificate.
  13917. * Multiple HTTPS hosts on one IP+port are only possible
  13918. * with a certificate containing all alternative names.
  13919. */
  13920. if ((servername == NULL) || (*servername == 0)) {
  13921. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13922. mg_lock_context(conn->phys_ctx);
  13923. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13924. mg_unlock_context(conn->phys_ctx);
  13925. return SSL_TLSEXT_ERR_NOACK;
  13926. }
  13927. DEBUG_TRACE("TLS connection to host %s", servername);
  13928. while (conn->dom_ctx) {
  13929. if (!mg_strcasecmp(servername,
  13930. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  13931. /* Found matching domain */
  13932. DEBUG_TRACE("TLS domain %s found",
  13933. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  13934. break;
  13935. }
  13936. mg_lock_context(conn->phys_ctx);
  13937. conn->dom_ctx = conn->dom_ctx->next;
  13938. mg_unlock_context(conn->phys_ctx);
  13939. }
  13940. if (conn->dom_ctx == NULL) {
  13941. /* Default domain */
  13942. DEBUG_TRACE("TLS default domain %s used",
  13943. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13944. conn->dom_ctx = &(conn->phys_ctx->dd);
  13945. }
  13946. mg_lock_context(conn->phys_ctx);
  13947. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13948. mg_unlock_context(conn->phys_ctx);
  13949. return SSL_TLSEXT_ERR_OK;
  13950. }
  13951. #if defined(USE_ALPN)
  13952. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  13953. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  13954. alpn_proto_list + 3 + 8,
  13955. NULL};
  13956. #if defined(USE_HTTP2)
  13957. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  13958. alpn_proto_list + 3,
  13959. alpn_proto_list + 3 + 8,
  13960. NULL};
  13961. #endif
  13962. static int
  13963. alpn_select_cb(SSL *ssl,
  13964. const unsigned char **out,
  13965. unsigned char *outlen,
  13966. const unsigned char *in,
  13967. unsigned int inlen,
  13968. void *arg)
  13969. {
  13970. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  13971. unsigned int i, j, enable_http2 = 0;
  13972. const char **alpn_proto_order = alpn_proto_order_http1;
  13973. struct mg_workerTLS *tls =
  13974. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  13975. (void)ssl;
  13976. if (tls == NULL) {
  13977. /* Need to store protocol in Thread Local Storage */
  13978. /* If there is no Thread Local Storage, don't use ALPN */
  13979. return SSL_TLSEXT_ERR_NOACK;
  13980. }
  13981. #if defined(USE_HTTP2)
  13982. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  13983. if (enable_http2) {
  13984. alpn_proto_order = alpn_proto_order_http2;
  13985. }
  13986. #endif
  13987. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  13988. /* check all accepted protocols in this order */
  13989. const char *alpn_proto = alpn_proto_order[j];
  13990. /* search input for matching protocol */
  13991. for (i = 0; i < inlen; i++) {
  13992. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  13993. *out = in + i + 1;
  13994. *outlen = in[i];
  13995. tls->alpn_proto = alpn_proto;
  13996. return SSL_TLSEXT_ERR_OK;
  13997. }
  13998. }
  13999. }
  14000. /* Nothing found */
  14001. return SSL_TLSEXT_ERR_NOACK;
  14002. }
  14003. static int
  14004. next_protos_advertised_cb(SSL *ssl,
  14005. const unsigned char **data,
  14006. unsigned int *len,
  14007. void *arg)
  14008. {
  14009. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14010. *data = (const unsigned char *)alpn_proto_list;
  14011. *len = (unsigned int)strlen((const char *)data);
  14012. (void)ssl;
  14013. (void)dom_ctx;
  14014. return SSL_TLSEXT_ERR_OK;
  14015. }
  14016. static int
  14017. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14018. {
  14019. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14020. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14021. (const unsigned char *)alpn_proto_list,
  14022. alpn_len);
  14023. if (ret != 0) {
  14024. mg_cry_ctx_internal(phys_ctx,
  14025. "SSL_CTX_set_alpn_protos error: %s",
  14026. ssl_error());
  14027. }
  14028. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14029. alpn_select_cb,
  14030. (void *)dom_ctx);
  14031. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14032. next_protos_advertised_cb,
  14033. (void *)dom_ctx);
  14034. return ret;
  14035. }
  14036. #endif
  14037. /* Setup SSL CTX as required by CivetWeb */
  14038. static int
  14039. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14040. struct mg_domain_context *dom_ctx,
  14041. const char *pem,
  14042. const char *chain)
  14043. {
  14044. int callback_ret;
  14045. int should_verify_peer;
  14046. int peer_certificate_optional;
  14047. const char *ca_path;
  14048. const char *ca_file;
  14049. int use_default_verify_paths;
  14050. int verify_depth;
  14051. struct timespec now_mt;
  14052. md5_byte_t ssl_context_id[16];
  14053. md5_state_t md5state;
  14054. int protocol_ver;
  14055. int ssl_cache_timeout;
  14056. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14057. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14058. mg_cry_ctx_internal(phys_ctx,
  14059. "SSL_CTX_new (server) error: %s",
  14060. ssl_error());
  14061. return 0;
  14062. }
  14063. #else
  14064. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14065. mg_cry_ctx_internal(phys_ctx,
  14066. "SSL_CTX_new (server) error: %s",
  14067. ssl_error());
  14068. return 0;
  14069. }
  14070. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14071. #if defined(SSL_OP_NO_TLSv1_3)
  14072. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14073. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14074. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14075. | SSL_OP_NO_TLSv1_3);
  14076. #else
  14077. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14078. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14079. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14080. #endif
  14081. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14082. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14083. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14084. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14085. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14086. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14087. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14088. #if defined(SSL_OP_NO_RENEGOTIATION)
  14089. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14090. #endif
  14091. #if !defined(NO_SSL_DL)
  14092. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14093. #endif /* NO_SSL_DL */
  14094. /* In SSL documentation examples callback defined without const
  14095. * specifier 'void (*)(SSL *, int, int)' See:
  14096. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14097. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14098. * But in the source code const SSL is used:
  14099. * 'void (*)(const SSL *, int, int)' See:
  14100. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14101. * Problem about wrong documentation described, but not resolved:
  14102. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14103. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14104. * But when compiled with modern C++ compiler, correct const should be
  14105. * provided
  14106. */
  14107. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14108. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14109. ssl_servername_callback);
  14110. /* If a callback has been specified, call it. */
  14111. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14112. ? 0
  14113. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14114. phys_ctx->user_data));
  14115. /* If callback returns 0, civetweb sets up the SSL certificate.
  14116. * If it returns 1, civetweb assumes the calback already did this.
  14117. * If it returns -1, initializing ssl fails. */
  14118. if (callback_ret < 0) {
  14119. mg_cry_ctx_internal(phys_ctx,
  14120. "SSL callback returned error: %i",
  14121. callback_ret);
  14122. return 0;
  14123. }
  14124. if (callback_ret > 0) {
  14125. /* Callback did everything. */
  14126. return 1;
  14127. }
  14128. /* If a domain callback has been specified, call it. */
  14129. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14130. ? 0
  14131. : (phys_ctx->callbacks.init_ssl_domain(
  14132. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14133. dom_ctx->ssl_ctx,
  14134. phys_ctx->user_data));
  14135. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14136. * If it returns 1, civetweb assumes the calback already did this.
  14137. * If it returns -1, initializing ssl fails. */
  14138. if (callback_ret < 0) {
  14139. mg_cry_ctx_internal(phys_ctx,
  14140. "Domain SSL callback returned error: %i",
  14141. callback_ret);
  14142. return 0;
  14143. }
  14144. if (callback_ret > 0) {
  14145. /* Domain callback did everything. */
  14146. return 1;
  14147. }
  14148. /* Use some combination of start time, domain and port as a SSL
  14149. * context ID. This should be unique on the current machine. */
  14150. md5_init(&md5state);
  14151. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14152. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14153. md5_append(&md5state,
  14154. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14155. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14156. md5_append(&md5state,
  14157. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14158. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14159. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14160. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14161. md5_finish(&md5state, ssl_context_id);
  14162. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14163. (unsigned char *)ssl_context_id,
  14164. sizeof(ssl_context_id));
  14165. if (pem != NULL) {
  14166. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14167. return 0;
  14168. }
  14169. }
  14170. /* Should we support client certificates? */
  14171. /* Default is "no". */
  14172. should_verify_peer = 0;
  14173. peer_certificate_optional = 0;
  14174. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14175. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14176. /* Yes, they are mandatory */
  14177. should_verify_peer = 1;
  14178. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14179. "optional")
  14180. == 0) {
  14181. /* Yes, they are optional */
  14182. should_verify_peer = 1;
  14183. peer_certificate_optional = 1;
  14184. }
  14185. }
  14186. use_default_verify_paths =
  14187. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14188. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14189. == 0);
  14190. if (should_verify_peer) {
  14191. ca_path = dom_ctx->config[SSL_CA_PATH];
  14192. ca_file = dom_ctx->config[SSL_CA_FILE];
  14193. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14194. != 1) {
  14195. mg_cry_ctx_internal(phys_ctx,
  14196. "SSL_CTX_load_verify_locations error: %s "
  14197. "ssl_verify_peer requires setting "
  14198. "either ssl_ca_path or ssl_ca_file. "
  14199. "Is any of them present in the "
  14200. ".conf file?",
  14201. ssl_error());
  14202. return 0;
  14203. }
  14204. if (peer_certificate_optional) {
  14205. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14206. } else {
  14207. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14208. SSL_VERIFY_PEER
  14209. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14210. NULL);
  14211. }
  14212. if (use_default_verify_paths
  14213. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14214. mg_cry_ctx_internal(phys_ctx,
  14215. "SSL_CTX_set_default_verify_paths error: %s",
  14216. ssl_error());
  14217. return 0;
  14218. }
  14219. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14220. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14221. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14222. }
  14223. }
  14224. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14225. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14226. dom_ctx->config[SSL_CIPHER_LIST])
  14227. != 1) {
  14228. mg_cry_ctx_internal(phys_ctx,
  14229. "SSL_CTX_set_cipher_list error: %s",
  14230. ssl_error());
  14231. }
  14232. }
  14233. /* SSL session caching */
  14234. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14235. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14236. : 0);
  14237. if (ssl_cache_timeout > 0) {
  14238. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14239. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14240. * default */
  14241. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14242. }
  14243. #if defined(USE_ALPN)
  14244. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14245. #if !defined(NO_SSL_DL)
  14246. if (!tls_feature_missing[TLS_ALPN])
  14247. #endif
  14248. {
  14249. init_alpn(phys_ctx, dom_ctx);
  14250. }
  14251. #endif
  14252. return 1;
  14253. }
  14254. /* Check if SSL is required.
  14255. * If so, dynamically load SSL library
  14256. * and set up ctx->ssl_ctx pointer. */
  14257. static int
  14258. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14259. {
  14260. void *ssl_ctx = 0;
  14261. int callback_ret;
  14262. const char *pem;
  14263. const char *chain;
  14264. char ebuf[128];
  14265. if (!phys_ctx) {
  14266. return 0;
  14267. }
  14268. if (!dom_ctx) {
  14269. dom_ctx = &(phys_ctx->dd);
  14270. }
  14271. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14272. /* No SSL port is set. No need to setup SSL. */
  14273. return 1;
  14274. }
  14275. /* Check for external SSL_CTX */
  14276. callback_ret =
  14277. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14278. ? 0
  14279. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14280. phys_ctx->user_data));
  14281. if (callback_ret < 0) {
  14282. /* Callback exists and returns <0: Initializing failed. */
  14283. mg_cry_ctx_internal(phys_ctx,
  14284. "external_ssl_ctx callback returned error: %i",
  14285. callback_ret);
  14286. return 0;
  14287. } else if (callback_ret > 0) {
  14288. /* Callback exists and returns >0: Initializing complete,
  14289. * civetweb should not modify the SSL context. */
  14290. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14291. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14292. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14293. return 0;
  14294. }
  14295. return 1;
  14296. }
  14297. /* If the callback does not exist or return 0, civetweb must initialize
  14298. * the SSL context. Handle "domain" callback next. */
  14299. /* Check for external domain SSL_CTX callback. */
  14300. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14301. ? 0
  14302. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14303. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14304. &ssl_ctx,
  14305. phys_ctx->user_data));
  14306. if (callback_ret < 0) {
  14307. /* Callback < 0: Error. Abort init. */
  14308. mg_cry_ctx_internal(
  14309. phys_ctx,
  14310. "external_ssl_ctx_domain callback returned error: %i",
  14311. callback_ret);
  14312. return 0;
  14313. } else if (callback_ret > 0) {
  14314. /* Callback > 0: Consider init done. */
  14315. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14316. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14317. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14318. return 0;
  14319. }
  14320. return 1;
  14321. }
  14322. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14323. * 0, CivetWeb should continue initializing SSL */
  14324. /* If PEM file is not specified and the init_ssl callbacks
  14325. * are not specified, setup will fail. */
  14326. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14327. && (phys_ctx->callbacks.init_ssl == NULL)
  14328. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14329. /* No certificate and no init_ssl callbacks:
  14330. * Essential data to set up TLS is missing.
  14331. */
  14332. mg_cry_ctx_internal(phys_ctx,
  14333. "Initializing SSL failed: -%s is not set",
  14334. config_options[SSL_CERTIFICATE].name);
  14335. return 0;
  14336. }
  14337. /* If a certificate chain is configured, use it. */
  14338. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14339. if (chain == NULL) {
  14340. /* Default: certificate chain in PEM file */
  14341. chain = pem;
  14342. }
  14343. if ((chain != NULL) && (*chain == 0)) {
  14344. /* If the chain is an empty string, don't use it. */
  14345. chain = NULL;
  14346. }
  14347. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14348. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14349. return 0;
  14350. }
  14351. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14352. }
  14353. static void
  14354. uninitialize_openssl(void)
  14355. {
  14356. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14357. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14358. /* Shutdown according to
  14359. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14360. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14361. */
  14362. CONF_modules_unload(1);
  14363. #else
  14364. int i;
  14365. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14366. /* Shutdown according to
  14367. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14368. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14369. */
  14370. CRYPTO_set_locking_callback(NULL);
  14371. CRYPTO_set_id_callback(NULL);
  14372. ENGINE_cleanup();
  14373. CONF_modules_unload(1);
  14374. ERR_free_strings();
  14375. EVP_cleanup();
  14376. CRYPTO_cleanup_all_ex_data();
  14377. OPENSSL_REMOVE_THREAD_STATE();
  14378. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14379. pthread_mutex_destroy(&ssl_mutexes[i]);
  14380. }
  14381. mg_free(ssl_mutexes);
  14382. ssl_mutexes = NULL;
  14383. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14384. }
  14385. }
  14386. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  14387. #if !defined(NO_FILESYSTEMS)
  14388. static int
  14389. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14390. {
  14391. if (phys_ctx) {
  14392. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14393. const char *path;
  14394. struct mg_connection fc;
  14395. if (!dom_ctx) {
  14396. dom_ctx = &(phys_ctx->dd);
  14397. }
  14398. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14399. if ((path != NULL)
  14400. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14401. mg_cry_ctx_internal(phys_ctx,
  14402. "Cannot open %s: %s",
  14403. path,
  14404. strerror(ERRNO));
  14405. return 0;
  14406. }
  14407. return 1;
  14408. }
  14409. return 0;
  14410. }
  14411. #endif /* NO_FILESYSTEMS */
  14412. static int
  14413. set_acl_option(struct mg_context *phys_ctx)
  14414. {
  14415. union usa sa;
  14416. memset(&sa, 0, sizeof(sa));
  14417. #if defined(USE_IPV6)
  14418. sa.sin6.sin6_family = AF_INET6;
  14419. #else
  14420. sa.sin.sin_family = AF_INET;
  14421. #endif
  14422. return check_acl(phys_ctx, &sa) != -1;
  14423. }
  14424. static void
  14425. reset_per_request_attributes(struct mg_connection *conn)
  14426. {
  14427. if (!conn) {
  14428. return;
  14429. }
  14430. conn->num_bytes_sent = conn->consumed_content = 0;
  14431. conn->path_info = NULL;
  14432. conn->status_code = -1;
  14433. conn->content_len = -1;
  14434. conn->is_chunked = 0;
  14435. conn->must_close = 0;
  14436. conn->request_len = 0;
  14437. conn->request_state = 0;
  14438. conn->throttle = 0;
  14439. conn->accept_gzip = 0;
  14440. conn->response_info.content_length = conn->request_info.content_length = -1;
  14441. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14442. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14443. conn->response_info.status_text = NULL;
  14444. conn->response_info.status_code = 0;
  14445. conn->request_info.remote_user = NULL;
  14446. conn->request_info.request_method = NULL;
  14447. conn->request_info.request_uri = NULL;
  14448. /* Free cleaned local URI (if any) */
  14449. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  14450. mg_free((void *)conn->request_info.local_uri);
  14451. conn->request_info.local_uri = NULL;
  14452. }
  14453. conn->request_info.local_uri = NULL;
  14454. #if defined(USE_SERVER_STATS)
  14455. conn->processing_time = 0;
  14456. #endif
  14457. #if defined(MG_LEGACY_INTERFACE)
  14458. /* Legacy before split into local_uri and request_uri */
  14459. conn->request_info.uri = NULL;
  14460. #endif
  14461. }
  14462. static int
  14463. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14464. {
  14465. if ((so->lsa.sa.sa_family == AF_INET)
  14466. || (so->lsa.sa.sa_family == AF_INET6)) {
  14467. /* Only for TCP sockets */
  14468. if (setsockopt(so->sock,
  14469. IPPROTO_TCP,
  14470. TCP_NODELAY,
  14471. (SOCK_OPT_TYPE)&nodelay_on,
  14472. sizeof(nodelay_on))
  14473. != 0) {
  14474. /* Error */
  14475. return 1;
  14476. }
  14477. }
  14478. /* OK */
  14479. return 0;
  14480. }
  14481. #if !defined(__ZEPHYR__)
  14482. static void
  14483. close_socket_gracefully(struct mg_connection *conn)
  14484. {
  14485. #if defined(_WIN32)
  14486. char buf[MG_BUF_LEN];
  14487. int n;
  14488. #endif
  14489. struct linger linger;
  14490. int error_code = 0;
  14491. int linger_timeout = -2;
  14492. socklen_t opt_len = sizeof(error_code);
  14493. if (!conn) {
  14494. return;
  14495. }
  14496. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14497. * "Note that enabling a nonzero timeout on a nonblocking socket
  14498. * is not recommended.", so set it to blocking now */
  14499. set_blocking_mode(conn->client.sock);
  14500. /* Send FIN to the client */
  14501. shutdown(conn->client.sock, SHUTDOWN_WR);
  14502. #if defined(_WIN32)
  14503. /* Read and discard pending incoming data. If we do not do that and
  14504. * close
  14505. * the socket, the data in the send buffer may be discarded. This
  14506. * behaviour is seen on Windows, when client keeps sending data
  14507. * when server decides to close the connection; then when client
  14508. * does recv() it gets no data back. */
  14509. do {
  14510. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14511. } while (n > 0);
  14512. #endif
  14513. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14514. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14515. }
  14516. /* Set linger option according to configuration */
  14517. if (linger_timeout >= 0) {
  14518. /* Set linger option to avoid socket hanging out after close. This
  14519. * prevent ephemeral port exhaust problem under high QPS. */
  14520. linger.l_onoff = 1;
  14521. #if defined(_MSC_VER)
  14522. #pragma warning(push)
  14523. #pragma warning(disable : 4244)
  14524. #endif
  14525. #if defined(GCC_DIAGNOSTIC)
  14526. #pragma GCC diagnostic push
  14527. #pragma GCC diagnostic ignored "-Wconversion"
  14528. #endif
  14529. /* Data type of linger structure elements may differ,
  14530. * so we don't know what cast we need here.
  14531. * Disable type conversion warnings. */
  14532. linger.l_linger = (linger_timeout + 999) / 1000;
  14533. #if defined(GCC_DIAGNOSTIC)
  14534. #pragma GCC diagnostic pop
  14535. #endif
  14536. #if defined(_MSC_VER)
  14537. #pragma warning(pop)
  14538. #endif
  14539. } else {
  14540. linger.l_onoff = 0;
  14541. linger.l_linger = 0;
  14542. }
  14543. if (linger_timeout < -1) {
  14544. /* Default: don't configure any linger */
  14545. } else if (getsockopt(conn->client.sock,
  14546. SOL_SOCKET,
  14547. SO_ERROR,
  14548. #if defined(_WIN32) /* WinSock uses different data type here */
  14549. (char *)&error_code,
  14550. #else
  14551. &error_code,
  14552. #endif
  14553. &opt_len)
  14554. != 0) {
  14555. /* Cannot determine if socket is already closed. This should
  14556. * not occur and never did in a test. Log an error message
  14557. * and continue. */
  14558. mg_cry_internal(conn,
  14559. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14560. __func__,
  14561. strerror(ERRNO));
  14562. #if defined(_WIN32)
  14563. } else if (error_code == WSAECONNRESET) {
  14564. #else
  14565. } else if (error_code == ECONNRESET) {
  14566. #endif
  14567. /* Socket already closed by client/peer, close socket without linger
  14568. */
  14569. } else {
  14570. /* Set linger timeout */
  14571. if (setsockopt(conn->client.sock,
  14572. SOL_SOCKET,
  14573. SO_LINGER,
  14574. (char *)&linger,
  14575. sizeof(linger))
  14576. != 0) {
  14577. mg_cry_internal(
  14578. conn,
  14579. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14580. __func__,
  14581. linger.l_onoff,
  14582. linger.l_linger,
  14583. strerror(ERRNO));
  14584. }
  14585. }
  14586. /* Now we know that our FIN is ACK-ed, safe to close */
  14587. closesocket(conn->client.sock);
  14588. conn->client.sock = INVALID_SOCKET;
  14589. }
  14590. #endif
  14591. static void
  14592. close_connection(struct mg_connection *conn)
  14593. {
  14594. #if defined(USE_SERVER_STATS)
  14595. conn->conn_state = 6; /* to close */
  14596. #endif
  14597. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14598. if (conn->lua_websocket_state) {
  14599. lua_websocket_close(conn, conn->lua_websocket_state);
  14600. conn->lua_websocket_state = NULL;
  14601. }
  14602. #endif
  14603. mg_lock_connection(conn);
  14604. /* Set close flag, so keep-alive loops will stop */
  14605. conn->must_close = 1;
  14606. /* call the connection_close callback if assigned */
  14607. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14608. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14609. conn->phys_ctx->callbacks.connection_close(conn);
  14610. }
  14611. }
  14612. /* Reset user data, after close callback is called.
  14613. * Do not reuse it. If the user needs a destructor,
  14614. * it must be done in the connection_close callback. */
  14615. mg_set_user_connection_data(conn, NULL);
  14616. #if defined(USE_SERVER_STATS)
  14617. conn->conn_state = 7; /* closing */
  14618. #endif
  14619. #if defined(USE_MBEDTLS)
  14620. if (conn->ssl != NULL) {
  14621. mbed_ssl_close(conn->ssl);
  14622. conn->ssl = NULL;
  14623. }
  14624. #elif !defined(NO_SSL)
  14625. if (conn->ssl != NULL) {
  14626. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14627. */
  14628. SSL_shutdown(conn->ssl);
  14629. SSL_free(conn->ssl);
  14630. OPENSSL_REMOVE_THREAD_STATE();
  14631. conn->ssl = NULL;
  14632. }
  14633. #endif
  14634. if (conn->client.sock != INVALID_SOCKET) {
  14635. #if defined(__ZEPHYR__)
  14636. closesocket(conn->client.sock);
  14637. #else
  14638. close_socket_gracefully(conn);
  14639. #endif
  14640. conn->client.sock = INVALID_SOCKET;
  14641. }
  14642. /* call the connection_closed callback if assigned */
  14643. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  14644. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14645. conn->phys_ctx->callbacks.connection_closed(conn);
  14646. }
  14647. }
  14648. mg_unlock_connection(conn);
  14649. #if defined(USE_SERVER_STATS)
  14650. conn->conn_state = 8; /* closed */
  14651. #endif
  14652. }
  14653. void
  14654. mg_close_connection(struct mg_connection *conn)
  14655. {
  14656. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14657. return;
  14658. }
  14659. #if defined(USE_WEBSOCKET)
  14660. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14661. if (conn->in_websocket_handling) {
  14662. /* Set close flag, so the server thread can exit. */
  14663. conn->must_close = 1;
  14664. return;
  14665. }
  14666. }
  14667. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14668. unsigned int i;
  14669. /* client context: loops must end */
  14670. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14671. conn->must_close = 1;
  14672. /* We need to get the client thread out of the select/recv call
  14673. * here. */
  14674. /* Since we use a sleep quantum of some seconds to check for recv
  14675. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14676. /* join worker thread */
  14677. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14678. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14679. }
  14680. }
  14681. #endif /* defined(USE_WEBSOCKET) */
  14682. close_connection(conn);
  14683. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14684. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14685. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14686. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14687. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14688. }
  14689. #endif
  14690. #if defined(USE_WEBSOCKET)
  14691. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14692. mg_free(conn->phys_ctx->worker_threadids);
  14693. (void)pthread_mutex_destroy(&conn->mutex);
  14694. mg_free(conn);
  14695. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14696. (void)pthread_mutex_destroy(&conn->mutex);
  14697. mg_free(conn);
  14698. }
  14699. #else
  14700. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14701. (void)pthread_mutex_destroy(&conn->mutex);
  14702. mg_free(conn);
  14703. }
  14704. #endif /* defined(USE_WEBSOCKET) */
  14705. }
  14706. static struct mg_connection *
  14707. mg_connect_client_impl(const struct mg_client_options *client_options,
  14708. int use_ssl,
  14709. char *ebuf,
  14710. size_t ebuf_len)
  14711. {
  14712. struct mg_connection *conn = NULL;
  14713. SOCKET sock;
  14714. union usa sa;
  14715. struct sockaddr *psa;
  14716. socklen_t len;
  14717. unsigned max_req_size =
  14718. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14719. /* Size of structures, aligned to 8 bytes */
  14720. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14721. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14722. conn =
  14723. (struct mg_connection *)mg_calloc(1,
  14724. conn_size + ctx_size + max_req_size);
  14725. if (conn == NULL) {
  14726. mg_snprintf(NULL,
  14727. NULL, /* No truncation check for ebuf */
  14728. ebuf,
  14729. ebuf_len,
  14730. "calloc(): %s",
  14731. strerror(ERRNO));
  14732. return NULL;
  14733. }
  14734. #if defined(GCC_DIAGNOSTIC)
  14735. #pragma GCC diagnostic push
  14736. #pragma GCC diagnostic ignored "-Wcast-align"
  14737. #endif /* defined(GCC_DIAGNOSTIC) */
  14738. /* conn_size is aligned to 8 bytes */
  14739. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14740. #if defined(GCC_DIAGNOSTIC)
  14741. #pragma GCC diagnostic pop
  14742. #endif /* defined(GCC_DIAGNOSTIC) */
  14743. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14744. conn->buf_size = (int)max_req_size;
  14745. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14746. conn->dom_ctx = &(conn->phys_ctx->dd);
  14747. if (!connect_socket(conn->phys_ctx,
  14748. client_options->host,
  14749. client_options->port,
  14750. use_ssl,
  14751. ebuf,
  14752. ebuf_len,
  14753. &sock,
  14754. &sa)) {
  14755. /* ebuf is set by connect_socket,
  14756. * free all memory and return NULL; */
  14757. mg_free(conn);
  14758. return NULL;
  14759. }
  14760. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14761. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14762. if (use_ssl
  14763. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14764. == NULL) {
  14765. mg_snprintf(NULL,
  14766. NULL, /* No truncation check for ebuf */
  14767. ebuf,
  14768. ebuf_len,
  14769. "SSL_CTX_new error: %s",
  14770. ssl_error());
  14771. closesocket(sock);
  14772. mg_free(conn);
  14773. return NULL;
  14774. }
  14775. #else
  14776. if (use_ssl
  14777. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14778. == NULL) {
  14779. mg_snprintf(NULL,
  14780. NULL, /* No truncation check for ebuf */
  14781. ebuf,
  14782. ebuf_len,
  14783. "SSL_CTX_new error: %s",
  14784. ssl_error());
  14785. closesocket(sock);
  14786. mg_free(conn);
  14787. return NULL;
  14788. }
  14789. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14790. #endif /* NO_SSL */
  14791. #if defined(USE_IPV6)
  14792. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14793. : sizeof(conn->client.rsa.sin6);
  14794. psa = (sa.sa.sa_family == AF_INET)
  14795. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14796. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14797. #else
  14798. len = sizeof(conn->client.rsa.sin);
  14799. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14800. #endif
  14801. conn->client.sock = sock;
  14802. conn->client.lsa = sa;
  14803. if (getsockname(sock, psa, &len) != 0) {
  14804. mg_cry_internal(conn,
  14805. "%s: getsockname() failed: %s",
  14806. __func__,
  14807. strerror(ERRNO));
  14808. }
  14809. conn->client.is_ssl = use_ssl ? 1 : 0;
  14810. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14811. mg_snprintf(NULL,
  14812. NULL, /* No truncation check for ebuf */
  14813. ebuf,
  14814. ebuf_len,
  14815. "Can not create mutex");
  14816. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14817. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14818. #endif
  14819. closesocket(sock);
  14820. mg_free(conn);
  14821. return NULL;
  14822. }
  14823. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14824. if (use_ssl) {
  14825. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14826. * SSL_CTX_set_verify call is needed to switch off server
  14827. * certificate checking, which is off by default in OpenSSL and
  14828. * on in yaSSL. */
  14829. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14830. * SSL_VERIFY_PEER, verify_ssl_server); */
  14831. if (client_options->client_cert) {
  14832. if (!ssl_use_pem_file(conn->phys_ctx,
  14833. conn->dom_ctx,
  14834. client_options->client_cert,
  14835. NULL)) {
  14836. mg_snprintf(NULL,
  14837. NULL, /* No truncation check for ebuf */
  14838. ebuf,
  14839. ebuf_len,
  14840. "Can not use SSL client certificate");
  14841. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14842. closesocket(sock);
  14843. mg_free(conn);
  14844. return NULL;
  14845. }
  14846. }
  14847. if (client_options->server_cert) {
  14848. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14849. client_options->server_cert,
  14850. NULL)
  14851. != 1) {
  14852. mg_cry_internal(conn,
  14853. "SSL_CTX_load_verify_locations error: %s ",
  14854. ssl_error());
  14855. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14856. closesocket(sock);
  14857. mg_free(conn);
  14858. return NULL;
  14859. }
  14860. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14861. } else {
  14862. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14863. }
  14864. if (!sslize(conn, SSL_connect, client_options)) {
  14865. mg_snprintf(NULL,
  14866. NULL, /* No truncation check for ebuf */
  14867. ebuf,
  14868. ebuf_len,
  14869. "SSL connection error");
  14870. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14871. closesocket(sock);
  14872. mg_free(conn);
  14873. return NULL;
  14874. }
  14875. }
  14876. #endif
  14877. return conn;
  14878. }
  14879. CIVETWEB_API struct mg_connection *
  14880. mg_connect_client_secure(const struct mg_client_options *client_options,
  14881. char *error_buffer,
  14882. size_t error_buffer_size)
  14883. {
  14884. return mg_connect_client_impl(client_options,
  14885. 1,
  14886. error_buffer,
  14887. error_buffer_size);
  14888. }
  14889. struct mg_connection *
  14890. mg_connect_client(const char *host,
  14891. int port,
  14892. int use_ssl,
  14893. char *error_buffer,
  14894. size_t error_buffer_size)
  14895. {
  14896. struct mg_client_options opts;
  14897. memset(&opts, 0, sizeof(opts));
  14898. opts.host = host;
  14899. opts.port = port;
  14900. return mg_connect_client_impl(&opts,
  14901. use_ssl,
  14902. error_buffer,
  14903. error_buffer_size);
  14904. }
  14905. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14906. struct mg_connection *
  14907. mg_connect_client2(const char *host,
  14908. const char *protocol,
  14909. int port,
  14910. const char *path,
  14911. struct mg_init_data *init,
  14912. struct mg_error_data *error)
  14913. {
  14914. int is_ssl, is_ws;
  14915. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14916. if (error != NULL) {
  14917. error->code = 0;
  14918. if (error->text_buffer_size > 0) {
  14919. *error->text = 0;
  14920. }
  14921. }
  14922. if ((host == NULL) || (protocol == NULL)) {
  14923. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14924. mg_snprintf(NULL,
  14925. NULL, /* No truncation check for error buffers */
  14926. error->text,
  14927. error->text_buffer_size,
  14928. "%s",
  14929. "Invalid parameters");
  14930. }
  14931. return NULL;
  14932. }
  14933. /* check all known protocolls */
  14934. if (!mg_strcasecmp(protocol, "http")) {
  14935. is_ssl = 0;
  14936. is_ws = 0;
  14937. } else if (!mg_strcasecmp(protocol, "https")) {
  14938. is_ssl = 1;
  14939. is_ws = 0;
  14940. #if defined(USE_WEBSOCKET)
  14941. } else if (!mg_strcasecmp(protocol, "ws")) {
  14942. is_ssl = 0;
  14943. is_ws = 1;
  14944. } else if (!mg_strcasecmp(protocol, "wss")) {
  14945. is_ssl = 1;
  14946. is_ws = 1;
  14947. #endif
  14948. } else {
  14949. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14950. mg_snprintf(NULL,
  14951. NULL, /* No truncation check for error buffers */
  14952. error->text,
  14953. error->text_buffer_size,
  14954. "Protocol %s not supported",
  14955. protocol);
  14956. }
  14957. return NULL;
  14958. }
  14959. /* TODO: The current implementation here just calls the old
  14960. * implementations, without using any new options. This is just a first
  14961. * step to test the new interfaces. */
  14962. #if defined(USE_WEBSOCKET)
  14963. if (is_ws) {
  14964. /* TODO: implement all options */
  14965. return mg_connect_websocket_client(
  14966. host,
  14967. port,
  14968. is_ssl,
  14969. ((error != NULL) ? error->text : NULL),
  14970. ((error != NULL) ? error->text_buffer_size : 0),
  14971. (path ? path : ""),
  14972. NULL /* TODO: origin */,
  14973. experimental_websocket_client_data_wrapper,
  14974. experimental_websocket_client_close_wrapper,
  14975. (void *)init->callbacks);
  14976. }
  14977. #endif
  14978. /* TODO: all additional options */
  14979. struct mg_client_options opts;
  14980. memset(&opts, 0, sizeof(opts));
  14981. opts.host = host;
  14982. opts.port = port;
  14983. return mg_connect_client_impl(&opts,
  14984. is_ssl,
  14985. ((error != NULL) ? error->text : NULL),
  14986. ((error != NULL) ? error->text_buffer_size
  14987. : 0));
  14988. }
  14989. #endif
  14990. static const struct {
  14991. const char *proto;
  14992. size_t proto_len;
  14993. unsigned default_port;
  14994. } abs_uri_protocols[] = {{"http://", 7, 80},
  14995. {"https://", 8, 443},
  14996. {"ws://", 5, 80},
  14997. {"wss://", 6, 443},
  14998. {NULL, 0, 0}};
  14999. /* Check if the uri is valid.
  15000. * return 0 for invalid uri,
  15001. * return 1 for *,
  15002. * return 2 for relative uri,
  15003. * return 3 for absolute uri without port,
  15004. * return 4 for absolute uri with port */
  15005. static int
  15006. get_uri_type(const char *uri)
  15007. {
  15008. int i;
  15009. const char *hostend, *portbegin;
  15010. char *portend;
  15011. unsigned long port;
  15012. /* According to the HTTP standard
  15013. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15014. * URI can be an asterisk (*) or should start with slash (relative uri),
  15015. * or it should start with the protocol (absolute uri). */
  15016. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15017. /* asterisk */
  15018. return 1;
  15019. }
  15020. /* Valid URIs according to RFC 3986
  15021. * (https://www.ietf.org/rfc/rfc3986.txt)
  15022. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15023. * and unreserved characters A-Z a-z 0-9 and -._~
  15024. * and % encoded symbols.
  15025. */
  15026. for (i = 0; uri[i] != 0; i++) {
  15027. if (uri[i] < 33) {
  15028. /* control characters and spaces are invalid */
  15029. return 0;
  15030. }
  15031. /* Allow everything else here (See #894) */
  15032. }
  15033. /* A relative uri starts with a / character */
  15034. if (uri[0] == '/') {
  15035. /* relative uri */
  15036. return 2;
  15037. }
  15038. /* It could be an absolute uri: */
  15039. /* This function only checks if the uri is valid, not if it is
  15040. * addressing the current server. So civetweb can also be used
  15041. * as a proxy server. */
  15042. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15043. if (mg_strncasecmp(uri,
  15044. abs_uri_protocols[i].proto,
  15045. abs_uri_protocols[i].proto_len)
  15046. == 0) {
  15047. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15048. if (!hostend) {
  15049. return 0;
  15050. }
  15051. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15052. if (!portbegin) {
  15053. return 3;
  15054. }
  15055. port = strtoul(portbegin + 1, &portend, 10);
  15056. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15057. return 0;
  15058. }
  15059. return 4;
  15060. }
  15061. }
  15062. return 0;
  15063. }
  15064. /* Return NULL or the relative uri at the current server */
  15065. static const char *
  15066. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15067. {
  15068. const char *server_domain;
  15069. size_t server_domain_len;
  15070. size_t request_domain_len = 0;
  15071. unsigned long port = 0;
  15072. int i, auth_domain_check_enabled;
  15073. const char *hostbegin = NULL;
  15074. const char *hostend = NULL;
  15075. const char *portbegin;
  15076. char *portend;
  15077. auth_domain_check_enabled =
  15078. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15079. /* DNS is case insensitive, so use case insensitive string compare here
  15080. */
  15081. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15082. if (mg_strncasecmp(uri,
  15083. abs_uri_protocols[i].proto,
  15084. abs_uri_protocols[i].proto_len)
  15085. == 0) {
  15086. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15087. hostend = strchr(hostbegin, '/');
  15088. if (!hostend) {
  15089. return 0;
  15090. }
  15091. portbegin = strchr(hostbegin, ':');
  15092. if ((!portbegin) || (portbegin > hostend)) {
  15093. port = abs_uri_protocols[i].default_port;
  15094. request_domain_len = (size_t)(hostend - hostbegin);
  15095. } else {
  15096. port = strtoul(portbegin + 1, &portend, 10);
  15097. if ((portend != hostend) || (port <= 0)
  15098. || !is_valid_port(port)) {
  15099. return 0;
  15100. }
  15101. request_domain_len = (size_t)(portbegin - hostbegin);
  15102. }
  15103. /* protocol found, port set */
  15104. break;
  15105. }
  15106. }
  15107. if (!port) {
  15108. /* port remains 0 if the protocol is not found */
  15109. return 0;
  15110. }
  15111. /* Check if the request is directed to a different server. */
  15112. /* First check if the port is the same. */
  15113. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15114. /* Request is directed to a different port */
  15115. return 0;
  15116. }
  15117. /* Finally check if the server corresponds to the authentication
  15118. * domain of the server (the server domain).
  15119. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15120. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15121. * but do not allow substrings (like
  15122. * http://notmydomain.com/path/file.ext
  15123. * or http://mydomain.com.fake/path/file.ext).
  15124. */
  15125. if (auth_domain_check_enabled) {
  15126. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15127. server_domain_len = strlen(server_domain);
  15128. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15129. return 0;
  15130. }
  15131. if ((request_domain_len == server_domain_len)
  15132. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15133. /* Request is directed to this server - full name match. */
  15134. } else {
  15135. if (request_domain_len < (server_domain_len + 2)) {
  15136. /* Request is directed to another server: The server name
  15137. * is longer than the request name.
  15138. * Drop this case here to avoid overflows in the
  15139. * following checks. */
  15140. return 0;
  15141. }
  15142. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15143. /* Request is directed to another server: It could be a
  15144. * substring
  15145. * like notmyserver.com */
  15146. return 0;
  15147. }
  15148. if (0
  15149. != memcmp(server_domain,
  15150. hostbegin + request_domain_len - server_domain_len,
  15151. server_domain_len)) {
  15152. /* Request is directed to another server:
  15153. * The server name is different. */
  15154. return 0;
  15155. }
  15156. }
  15157. }
  15158. return hostend;
  15159. }
  15160. static int
  15161. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15162. {
  15163. if (ebuf_len > 0) {
  15164. ebuf[0] = '\0';
  15165. }
  15166. *err = 0;
  15167. reset_per_request_attributes(conn);
  15168. if (!conn) {
  15169. mg_snprintf(conn,
  15170. NULL, /* No truncation check for ebuf */
  15171. ebuf,
  15172. ebuf_len,
  15173. "%s",
  15174. "Internal error");
  15175. *err = 500;
  15176. return 0;
  15177. }
  15178. /* Set the time the request was received. This value should be used for
  15179. * timeouts. */
  15180. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15181. conn->request_len =
  15182. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15183. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15184. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15185. mg_snprintf(conn,
  15186. NULL, /* No truncation check for ebuf */
  15187. ebuf,
  15188. ebuf_len,
  15189. "%s",
  15190. "Invalid message size");
  15191. *err = 500;
  15192. return 0;
  15193. }
  15194. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15195. mg_snprintf(conn,
  15196. NULL, /* No truncation check for ebuf */
  15197. ebuf,
  15198. ebuf_len,
  15199. "%s",
  15200. "Message too large");
  15201. *err = 413;
  15202. return 0;
  15203. }
  15204. if (conn->request_len <= 0) {
  15205. if (conn->data_len > 0) {
  15206. mg_snprintf(conn,
  15207. NULL, /* No truncation check for ebuf */
  15208. ebuf,
  15209. ebuf_len,
  15210. "%s",
  15211. "Malformed message");
  15212. *err = 400;
  15213. } else {
  15214. /* Server did not recv anything -> just close the connection */
  15215. conn->must_close = 1;
  15216. mg_snprintf(conn,
  15217. NULL, /* No truncation check for ebuf */
  15218. ebuf,
  15219. ebuf_len,
  15220. "%s",
  15221. "No data received");
  15222. *err = 0;
  15223. }
  15224. return 0;
  15225. }
  15226. return 1;
  15227. }
  15228. static int
  15229. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15230. {
  15231. const char *cl;
  15232. conn->connection_type =
  15233. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15234. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15235. return 0;
  15236. }
  15237. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15238. <= 0) {
  15239. mg_snprintf(conn,
  15240. NULL, /* No truncation check for ebuf */
  15241. ebuf,
  15242. ebuf_len,
  15243. "%s",
  15244. "Bad request");
  15245. *err = 400;
  15246. return 0;
  15247. }
  15248. /* Message is a valid request */
  15249. if (!switch_domain_context(conn)) {
  15250. mg_snprintf(conn,
  15251. NULL, /* No truncation check for ebuf */
  15252. ebuf,
  15253. ebuf_len,
  15254. "%s",
  15255. "Bad request: Host mismatch");
  15256. *err = 400;
  15257. return 0;
  15258. }
  15259. if (((cl = get_header(conn->request_info.http_headers,
  15260. conn->request_info.num_headers,
  15261. "Transfer-Encoding"))
  15262. != NULL)
  15263. && mg_strcasecmp(cl, "identity")) {
  15264. if (mg_strcasecmp(cl, "chunked")) {
  15265. mg_snprintf(conn,
  15266. NULL, /* No truncation check for ebuf */
  15267. ebuf,
  15268. ebuf_len,
  15269. "%s",
  15270. "Bad request");
  15271. *err = 400;
  15272. return 0;
  15273. }
  15274. conn->is_chunked = 1;
  15275. conn->content_len = 0; /* not yet read */
  15276. } else if ((cl = get_header(conn->request_info.http_headers,
  15277. conn->request_info.num_headers,
  15278. "Content-Length"))
  15279. != NULL) {
  15280. /* Request has content length set */
  15281. char *endptr = NULL;
  15282. conn->content_len = strtoll(cl, &endptr, 10);
  15283. if ((endptr == cl) || (conn->content_len < 0)) {
  15284. mg_snprintf(conn,
  15285. NULL, /* No truncation check for ebuf */
  15286. ebuf,
  15287. ebuf_len,
  15288. "%s",
  15289. "Bad request");
  15290. *err = 411;
  15291. return 0;
  15292. }
  15293. /* Publish the content length back to the request info. */
  15294. conn->request_info.content_length = conn->content_len;
  15295. } else {
  15296. /* There is no exception, see RFC7230. */
  15297. conn->content_len = 0;
  15298. }
  15299. return 1;
  15300. }
  15301. /* conn is assumed to be valid in this internal function */
  15302. static int
  15303. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15304. {
  15305. const char *cl;
  15306. conn->connection_type =
  15307. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15308. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15309. return 0;
  15310. }
  15311. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15312. <= 0) {
  15313. mg_snprintf(conn,
  15314. NULL, /* No truncation check for ebuf */
  15315. ebuf,
  15316. ebuf_len,
  15317. "%s",
  15318. "Bad response");
  15319. *err = 400;
  15320. return 0;
  15321. }
  15322. /* Message is a valid response */
  15323. if (((cl = get_header(conn->response_info.http_headers,
  15324. conn->response_info.num_headers,
  15325. "Transfer-Encoding"))
  15326. != NULL)
  15327. && mg_strcasecmp(cl, "identity")) {
  15328. if (mg_strcasecmp(cl, "chunked")) {
  15329. mg_snprintf(conn,
  15330. NULL, /* No truncation check for ebuf */
  15331. ebuf,
  15332. ebuf_len,
  15333. "%s",
  15334. "Bad request");
  15335. *err = 400;
  15336. return 0;
  15337. }
  15338. conn->is_chunked = 1;
  15339. conn->content_len = 0; /* not yet read */
  15340. } else if ((cl = get_header(conn->response_info.http_headers,
  15341. conn->response_info.num_headers,
  15342. "Content-Length"))
  15343. != NULL) {
  15344. char *endptr = NULL;
  15345. conn->content_len = strtoll(cl, &endptr, 10);
  15346. if ((endptr == cl) || (conn->content_len < 0)) {
  15347. mg_snprintf(conn,
  15348. NULL, /* No truncation check for ebuf */
  15349. ebuf,
  15350. ebuf_len,
  15351. "%s",
  15352. "Bad request");
  15353. *err = 411;
  15354. return 0;
  15355. }
  15356. /* Publish the content length back to the response info. */
  15357. conn->response_info.content_length = conn->content_len;
  15358. /* TODO: check if it is still used in response_info */
  15359. conn->request_info.content_length = conn->content_len;
  15360. /* TODO: we should also consider HEAD method */
  15361. if (conn->response_info.status_code == 304) {
  15362. conn->content_len = 0;
  15363. }
  15364. } else {
  15365. /* TODO: we should also consider HEAD method */
  15366. if (((conn->response_info.status_code >= 100)
  15367. && (conn->response_info.status_code <= 199))
  15368. || (conn->response_info.status_code == 204)
  15369. || (conn->response_info.status_code == 304)) {
  15370. conn->content_len = 0;
  15371. } else {
  15372. conn->content_len = -1; /* unknown content length */
  15373. }
  15374. }
  15375. return 1;
  15376. }
  15377. int
  15378. mg_get_response(struct mg_connection *conn,
  15379. char *ebuf,
  15380. size_t ebuf_len,
  15381. int timeout)
  15382. {
  15383. int err, ret;
  15384. char txt[32]; /* will not overflow */
  15385. char *save_timeout;
  15386. char *new_timeout;
  15387. if (ebuf_len > 0) {
  15388. ebuf[0] = '\0';
  15389. }
  15390. if (!conn) {
  15391. mg_snprintf(conn,
  15392. NULL, /* No truncation check for ebuf */
  15393. ebuf,
  15394. ebuf_len,
  15395. "%s",
  15396. "Parameter error");
  15397. return -1;
  15398. }
  15399. /* Reset the previous responses */
  15400. conn->data_len = 0;
  15401. /* Implementation of API function for HTTP clients */
  15402. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15403. if (timeout >= 0) {
  15404. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15405. new_timeout = txt;
  15406. } else {
  15407. new_timeout = NULL;
  15408. }
  15409. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15410. ret = get_response(conn, ebuf, ebuf_len, &err);
  15411. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15412. #if defined(MG_LEGACY_INTERFACE)
  15413. /* TODO: 1) uri is deprecated;
  15414. * 2) here, ri.uri is the http response code */
  15415. conn->request_info.uri = conn->request_info.request_uri;
  15416. #endif
  15417. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15418. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15419. /* TODO (mid): Define proper return values - maybe return length?
  15420. * For the first test use <0 for error and >0 for OK */
  15421. return (ret == 0) ? -1 : +1;
  15422. }
  15423. struct mg_connection *
  15424. mg_download(const char *host,
  15425. int port,
  15426. int use_ssl,
  15427. char *ebuf,
  15428. size_t ebuf_len,
  15429. const char *fmt,
  15430. ...)
  15431. {
  15432. struct mg_connection *conn;
  15433. va_list ap;
  15434. int i;
  15435. int reqerr;
  15436. if (ebuf_len > 0) {
  15437. ebuf[0] = '\0';
  15438. }
  15439. va_start(ap, fmt);
  15440. /* open a connection */
  15441. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15442. if (conn != NULL) {
  15443. i = mg_vprintf(conn, fmt, ap);
  15444. if (i <= 0) {
  15445. mg_snprintf(conn,
  15446. NULL, /* No truncation check for ebuf */
  15447. ebuf,
  15448. ebuf_len,
  15449. "%s",
  15450. "Error sending request");
  15451. } else {
  15452. /* make sure the buffer is clear */
  15453. conn->data_len = 0;
  15454. get_response(conn, ebuf, ebuf_len, &reqerr);
  15455. #if defined(MG_LEGACY_INTERFACE)
  15456. /* TODO: 1) uri is deprecated;
  15457. * 2) here, ri.uri is the http response code */
  15458. conn->request_info.uri = conn->request_info.request_uri;
  15459. #endif
  15460. conn->request_info.local_uri = conn->request_info.request_uri;
  15461. }
  15462. }
  15463. /* if an error occurred, close the connection */
  15464. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15465. mg_close_connection(conn);
  15466. conn = NULL;
  15467. }
  15468. va_end(ap);
  15469. return conn;
  15470. }
  15471. struct websocket_client_thread_data {
  15472. struct mg_connection *conn;
  15473. mg_websocket_data_handler data_handler;
  15474. mg_websocket_close_handler close_handler;
  15475. void *callback_data;
  15476. };
  15477. #if defined(USE_WEBSOCKET)
  15478. #if defined(_WIN32)
  15479. static unsigned __stdcall websocket_client_thread(void *data)
  15480. #else
  15481. static void *
  15482. websocket_client_thread(void *data)
  15483. #endif
  15484. {
  15485. struct websocket_client_thread_data *cdata =
  15486. (struct websocket_client_thread_data *)data;
  15487. void *user_thread_ptr = NULL;
  15488. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15489. struct sigaction sa;
  15490. /* Ignore SIGPIPE */
  15491. memset(&sa, 0, sizeof(sa));
  15492. sa.sa_handler = SIG_IGN;
  15493. sigaction(SIGPIPE, &sa, NULL);
  15494. #endif
  15495. mg_set_thread_name("ws-clnt");
  15496. if (cdata->conn->phys_ctx) {
  15497. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15498. /* 3 indicates a websocket client thread */
  15499. /* TODO: check if conn->phys_ctx can be set */
  15500. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15501. cdata->conn->phys_ctx, 3);
  15502. }
  15503. }
  15504. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15505. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15506. if (cdata->close_handler != NULL) {
  15507. cdata->close_handler(cdata->conn, cdata->callback_data);
  15508. }
  15509. /* The websocket_client context has only this thread. If it runs out,
  15510. set the stop_flag to 2 (= "stopped"). */
  15511. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15512. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15513. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15514. 3,
  15515. user_thread_ptr);
  15516. }
  15517. mg_free((void *)cdata);
  15518. #if defined(_WIN32)
  15519. return 0;
  15520. #else
  15521. return NULL;
  15522. #endif
  15523. }
  15524. #endif
  15525. static struct mg_connection *
  15526. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15527. int use_ssl,
  15528. char *error_buffer,
  15529. size_t error_buffer_size,
  15530. const char *path,
  15531. const char *origin,
  15532. const char *extensions,
  15533. mg_websocket_data_handler data_func,
  15534. mg_websocket_close_handler close_func,
  15535. void *user_data)
  15536. {
  15537. struct mg_connection *conn = NULL;
  15538. #if defined(USE_WEBSOCKET)
  15539. struct websocket_client_thread_data *thread_data;
  15540. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15541. const char *host = client_options->host;
  15542. int i;
  15543. #if defined(__clang__)
  15544. #pragma clang diagnostic push
  15545. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15546. #endif
  15547. /* Establish the client connection and request upgrade */
  15548. conn = mg_connect_client_impl(client_options,
  15549. use_ssl,
  15550. error_buffer,
  15551. error_buffer_size);
  15552. /* Connection object will be null if something goes wrong */
  15553. if (conn == NULL) {
  15554. /* error_buffer should be already filled ... */
  15555. if (!error_buffer[0]) {
  15556. /* ... if not add an error message */
  15557. mg_snprintf(conn,
  15558. NULL, /* No truncation check for ebuf */
  15559. error_buffer,
  15560. error_buffer_size,
  15561. "Unexpected error");
  15562. }
  15563. return NULL;
  15564. }
  15565. if (origin != NULL) {
  15566. if (extensions != NULL) {
  15567. i = mg_printf(conn,
  15568. "GET %s HTTP/1.1\r\n"
  15569. "Host: %s\r\n"
  15570. "Upgrade: websocket\r\n"
  15571. "Connection: Upgrade\r\n"
  15572. "Sec-WebSocket-Key: %s\r\n"
  15573. "Sec-WebSocket-Version: 13\r\n"
  15574. "Sec-WebSocket-Extensions: %s\r\n"
  15575. "Origin: %s\r\n"
  15576. "\r\n",
  15577. path,
  15578. host,
  15579. magic,
  15580. extensions,
  15581. origin);
  15582. } else {
  15583. i = mg_printf(conn,
  15584. "GET %s HTTP/1.1\r\n"
  15585. "Host: %s\r\n"
  15586. "Upgrade: websocket\r\n"
  15587. "Connection: Upgrade\r\n"
  15588. "Sec-WebSocket-Key: %s\r\n"
  15589. "Sec-WebSocket-Version: 13\r\n"
  15590. "Origin: %s\r\n"
  15591. "\r\n",
  15592. path,
  15593. host,
  15594. magic,
  15595. origin);
  15596. }
  15597. } else {
  15598. if (extensions != NULL) {
  15599. i = mg_printf(conn,
  15600. "GET %s HTTP/1.1\r\n"
  15601. "Host: %s\r\n"
  15602. "Upgrade: websocket\r\n"
  15603. "Connection: Upgrade\r\n"
  15604. "Sec-WebSocket-Key: %s\r\n"
  15605. "Sec-WebSocket-Version: 13\r\n"
  15606. "Sec-WebSocket-Extensions: %s\r\n"
  15607. "\r\n",
  15608. path,
  15609. host,
  15610. magic,
  15611. extensions);
  15612. } else {
  15613. i = mg_printf(conn,
  15614. "GET %s HTTP/1.1\r\n"
  15615. "Host: %s\r\n"
  15616. "Upgrade: websocket\r\n"
  15617. "Connection: Upgrade\r\n"
  15618. "Sec-WebSocket-Key: %s\r\n"
  15619. "Sec-WebSocket-Version: 13\r\n"
  15620. "\r\n",
  15621. path,
  15622. host,
  15623. magic);
  15624. }
  15625. }
  15626. if (i <= 0) {
  15627. mg_snprintf(conn,
  15628. NULL, /* No truncation check for ebuf */
  15629. error_buffer,
  15630. error_buffer_size,
  15631. "%s",
  15632. "Error sending request");
  15633. mg_close_connection(conn);
  15634. return NULL;
  15635. }
  15636. conn->data_len = 0;
  15637. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15638. mg_close_connection(conn);
  15639. return NULL;
  15640. }
  15641. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15642. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15643. #if defined(__clang__)
  15644. #pragma clang diagnostic pop
  15645. #endif
  15646. if (conn->response_info.status_code != 101) {
  15647. /* We sent an "upgrade" request. For a correct websocket
  15648. * protocol handshake, we expect a "101 Continue" response.
  15649. * Otherwise it is a protocol violation. Maybe the HTTP
  15650. * Server does not know websockets. */
  15651. if (!*error_buffer) {
  15652. /* set an error, if not yet set */
  15653. mg_snprintf(conn,
  15654. NULL, /* No truncation check for ebuf */
  15655. error_buffer,
  15656. error_buffer_size,
  15657. "Unexpected server reply");
  15658. }
  15659. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15660. mg_close_connection(conn);
  15661. return NULL;
  15662. }
  15663. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15664. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15665. if (!thread_data) {
  15666. DEBUG_TRACE("%s\r\n", "Out of memory");
  15667. mg_close_connection(conn);
  15668. return NULL;
  15669. }
  15670. thread_data->conn = conn;
  15671. thread_data->data_handler = data_func;
  15672. thread_data->close_handler = close_func;
  15673. thread_data->callback_data = user_data;
  15674. conn->phys_ctx->worker_threadids =
  15675. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15676. if (!conn->phys_ctx->worker_threadids) {
  15677. DEBUG_TRACE("%s\r\n", "Out of memory");
  15678. mg_free(thread_data);
  15679. mg_close_connection(conn);
  15680. return NULL;
  15681. }
  15682. /* Now upgrade to ws/wss client context */
  15683. conn->phys_ctx->user_data = user_data;
  15684. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15685. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15686. /* Start a thread to read the websocket client connection
  15687. * This thread will automatically stop when mg_disconnect is
  15688. * called on the client connection */
  15689. if (mg_start_thread_with_id(websocket_client_thread,
  15690. thread_data,
  15691. conn->phys_ctx->worker_threadids)
  15692. != 0) {
  15693. conn->phys_ctx->cfg_worker_threads = 0;
  15694. mg_free(thread_data);
  15695. mg_close_connection(conn);
  15696. conn = NULL;
  15697. DEBUG_TRACE("%s",
  15698. "Websocket client connect thread could not be started\r\n");
  15699. }
  15700. #else
  15701. /* Appease "unused parameter" warnings */
  15702. (void)client_options;
  15703. (void)use_ssl;
  15704. (void)error_buffer;
  15705. (void)error_buffer_size;
  15706. (void)path;
  15707. (void)origin;
  15708. (void)extensions;
  15709. (void)user_data;
  15710. (void)data_func;
  15711. (void)close_func;
  15712. #endif
  15713. return conn;
  15714. }
  15715. struct mg_connection *
  15716. mg_connect_websocket_client(const char *host,
  15717. int port,
  15718. int use_ssl,
  15719. char *error_buffer,
  15720. size_t error_buffer_size,
  15721. const char *path,
  15722. const char *origin,
  15723. mg_websocket_data_handler data_func,
  15724. mg_websocket_close_handler close_func,
  15725. void *user_data)
  15726. {
  15727. struct mg_client_options client_options;
  15728. memset(&client_options, 0, sizeof(client_options));
  15729. client_options.host = host;
  15730. client_options.port = port;
  15731. return mg_connect_websocket_client_impl(&client_options,
  15732. use_ssl,
  15733. error_buffer,
  15734. error_buffer_size,
  15735. path,
  15736. origin,
  15737. NULL,
  15738. data_func,
  15739. close_func,
  15740. user_data);
  15741. }
  15742. struct mg_connection *
  15743. mg_connect_websocket_client_secure(
  15744. const struct mg_client_options *client_options,
  15745. char *error_buffer,
  15746. size_t error_buffer_size,
  15747. const char *path,
  15748. const char *origin,
  15749. mg_websocket_data_handler data_func,
  15750. mg_websocket_close_handler close_func,
  15751. void *user_data)
  15752. {
  15753. if (!client_options) {
  15754. return NULL;
  15755. }
  15756. return mg_connect_websocket_client_impl(client_options,
  15757. 1,
  15758. error_buffer,
  15759. error_buffer_size,
  15760. path,
  15761. origin,
  15762. NULL,
  15763. data_func,
  15764. close_func,
  15765. user_data);
  15766. }
  15767. struct mg_connection *
  15768. mg_connect_websocket_client_extensions(const char *host,
  15769. int port,
  15770. int use_ssl,
  15771. char *error_buffer,
  15772. size_t error_buffer_size,
  15773. const char *path,
  15774. const char *origin,
  15775. const char *extensions,
  15776. mg_websocket_data_handler data_func,
  15777. mg_websocket_close_handler close_func,
  15778. void *user_data)
  15779. {
  15780. struct mg_client_options client_options;
  15781. memset(&client_options, 0, sizeof(client_options));
  15782. client_options.host = host;
  15783. client_options.port = port;
  15784. return mg_connect_websocket_client_impl(&client_options,
  15785. use_ssl,
  15786. error_buffer,
  15787. error_buffer_size,
  15788. path,
  15789. origin,
  15790. extensions,
  15791. data_func,
  15792. close_func,
  15793. user_data);
  15794. }
  15795. struct mg_connection *
  15796. mg_connect_websocket_client_secure_extensions(
  15797. const struct mg_client_options *client_options,
  15798. char *error_buffer,
  15799. size_t error_buffer_size,
  15800. const char *path,
  15801. const char *origin,
  15802. const char *extensions,
  15803. mg_websocket_data_handler data_func,
  15804. mg_websocket_close_handler close_func,
  15805. void *user_data)
  15806. {
  15807. if (!client_options) {
  15808. return NULL;
  15809. }
  15810. return mg_connect_websocket_client_impl(client_options,
  15811. 1,
  15812. error_buffer,
  15813. error_buffer_size,
  15814. path,
  15815. origin,
  15816. extensions,
  15817. data_func,
  15818. close_func,
  15819. user_data);
  15820. }
  15821. /* Prepare connection data structure */
  15822. static void
  15823. init_connection(struct mg_connection *conn)
  15824. {
  15825. /* Is keep alive allowed by the server */
  15826. int keep_alive_enabled =
  15827. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15828. if (!keep_alive_enabled) {
  15829. conn->must_close = 1;
  15830. }
  15831. /* Important: on new connection, reset the receiving buffer. Credit
  15832. * goes to crule42. */
  15833. conn->data_len = 0;
  15834. conn->handled_requests = 0;
  15835. conn->connection_type = CONNECTION_TYPE_INVALID;
  15836. mg_set_user_connection_data(conn, NULL);
  15837. #if defined(USE_SERVER_STATS)
  15838. conn->conn_state = 2; /* init */
  15839. #endif
  15840. /* call the init_connection callback if assigned */
  15841. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15842. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15843. void *conn_data = NULL;
  15844. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15845. mg_set_user_connection_data(conn, conn_data);
  15846. }
  15847. }
  15848. }
  15849. /* Process a connection - may handle multiple requests
  15850. * using the same connection.
  15851. * Must be called with a valid connection (conn and
  15852. * conn->phys_ctx must be valid).
  15853. */
  15854. static void
  15855. process_new_connection(struct mg_connection *conn)
  15856. {
  15857. struct mg_request_info *ri = &conn->request_info;
  15858. int keep_alive, discard_len;
  15859. char ebuf[100];
  15860. const char *hostend;
  15861. int reqerr, uri_type;
  15862. #if defined(USE_SERVER_STATS)
  15863. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15864. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15865. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15866. #endif
  15867. DEBUG_TRACE("Start processing connection from %s",
  15868. conn->request_info.remote_addr);
  15869. /* Loop over multiple requests sent using the same connection
  15870. * (while "keep alive"). */
  15871. do {
  15872. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15873. conn->handled_requests + 1);
  15874. #if defined(USE_SERVER_STATS)
  15875. conn->conn_state = 3; /* ready */
  15876. #endif
  15877. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15878. /* The request sent by the client could not be understood by
  15879. * the server, or it was incomplete or a timeout. Send an
  15880. * error message and close the connection. */
  15881. if (reqerr > 0) {
  15882. DEBUG_ASSERT(ebuf[0] != '\0');
  15883. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15884. }
  15885. } else if (strcmp(ri->http_version, "1.0")
  15886. && strcmp(ri->http_version, "1.1")) {
  15887. /* HTTP/2 is not allowed here */
  15888. mg_snprintf(conn,
  15889. NULL, /* No truncation check for ebuf */
  15890. ebuf,
  15891. sizeof(ebuf),
  15892. "Bad HTTP version: [%s]",
  15893. ri->http_version);
  15894. mg_send_http_error(conn, 505, "%s", ebuf);
  15895. }
  15896. if (ebuf[0] == '\0') {
  15897. uri_type = get_uri_type(conn->request_info.request_uri);
  15898. switch (uri_type) {
  15899. case 1:
  15900. /* Asterisk */
  15901. conn->request_info.local_uri_raw = 0;
  15902. /* TODO: Deal with '*'. */
  15903. break;
  15904. case 2:
  15905. /* relative uri */
  15906. conn->request_info.local_uri_raw =
  15907. conn->request_info.request_uri;
  15908. break;
  15909. case 3:
  15910. case 4:
  15911. /* absolute uri (with/without port) */
  15912. hostend = get_rel_url_at_current_server(
  15913. conn->request_info.request_uri, conn);
  15914. if (hostend) {
  15915. conn->request_info.local_uri_raw = hostend;
  15916. } else {
  15917. conn->request_info.local_uri_raw = NULL;
  15918. }
  15919. break;
  15920. default:
  15921. mg_snprintf(conn,
  15922. NULL, /* No truncation check for ebuf */
  15923. ebuf,
  15924. sizeof(ebuf),
  15925. "Invalid URI");
  15926. mg_send_http_error(conn, 400, "%s", ebuf);
  15927. conn->request_info.local_uri_raw = NULL;
  15928. break;
  15929. }
  15930. conn->request_info.local_uri =
  15931. (char *)conn->request_info.local_uri_raw;
  15932. #if defined(MG_LEGACY_INTERFACE)
  15933. /* Legacy before split into local_uri and request_uri */
  15934. conn->request_info.uri = conn->request_info.local_uri;
  15935. #endif
  15936. }
  15937. if (ebuf[0] != '\0') {
  15938. conn->protocol_type = -1;
  15939. } else {
  15940. /* HTTP/1 allows protocol upgrade */
  15941. conn->protocol_type = should_switch_to_protocol(conn);
  15942. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  15943. /* This will occur, if a HTTP/1.1 request should be upgraded
  15944. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  15945. * Since most (all?) major browsers only support HTTP/2 using
  15946. * ALPN, this is hard to test and very low priority.
  15947. * Deactivate it (at least for now).
  15948. */
  15949. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  15950. }
  15951. }
  15952. DEBUG_TRACE("http: %s, error: %s",
  15953. (ri->http_version ? ri->http_version : "none"),
  15954. (ebuf[0] ? ebuf : "none"));
  15955. if (ebuf[0] == '\0') {
  15956. if (conn->request_info.local_uri) {
  15957. /* handle request to local server */
  15958. handle_request_stat_log(conn);
  15959. } else {
  15960. /* TODO: handle non-local request (PROXY) */
  15961. conn->must_close = 1;
  15962. }
  15963. } else {
  15964. conn->must_close = 1;
  15965. }
  15966. /* Response complete. Free header buffer */
  15967. free_buffered_response_header_list(conn);
  15968. if (ri->remote_user != NULL) {
  15969. mg_free((void *)ri->remote_user);
  15970. /* Important! When having connections with and without auth
  15971. * would cause double free and then crash */
  15972. ri->remote_user = NULL;
  15973. }
  15974. /* NOTE(lsm): order is important here. should_keep_alive() call
  15975. * is using parsed request, which will be invalid after
  15976. * memmove's below.
  15977. * Therefore, memorize should_keep_alive() result now for later
  15978. * use in loop exit condition. */
  15979. /* Enable it only if this request is completely discardable. */
  15980. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  15981. && should_keep_alive(conn) && (conn->content_len >= 0)
  15982. && (conn->request_len > 0)
  15983. && ((conn->is_chunked == 4)
  15984. || (!conn->is_chunked
  15985. && ((conn->consumed_content == conn->content_len)
  15986. || ((conn->request_len + conn->content_len)
  15987. <= conn->data_len))))
  15988. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  15989. if (keep_alive) {
  15990. /* Discard all buffered data for this request */
  15991. discard_len =
  15992. ((conn->request_len + conn->content_len) < conn->data_len)
  15993. ? (int)(conn->request_len + conn->content_len)
  15994. : conn->data_len;
  15995. conn->data_len -= discard_len;
  15996. if (conn->data_len > 0) {
  15997. DEBUG_TRACE("discard_len = %d", discard_len);
  15998. memmove(conn->buf,
  15999. conn->buf + discard_len,
  16000. (size_t)conn->data_len);
  16001. }
  16002. }
  16003. DEBUG_ASSERT(conn->data_len >= 0);
  16004. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16005. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16006. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16007. (long int)conn->data_len,
  16008. (long int)conn->buf_size);
  16009. break;
  16010. }
  16011. conn->handled_requests++;
  16012. } while (keep_alive);
  16013. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16014. conn->request_info.remote_addr,
  16015. difftime(time(NULL), conn->conn_birth_time));
  16016. close_connection(conn);
  16017. #if defined(USE_SERVER_STATS)
  16018. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16019. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16020. #endif
  16021. }
  16022. #if defined(ALTERNATIVE_QUEUE)
  16023. static void
  16024. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16025. {
  16026. unsigned int i;
  16027. while (!ctx->stop_flag) {
  16028. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16029. /* find a free worker slot and signal it */
  16030. if (ctx->client_socks[i].in_use == 2) {
  16031. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16032. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16033. ctx->client_socks[i] = *sp;
  16034. ctx->client_socks[i].in_use = 1;
  16035. /* socket has been moved to the consumer */
  16036. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16037. (void)event_signal(ctx->client_wait_events[i]);
  16038. return;
  16039. }
  16040. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16041. }
  16042. }
  16043. /* queue is full */
  16044. mg_sleep(1);
  16045. }
  16046. /* must consume */
  16047. set_blocking_mode(sp->sock);
  16048. closesocket(sp->sock);
  16049. }
  16050. static int
  16051. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16052. {
  16053. DEBUG_TRACE("%s", "going idle");
  16054. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16055. ctx->client_socks[thread_index].in_use = 2;
  16056. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16057. event_wait(ctx->client_wait_events[thread_index]);
  16058. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16059. *sp = ctx->client_socks[thread_index];
  16060. if (ctx->stop_flag) {
  16061. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16062. if (sp->in_use == 1) {
  16063. /* must consume */
  16064. set_blocking_mode(sp->sock);
  16065. closesocket(sp->sock);
  16066. }
  16067. return 0;
  16068. }
  16069. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16070. if (sp->in_use == 1) {
  16071. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16072. return 1;
  16073. }
  16074. /* must not reach here */
  16075. DEBUG_ASSERT(0);
  16076. return 0;
  16077. }
  16078. #else /* ALTERNATIVE_QUEUE */
  16079. /* Worker threads take accepted socket from the queue */
  16080. static int
  16081. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16082. {
  16083. (void)thread_index;
  16084. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16085. DEBUG_TRACE("%s", "going idle");
  16086. /* If the queue is empty, wait. We're idle at this point. */
  16087. while ((ctx->sq_head == ctx->sq_tail)
  16088. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16089. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16090. }
  16091. /* If we're stopping, sq_head may be equal to sq_tail. */
  16092. if (ctx->sq_head > ctx->sq_tail) {
  16093. /* Copy socket from the queue and increment tail */
  16094. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16095. ctx->sq_tail++;
  16096. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16097. /* Wrap pointers if needed */
  16098. while (ctx->sq_tail > ctx->sq_size) {
  16099. ctx->sq_tail -= ctx->sq_size;
  16100. ctx->sq_head -= ctx->sq_size;
  16101. }
  16102. }
  16103. (void)pthread_cond_signal(&ctx->sq_empty);
  16104. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16105. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16106. }
  16107. /* Master thread adds accepted socket to a queue */
  16108. static void
  16109. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16110. {
  16111. int queue_filled;
  16112. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16113. queue_filled = ctx->sq_head - ctx->sq_tail;
  16114. /* If the queue is full, wait */
  16115. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16116. && (queue_filled >= ctx->sq_size)) {
  16117. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16118. #if defined(USE_SERVER_STATS)
  16119. if (queue_filled > ctx->sq_max_fill) {
  16120. ctx->sq_max_fill = queue_filled;
  16121. }
  16122. #endif
  16123. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16124. ctx->sq_blocked = 0; /* Not blocked now */
  16125. queue_filled = ctx->sq_head - ctx->sq_tail;
  16126. }
  16127. if (queue_filled < ctx->sq_size) {
  16128. /* Copy socket to the queue and increment head */
  16129. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16130. ctx->sq_head++;
  16131. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16132. }
  16133. queue_filled = ctx->sq_head - ctx->sq_tail;
  16134. #if defined(USE_SERVER_STATS)
  16135. if (queue_filled > ctx->sq_max_fill) {
  16136. ctx->sq_max_fill = queue_filled;
  16137. }
  16138. #endif
  16139. (void)pthread_cond_signal(&ctx->sq_full);
  16140. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16141. }
  16142. #endif /* ALTERNATIVE_QUEUE */
  16143. static void
  16144. worker_thread_run(struct mg_connection *conn)
  16145. {
  16146. struct mg_context *ctx = conn->phys_ctx;
  16147. int thread_index;
  16148. struct mg_workerTLS tls;
  16149. mg_set_thread_name("worker");
  16150. tls.is_master = 0;
  16151. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16152. #if defined(_WIN32)
  16153. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16154. #endif
  16155. /* Initialize thread local storage before calling any callback */
  16156. pthread_setspecific(sTlsKey, &tls);
  16157. /* Check if there is a user callback */
  16158. if (ctx->callbacks.init_thread) {
  16159. /* call init_thread for a worker thread (type 1), and store the
  16160. * return value */
  16161. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16162. } else {
  16163. /* No callback: set user pointer to NULL */
  16164. tls.user_ptr = NULL;
  16165. }
  16166. /* Connection structure has been pre-allocated */
  16167. thread_index = (int)(conn - ctx->worker_connections);
  16168. if ((thread_index < 0)
  16169. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16170. mg_cry_ctx_internal(ctx,
  16171. "Internal error: Invalid worker index %i",
  16172. thread_index);
  16173. return;
  16174. }
  16175. /* Request buffers are not pre-allocated. They are private to the
  16176. * request and do not contain any state information that might be
  16177. * of interest to anyone observing a server status. */
  16178. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16179. if (conn->buf == NULL) {
  16180. mg_cry_ctx_internal(
  16181. ctx,
  16182. "Out of memory: Cannot allocate buffer for worker %i",
  16183. thread_index);
  16184. return;
  16185. }
  16186. conn->buf_size = (int)ctx->max_request_size;
  16187. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16188. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16189. conn->request_info.user_data = ctx->user_data;
  16190. /* Allocate a mutex for this connection to allow communication both
  16191. * within the request handler and from elsewhere in the application
  16192. */
  16193. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16194. mg_free(conn->buf);
  16195. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16196. return;
  16197. }
  16198. #if defined(USE_SERVER_STATS)
  16199. conn->conn_state = 1; /* not consumed */
  16200. #endif
  16201. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16202. * signal sq_empty condvar to wake up the master waiting in
  16203. * produce_socket() */
  16204. while (consume_socket(ctx, &conn->client, thread_index)) {
  16205. /* New connections must start with new protocol negotiation */
  16206. tls.alpn_proto = NULL;
  16207. #if defined(USE_SERVER_STATS)
  16208. conn->conn_close_time = 0;
  16209. #endif
  16210. conn->conn_birth_time = time(NULL);
  16211. /* Fill in IP, port info early so even if SSL setup below fails,
  16212. * error handler would have the corresponding info.
  16213. * Thanks to Johannes Winkelmann for the patch.
  16214. */
  16215. conn->request_info.remote_port =
  16216. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16217. conn->request_info.server_port =
  16218. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16219. sockaddr_to_string(conn->request_info.remote_addr,
  16220. sizeof(conn->request_info.remote_addr),
  16221. &conn->client.rsa);
  16222. DEBUG_TRACE("Incomming %sconnection from %s",
  16223. (conn->client.is_ssl ? "SSL " : ""),
  16224. conn->request_info.remote_addr);
  16225. conn->request_info.is_ssl = conn->client.is_ssl;
  16226. if (conn->client.is_ssl) {
  16227. #if defined(USE_MBEDTLS)
  16228. /* HTTPS connection */
  16229. if (mbed_ssl_accept(&(conn->ssl),
  16230. conn->dom_ctx->ssl_ctx,
  16231. (int *)&(conn->client.sock),
  16232. conn->phys_ctx)
  16233. == 0) {
  16234. /* conn->dom_ctx is set in get_request */
  16235. /* process HTTPS connection */
  16236. init_connection(conn);
  16237. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16238. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16239. process_new_connection(conn);
  16240. } else {
  16241. /* make sure the connection is cleaned up on SSL failure */
  16242. close_connection(conn);
  16243. }
  16244. #elif !defined(NO_SSL)
  16245. /* HTTPS connection */
  16246. if (sslize(conn, SSL_accept, NULL)) {
  16247. /* conn->dom_ctx is set in get_request */
  16248. /* Get SSL client certificate information (if set) */
  16249. struct mg_client_cert client_cert;
  16250. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16251. conn->request_info.client_cert = &client_cert;
  16252. }
  16253. /* process HTTPS connection */
  16254. #if defined(USE_HTTP2)
  16255. if ((tls.alpn_proto != NULL)
  16256. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16257. /* process HTTPS/2 connection */
  16258. init_connection(conn);
  16259. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16260. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16261. conn->content_len =
  16262. -1; /* content length is not predefined */
  16263. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16264. process_new_http2_connection(conn);
  16265. } else
  16266. #endif
  16267. {
  16268. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16269. init_connection(conn);
  16270. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16271. /* Start with HTTP, WS will be an "upgrade" request later */
  16272. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16273. process_new_connection(conn);
  16274. }
  16275. /* Free client certificate info */
  16276. if (conn->request_info.client_cert) {
  16277. mg_free((void *)(conn->request_info.client_cert->subject));
  16278. mg_free((void *)(conn->request_info.client_cert->issuer));
  16279. mg_free((void *)(conn->request_info.client_cert->serial));
  16280. mg_free((void *)(conn->request_info.client_cert->finger));
  16281. /* Free certificate memory */
  16282. X509_free(
  16283. (X509 *)conn->request_info.client_cert->peer_cert);
  16284. conn->request_info.client_cert->peer_cert = 0;
  16285. conn->request_info.client_cert->subject = 0;
  16286. conn->request_info.client_cert->issuer = 0;
  16287. conn->request_info.client_cert->serial = 0;
  16288. conn->request_info.client_cert->finger = 0;
  16289. conn->request_info.client_cert = 0;
  16290. }
  16291. } else {
  16292. /* make sure the connection is cleaned up on SSL failure */
  16293. close_connection(conn);
  16294. }
  16295. #endif
  16296. } else {
  16297. /* process HTTP connection */
  16298. init_connection(conn);
  16299. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16300. /* Start with HTTP, WS will be an "upgrade" request later */
  16301. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16302. process_new_connection(conn);
  16303. }
  16304. DEBUG_TRACE("%s", "Connection closed");
  16305. #if defined(USE_SERVER_STATS)
  16306. conn->conn_close_time = time(NULL);
  16307. #endif
  16308. }
  16309. /* Call exit thread user callback */
  16310. if (ctx->callbacks.exit_thread) {
  16311. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16312. }
  16313. /* delete thread local storage objects */
  16314. pthread_setspecific(sTlsKey, NULL);
  16315. #if defined(_WIN32)
  16316. CloseHandle(tls.pthread_cond_helper_mutex);
  16317. #endif
  16318. pthread_mutex_destroy(&conn->mutex);
  16319. /* Free the request buffer. */
  16320. conn->buf_size = 0;
  16321. mg_free(conn->buf);
  16322. conn->buf = NULL;
  16323. /* Free cleaned URI (if any) */
  16324. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16325. mg_free((void *)conn->request_info.local_uri);
  16326. conn->request_info.local_uri = NULL;
  16327. }
  16328. #if defined(USE_SERVER_STATS)
  16329. conn->conn_state = 9; /* done */
  16330. #endif
  16331. DEBUG_TRACE("%s", "exiting");
  16332. }
  16333. /* Threads have different return types on Windows and Unix. */
  16334. #if defined(_WIN32)
  16335. static unsigned __stdcall worker_thread(void *thread_func_param)
  16336. {
  16337. worker_thread_run((struct mg_connection *)thread_func_param);
  16338. return 0;
  16339. }
  16340. #else
  16341. static void *
  16342. worker_thread(void *thread_func_param)
  16343. {
  16344. #if !defined(__ZEPHYR__)
  16345. struct sigaction sa;
  16346. /* Ignore SIGPIPE */
  16347. memset(&sa, 0, sizeof(sa));
  16348. sa.sa_handler = SIG_IGN;
  16349. sigaction(SIGPIPE, &sa, NULL);
  16350. #endif
  16351. worker_thread_run((struct mg_connection *)thread_func_param);
  16352. return NULL;
  16353. }
  16354. #endif /* _WIN32 */
  16355. /* This is an internal function, thus all arguments are expected to be
  16356. * valid - a NULL check is not required. */
  16357. static void
  16358. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16359. {
  16360. struct socket so;
  16361. char src_addr[IP_ADDR_STR_LEN];
  16362. socklen_t len = sizeof(so.rsa);
  16363. #if !defined(__ZEPHYR__)
  16364. int on = 1;
  16365. #endif
  16366. memset(&so, 0, sizeof(so));
  16367. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16368. == INVALID_SOCKET) {
  16369. } else if (check_acl(ctx, &so.rsa) != 1) {
  16370. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16371. mg_cry_ctx_internal(ctx,
  16372. "%s: %s is not allowed to connect",
  16373. __func__,
  16374. src_addr);
  16375. closesocket(so.sock);
  16376. } else {
  16377. /* Put so socket structure into the queue */
  16378. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16379. set_close_on_exec(so.sock, NULL, ctx);
  16380. so.is_ssl = listener->is_ssl;
  16381. so.ssl_redir = listener->ssl_redir;
  16382. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16383. mg_cry_ctx_internal(ctx,
  16384. "%s: getsockname() failed: %s",
  16385. __func__,
  16386. strerror(ERRNO));
  16387. }
  16388. #if !defined(__ZEPHYR__)
  16389. if ((so.lsa.sa.sa_family == AF_INET)
  16390. || (so.lsa.sa.sa_family == AF_INET6)) {
  16391. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16392. * This is needed because if HTTP-level keep-alive
  16393. * is enabled, and client resets the connection, server won't get
  16394. * TCP FIN or RST and will keep the connection open forever. With
  16395. * TCP keep-alive, next keep-alive handshake will figure out that
  16396. * the client is down and will close the server end.
  16397. * Thanks to Igor Klopov who suggested the patch. */
  16398. if (setsockopt(so.sock,
  16399. SOL_SOCKET,
  16400. SO_KEEPALIVE,
  16401. (SOCK_OPT_TYPE)&on,
  16402. sizeof(on))
  16403. != 0) {
  16404. mg_cry_ctx_internal(
  16405. ctx,
  16406. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16407. __func__,
  16408. strerror(ERRNO));
  16409. }
  16410. }
  16411. #endif
  16412. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16413. * to effectively fill up the underlying IP packet payload and
  16414. * reduce the overhead of sending lots of small buffers. However
  16415. * this hurts the server's throughput (ie. operations per second)
  16416. * when HTTP 1.1 persistent connections are used and the responses
  16417. * are relatively small (eg. less than 1400 bytes).
  16418. */
  16419. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16420. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16421. if (set_tcp_nodelay(&so, 1) != 0) {
  16422. mg_cry_ctx_internal(
  16423. ctx,
  16424. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16425. __func__,
  16426. strerror(ERRNO));
  16427. }
  16428. }
  16429. /* The "non blocking" property should already be
  16430. * inherited from the parent socket. Set it for
  16431. * non-compliant socket implementations. */
  16432. set_non_blocking_mode(so.sock);
  16433. so.in_use = 0;
  16434. produce_socket(ctx, &so);
  16435. }
  16436. }
  16437. static void
  16438. master_thread_run(struct mg_context *ctx)
  16439. {
  16440. struct mg_workerTLS tls;
  16441. struct mg_pollfd *pfd;
  16442. unsigned int i;
  16443. unsigned int workerthreadcount;
  16444. if (!ctx) {
  16445. return;
  16446. }
  16447. mg_set_thread_name("master");
  16448. /* Increase priority of the master thread */
  16449. #if defined(_WIN32)
  16450. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16451. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16452. int min_prio = sched_get_priority_min(SCHED_RR);
  16453. int max_prio = sched_get_priority_max(SCHED_RR);
  16454. if ((min_prio >= 0) && (max_prio >= 0)
  16455. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16456. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16457. struct sched_param sched_param = {0};
  16458. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16459. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16460. }
  16461. #endif
  16462. /* Initialize thread local storage */
  16463. #if defined(_WIN32)
  16464. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16465. #endif
  16466. tls.is_master = 1;
  16467. pthread_setspecific(sTlsKey, &tls);
  16468. if (ctx->callbacks.init_thread) {
  16469. /* Callback for the master thread (type 0) */
  16470. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16471. } else {
  16472. tls.user_ptr = NULL;
  16473. }
  16474. /* Lua background script "start" event */
  16475. #if defined(USE_LUA)
  16476. if (ctx->lua_background_state) {
  16477. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16478. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16479. /* call "start()" in Lua */
  16480. lua_getglobal(lstate, "start");
  16481. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16482. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16483. if (ret != 0) {
  16484. struct mg_connection fc;
  16485. lua_cry(fake_connection(&fc, ctx),
  16486. ret,
  16487. lstate,
  16488. "lua_background_script",
  16489. "start");
  16490. }
  16491. } else {
  16492. lua_pop(lstate, 1);
  16493. }
  16494. /* determine if there is a "log()" function in Lua background script */
  16495. lua_getglobal(lstate, "log");
  16496. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16497. ctx->lua_bg_log_available = 1;
  16498. }
  16499. lua_pop(lstate, 1);
  16500. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16501. }
  16502. #endif
  16503. /* Server starts *now* */
  16504. ctx->start_time = time(NULL);
  16505. /* Server accept loop */
  16506. pfd = ctx->listening_socket_fds;
  16507. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16508. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16509. pfd[i].fd = ctx->listening_sockets[i].sock;
  16510. pfd[i].events = POLLIN;
  16511. }
  16512. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  16513. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16514. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16515. * successful poll, and POLLIN is defined as
  16516. * (POLLRDNORM | POLLRDBAND)
  16517. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16518. * pfd[i].revents == POLLIN. */
  16519. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16520. && (pfd[i].revents & POLLIN)) {
  16521. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16522. }
  16523. }
  16524. }
  16525. }
  16526. /* Here stop_flag is 1 - Initiate shutdown. */
  16527. DEBUG_TRACE("%s", "stopping workers");
  16528. /* Stop signal received: somebody called mg_stop. Quit. */
  16529. close_all_listening_sockets(ctx);
  16530. /* Wakeup workers that are waiting for connections to handle. */
  16531. #if defined(ALTERNATIVE_QUEUE)
  16532. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16533. event_signal(ctx->client_wait_events[i]);
  16534. }
  16535. #else
  16536. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16537. pthread_cond_broadcast(&ctx->sq_full);
  16538. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16539. #endif
  16540. /* Join all worker threads to avoid leaking threads. */
  16541. workerthreadcount = ctx->cfg_worker_threads;
  16542. for (i = 0; i < workerthreadcount; i++) {
  16543. if (ctx->worker_threadids[i] != 0) {
  16544. mg_join_thread(ctx->worker_threadids[i]);
  16545. }
  16546. }
  16547. #if defined(USE_LUA)
  16548. /* Free Lua state of lua background task */
  16549. if (ctx->lua_background_state) {
  16550. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16551. ctx->lua_bg_log_available = 0;
  16552. /* call "stop()" in Lua */
  16553. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16554. lua_getglobal(lstate, "stop");
  16555. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16556. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16557. if (ret != 0) {
  16558. struct mg_connection fc;
  16559. lua_cry(fake_connection(&fc, ctx),
  16560. ret,
  16561. lstate,
  16562. "lua_background_script",
  16563. "stop");
  16564. }
  16565. }
  16566. lua_close(lstate);
  16567. ctx->lua_background_state = 0;
  16568. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16569. }
  16570. #endif
  16571. DEBUG_TRACE("%s", "exiting");
  16572. /* call exit thread callback */
  16573. if (ctx->callbacks.exit_thread) {
  16574. /* Callback for the master thread (type 0) */
  16575. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16576. }
  16577. #if defined(_WIN32)
  16578. CloseHandle(tls.pthread_cond_helper_mutex);
  16579. #endif
  16580. pthread_setspecific(sTlsKey, NULL);
  16581. /* Signal mg_stop() that we're done.
  16582. * WARNING: This must be the very last thing this
  16583. * thread does, as ctx becomes invalid after this line. */
  16584. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16585. }
  16586. /* Threads have different return types on Windows and Unix. */
  16587. #if defined(_WIN32)
  16588. static unsigned __stdcall master_thread(void *thread_func_param)
  16589. {
  16590. master_thread_run((struct mg_context *)thread_func_param);
  16591. return 0;
  16592. }
  16593. #else
  16594. static void *
  16595. master_thread(void *thread_func_param)
  16596. {
  16597. #if !defined(__ZEPHYR__)
  16598. struct sigaction sa;
  16599. /* Ignore SIGPIPE */
  16600. memset(&sa, 0, sizeof(sa));
  16601. sa.sa_handler = SIG_IGN;
  16602. sigaction(SIGPIPE, &sa, NULL);
  16603. #endif
  16604. master_thread_run((struct mg_context *)thread_func_param);
  16605. return NULL;
  16606. }
  16607. #endif /* _WIN32 */
  16608. static void
  16609. free_context(struct mg_context *ctx)
  16610. {
  16611. int i;
  16612. struct mg_handler_info *tmp_rh;
  16613. if (ctx == NULL) {
  16614. return;
  16615. }
  16616. /* Call user callback */
  16617. if (ctx->callbacks.exit_context) {
  16618. ctx->callbacks.exit_context(ctx);
  16619. }
  16620. /* All threads exited, no sync is needed. Destroy thread mutex and
  16621. * condvars
  16622. */
  16623. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16624. #if defined(ALTERNATIVE_QUEUE)
  16625. mg_free(ctx->client_socks);
  16626. if (ctx->client_wait_events != NULL) {
  16627. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16628. event_destroy(ctx->client_wait_events[i]);
  16629. }
  16630. mg_free(ctx->client_wait_events);
  16631. }
  16632. #else
  16633. (void)pthread_cond_destroy(&ctx->sq_empty);
  16634. (void)pthread_cond_destroy(&ctx->sq_full);
  16635. mg_free(ctx->squeue);
  16636. #endif
  16637. /* Destroy other context global data structures mutex */
  16638. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16639. #if defined(USE_LUA)
  16640. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  16641. #endif
  16642. /* Deallocate config parameters */
  16643. for (i = 0; i < NUM_OPTIONS; i++) {
  16644. if (ctx->dd.config[i] != NULL) {
  16645. #if defined(_MSC_VER)
  16646. #pragma warning(suppress : 6001)
  16647. #endif
  16648. mg_free(ctx->dd.config[i]);
  16649. }
  16650. }
  16651. /* Deallocate request handlers */
  16652. while (ctx->dd.handlers) {
  16653. tmp_rh = ctx->dd.handlers;
  16654. ctx->dd.handlers = tmp_rh->next;
  16655. mg_free(tmp_rh->uri);
  16656. mg_free(tmp_rh);
  16657. }
  16658. #if defined(USE_MBEDTLS)
  16659. if (ctx->dd.ssl_ctx != NULL) {
  16660. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16661. mg_free(ctx->dd.ssl_ctx);
  16662. ctx->dd.ssl_ctx = NULL;
  16663. }
  16664. #elif !defined(NO_SSL)
  16665. /* Deallocate SSL context */
  16666. if (ctx->dd.ssl_ctx != NULL) {
  16667. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16668. int callback_ret =
  16669. (ctx->callbacks.external_ssl_ctx == NULL)
  16670. ? 0
  16671. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16672. if (callback_ret == 0) {
  16673. SSL_CTX_free(ctx->dd.ssl_ctx);
  16674. }
  16675. /* else: ignore error and ommit SSL_CTX_free in case
  16676. * callback_ret is 1 */
  16677. }
  16678. #endif /* !NO_SSL */
  16679. /* Deallocate worker thread ID array */
  16680. mg_free(ctx->worker_threadids);
  16681. /* Deallocate worker thread ID array */
  16682. mg_free(ctx->worker_connections);
  16683. /* deallocate system name string */
  16684. mg_free(ctx->systemName);
  16685. /* Deallocate context itself */
  16686. mg_free(ctx);
  16687. }
  16688. void
  16689. mg_stop(struct mg_context *ctx)
  16690. {
  16691. pthread_t mt;
  16692. if (!ctx) {
  16693. return;
  16694. }
  16695. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16696. * two threads is not allowed. */
  16697. mt = ctx->masterthreadid;
  16698. if (mt == 0) {
  16699. return;
  16700. }
  16701. ctx->masterthreadid = 0;
  16702. /* Set stop flag, so all threads know they have to exit. */
  16703. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16704. /* Join timer thread */
  16705. #if defined(USE_TIMERS)
  16706. timers_exit(ctx);
  16707. #endif
  16708. /* Wait until everything has stopped. */
  16709. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16710. (void)mg_sleep(10);
  16711. }
  16712. /* Wait to stop master thread */
  16713. mg_join_thread(mt);
  16714. /* Close remaining Lua states */
  16715. #if defined(USE_LUA)
  16716. lua_ctx_exit(ctx);
  16717. #endif
  16718. /* Free memory */
  16719. free_context(ctx);
  16720. }
  16721. static void
  16722. get_system_name(char **sysName)
  16723. {
  16724. #if defined(_WIN32)
  16725. char name[128];
  16726. DWORD dwVersion = 0;
  16727. DWORD dwMajorVersion = 0;
  16728. DWORD dwMinorVersion = 0;
  16729. DWORD dwBuild = 0;
  16730. BOOL wowRet, isWoW = FALSE;
  16731. #if defined(_MSC_VER)
  16732. #pragma warning(push)
  16733. /* GetVersion was declared deprecated */
  16734. #pragma warning(disable : 4996)
  16735. #endif
  16736. dwVersion = GetVersion();
  16737. #if defined(_MSC_VER)
  16738. #pragma warning(pop)
  16739. #endif
  16740. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16741. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16742. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16743. (void)dwBuild;
  16744. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16745. sprintf(name,
  16746. "Windows %u.%u%s",
  16747. (unsigned)dwMajorVersion,
  16748. (unsigned)dwMinorVersion,
  16749. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16750. *sysName = mg_strdup(name);
  16751. #elif defined(__ZEPHYR__)
  16752. *sysName = mg_strdup("Zephyr OS");
  16753. #else
  16754. struct utsname name;
  16755. memset(&name, 0, sizeof(name));
  16756. uname(&name);
  16757. *sysName = mg_strdup(name.sysname);
  16758. #endif
  16759. }
  16760. static void
  16761. legacy_init(const char **options)
  16762. {
  16763. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16764. if (options) {
  16765. const char **run_options = options;
  16766. const char *optname = config_options[LISTENING_PORTS].name;
  16767. /* Try to find the "listening_ports" option */
  16768. while (*run_options) {
  16769. if (!strcmp(*run_options, optname)) {
  16770. ports_option = run_options[1];
  16771. }
  16772. run_options += 2;
  16773. }
  16774. }
  16775. if (is_ssl_port_used(ports_option)) {
  16776. /* Initialize with SSL support */
  16777. mg_init_library(MG_FEATURES_TLS);
  16778. } else {
  16779. /* Initialize without SSL support */
  16780. mg_init_library(MG_FEATURES_DEFAULT);
  16781. }
  16782. }
  16783. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16784. static
  16785. #endif
  16786. struct mg_context *
  16787. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16788. {
  16789. struct mg_context *ctx;
  16790. const char *name, *value, *default_value;
  16791. int idx, ok, workerthreadcount;
  16792. unsigned int i;
  16793. int itmp;
  16794. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16795. const char **options =
  16796. ((init != NULL) ? (init->configuration_options) : (NULL));
  16797. struct mg_workerTLS tls;
  16798. if (error != NULL) {
  16799. error->code = 0;
  16800. if (error->text_buffer_size > 0) {
  16801. *error->text = 0;
  16802. }
  16803. }
  16804. if (mg_init_library_called == 0) {
  16805. /* Legacy INIT, if mg_start is called without mg_init_library.
  16806. * Note: This will cause a memory leak when unloading the library.
  16807. */
  16808. legacy_init(options);
  16809. }
  16810. if (mg_init_library_called == 0) {
  16811. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16812. mg_snprintf(NULL,
  16813. NULL, /* No truncation check for error buffers */
  16814. error->text,
  16815. error->text_buffer_size,
  16816. "%s",
  16817. "Library uninitialized");
  16818. }
  16819. return NULL;
  16820. }
  16821. /* Allocate context and initialize reasonable general case defaults. */
  16822. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16823. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16824. mg_snprintf(NULL,
  16825. NULL, /* No truncation check for error buffers */
  16826. error->text,
  16827. error->text_buffer_size,
  16828. "%s",
  16829. "Out of memory");
  16830. }
  16831. return NULL;
  16832. }
  16833. /* Random number generator will initialize at the first call */
  16834. ctx->dd.auth_nonce_mask =
  16835. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16836. /* Save started thread index to reuse in other external API calls
  16837. * For the sake of thread synchronization all non-civetweb threads
  16838. * can be considered as single external thread */
  16839. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16840. tls.is_master = -1; /* Thread calling mg_start */
  16841. tls.thread_idx = ctx->starter_thread_idx;
  16842. #if defined(_WIN32)
  16843. tls.pthread_cond_helper_mutex = NULL;
  16844. #endif
  16845. pthread_setspecific(sTlsKey, &tls);
  16846. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16847. #if !defined(ALTERNATIVE_QUEUE)
  16848. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16849. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16850. ctx->sq_blocked = 0;
  16851. #endif
  16852. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16853. #if defined(USE_LUA)
  16854. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  16855. #endif
  16856. if (!ok) {
  16857. const char *err_msg =
  16858. "Cannot initialize thread synchronization objects";
  16859. /* Fatal error - abort start. However, this situation should never
  16860. * occur in practice. */
  16861. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16862. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16863. mg_snprintf(NULL,
  16864. NULL, /* No truncation check for error buffers */
  16865. error->text,
  16866. error->text_buffer_size,
  16867. "%s",
  16868. err_msg);
  16869. }
  16870. mg_free(ctx);
  16871. pthread_setspecific(sTlsKey, NULL);
  16872. return NULL;
  16873. }
  16874. if ((init != NULL) && (init->callbacks != NULL)) {
  16875. /* Set all callbacks except exit_context. */
  16876. ctx->callbacks = *init->callbacks;
  16877. exit_callback = init->callbacks->exit_context;
  16878. /* The exit callback is activated once the context is successfully
  16879. * created. It should not be called, if an incomplete context object
  16880. * is deleted during a failed initialization. */
  16881. ctx->callbacks.exit_context = 0;
  16882. }
  16883. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16884. ctx->dd.handlers = NULL;
  16885. ctx->dd.next = NULL;
  16886. #if defined(USE_LUA)
  16887. lua_ctx_init(ctx);
  16888. #endif
  16889. /* Store options */
  16890. while (options && (name = *options++) != NULL) {
  16891. if ((idx = get_option_index(name)) == -1) {
  16892. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16893. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16894. mg_snprintf(NULL,
  16895. NULL, /* No truncation check for error buffers */
  16896. error->text,
  16897. error->text_buffer_size,
  16898. "Invalid configuration option: %s",
  16899. name);
  16900. }
  16901. free_context(ctx);
  16902. pthread_setspecific(sTlsKey, NULL);
  16903. return NULL;
  16904. } else if ((value = *options++) == NULL) {
  16905. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16906. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16907. mg_snprintf(NULL,
  16908. NULL, /* No truncation check for error buffers */
  16909. error->text,
  16910. error->text_buffer_size,
  16911. "Invalid configuration option value: %s",
  16912. name);
  16913. }
  16914. free_context(ctx);
  16915. pthread_setspecific(sTlsKey, NULL);
  16916. return NULL;
  16917. }
  16918. if (ctx->dd.config[idx] != NULL) {
  16919. /* A duplicate configuration option is not an error - the last
  16920. * option value will be used. */
  16921. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16922. mg_free(ctx->dd.config[idx]);
  16923. }
  16924. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16925. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16926. }
  16927. /* Set default value if needed */
  16928. for (i = 0; config_options[i].name != NULL; i++) {
  16929. default_value = config_options[i].default_value;
  16930. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16931. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16932. }
  16933. }
  16934. /* Request size option */
  16935. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16936. if (itmp < 1024) {
  16937. mg_cry_ctx_internal(ctx,
  16938. "%s too small",
  16939. config_options[MAX_REQUEST_SIZE].name);
  16940. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16941. mg_snprintf(NULL,
  16942. NULL, /* No truncation check for error buffers */
  16943. error->text,
  16944. error->text_buffer_size,
  16945. "Invalid configuration option value: %s",
  16946. config_options[MAX_REQUEST_SIZE].name);
  16947. }
  16948. free_context(ctx);
  16949. pthread_setspecific(sTlsKey, NULL);
  16950. return NULL;
  16951. }
  16952. ctx->max_request_size = (unsigned)itmp;
  16953. /* Queue length */
  16954. #if !defined(ALTERNATIVE_QUEUE)
  16955. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  16956. if (itmp < 1) {
  16957. mg_cry_ctx_internal(ctx,
  16958. "%s too small",
  16959. config_options[CONNECTION_QUEUE_SIZE].name);
  16960. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16961. mg_snprintf(NULL,
  16962. NULL, /* No truncation check for error buffers */
  16963. error->text,
  16964. error->text_buffer_size,
  16965. "Invalid configuration option value: %s",
  16966. config_options[CONNECTION_QUEUE_SIZE].name);
  16967. }
  16968. free_context(ctx);
  16969. pthread_setspecific(sTlsKey, NULL);
  16970. return NULL;
  16971. }
  16972. ctx->squeue =
  16973. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  16974. if (ctx->squeue == NULL) {
  16975. mg_cry_ctx_internal(ctx,
  16976. "Out of memory: Cannot allocate %s",
  16977. config_options[CONNECTION_QUEUE_SIZE].name);
  16978. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16979. mg_snprintf(NULL,
  16980. NULL, /* No truncation check for error buffers */
  16981. error->text,
  16982. error->text_buffer_size,
  16983. "Out of memory: Cannot allocate %s",
  16984. config_options[CONNECTION_QUEUE_SIZE].name);
  16985. }
  16986. free_context(ctx);
  16987. pthread_setspecific(sTlsKey, NULL);
  16988. return NULL;
  16989. }
  16990. ctx->sq_size = itmp;
  16991. #endif
  16992. /* Worker thread count option */
  16993. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16994. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  16995. if (workerthreadcount <= 0) {
  16996. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16997. } else {
  16998. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16999. }
  17000. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17001. mg_snprintf(NULL,
  17002. NULL, /* No truncation check for error buffers */
  17003. error->text,
  17004. error->text_buffer_size,
  17005. "Invalid configuration option value: %s",
  17006. config_options[NUM_THREADS].name);
  17007. }
  17008. free_context(ctx);
  17009. pthread_setspecific(sTlsKey, NULL);
  17010. return NULL;
  17011. }
  17012. /* Document root */
  17013. #if defined(NO_FILES)
  17014. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17015. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17016. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17017. mg_snprintf(NULL,
  17018. NULL, /* No truncation check for error buffers */
  17019. error->text,
  17020. error->text_buffer_size,
  17021. "Invalid configuration option value: %s",
  17022. config_options[DOCUMENT_ROOT].name);
  17023. }
  17024. free_context(ctx);
  17025. pthread_setspecific(sTlsKey, NULL);
  17026. return NULL;
  17027. }
  17028. #endif
  17029. get_system_name(&ctx->systemName);
  17030. #if defined(USE_LUA)
  17031. /* If a Lua background script has been configured, start it. */
  17032. ctx->lua_bg_log_available = 0;
  17033. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17034. char ebuf[256];
  17035. struct vec opt_vec;
  17036. struct vec eq_vec;
  17037. const char *sparams;
  17038. memset(ebuf, 0, sizeof(ebuf));
  17039. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17040. /* Create a Lua state, load all standard libraries and the mg table */
  17041. lua_State *state = mg_lua_context_script_prepare(
  17042. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17043. if (!state) {
  17044. mg_cry_ctx_internal(ctx,
  17045. "lua_background_script load error: %s",
  17046. ebuf);
  17047. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17048. mg_snprintf(NULL,
  17049. NULL, /* No truncation check for error buffers */
  17050. error->text,
  17051. error->text_buffer_size,
  17052. "Error in script %s: %s",
  17053. config_options[LUA_BACKGROUND_SCRIPT].name,
  17054. ebuf);
  17055. }
  17056. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17057. free_context(ctx);
  17058. pthread_setspecific(sTlsKey, NULL);
  17059. return NULL;
  17060. }
  17061. /* Add a table with parameters into mg.params */
  17062. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17063. if (sparams && sparams[0]) {
  17064. lua_getglobal(state, "mg");
  17065. lua_pushstring(state, "params");
  17066. lua_newtable(state);
  17067. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17068. != NULL) {
  17069. reg_llstring(
  17070. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17071. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17072. break;
  17073. }
  17074. lua_rawset(state, -3);
  17075. lua_pop(state, 1);
  17076. }
  17077. /* Call script */
  17078. state = mg_lua_context_script_run(state,
  17079. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17080. ctx,
  17081. ebuf,
  17082. sizeof(ebuf));
  17083. if (!state) {
  17084. mg_cry_ctx_internal(ctx,
  17085. "lua_background_script start error: %s",
  17086. ebuf);
  17087. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17088. mg_snprintf(NULL,
  17089. NULL, /* No truncation check for error buffers */
  17090. error->text,
  17091. error->text_buffer_size,
  17092. "Error in script %s: %s",
  17093. config_options[DOCUMENT_ROOT].name,
  17094. ebuf);
  17095. }
  17096. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17097. free_context(ctx);
  17098. pthread_setspecific(sTlsKey, NULL);
  17099. return NULL;
  17100. }
  17101. /* state remains valid */
  17102. ctx->lua_background_state = (void *)state;
  17103. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17104. } else {
  17105. ctx->lua_background_state = 0;
  17106. }
  17107. #endif
  17108. /* Step by step initialization of ctx - depending on build options */
  17109. #if !defined(NO_FILESYSTEMS)
  17110. if (!set_gpass_option(ctx, NULL)) {
  17111. const char *err_msg = "Invalid global password file";
  17112. /* Fatal error - abort start. */
  17113. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17114. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17115. mg_snprintf(NULL,
  17116. NULL, /* No truncation check for error buffers */
  17117. error->text,
  17118. error->text_buffer_size,
  17119. "%s",
  17120. err_msg);
  17121. }
  17122. free_context(ctx);
  17123. pthread_setspecific(sTlsKey, NULL);
  17124. return NULL;
  17125. }
  17126. #endif
  17127. #if defined(USE_MBEDTLS)
  17128. if (!mg_sslctx_init(ctx, NULL)) {
  17129. const char *err_msg = "Error initializing SSL context";
  17130. /* Fatal error - abort start. */
  17131. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17132. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17133. mg_snprintf(NULL,
  17134. NULL, /* No truncation check for error buffers */
  17135. error->text,
  17136. error->text_buffer_size,
  17137. "%s",
  17138. err_msg);
  17139. }
  17140. free_context(ctx);
  17141. pthread_setspecific(sTlsKey, NULL);
  17142. return NULL;
  17143. }
  17144. #elif !defined(NO_SSL)
  17145. if (!init_ssl_ctx(ctx, NULL)) {
  17146. const char *err_msg = "Error initializing SSL context";
  17147. /* Fatal error - abort start. */
  17148. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17149. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17150. mg_snprintf(NULL,
  17151. NULL, /* No truncation check for error buffers */
  17152. error->text,
  17153. error->text_buffer_size,
  17154. "%s",
  17155. err_msg);
  17156. }
  17157. free_context(ctx);
  17158. pthread_setspecific(sTlsKey, NULL);
  17159. return NULL;
  17160. }
  17161. #endif
  17162. if (!set_ports_option(ctx)) {
  17163. const char *err_msg = "Failed to setup server ports";
  17164. /* Fatal error - abort start. */
  17165. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17166. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17167. mg_snprintf(NULL,
  17168. NULL, /* No truncation check for error buffers */
  17169. error->text,
  17170. error->text_buffer_size,
  17171. "%s",
  17172. err_msg);
  17173. }
  17174. free_context(ctx);
  17175. pthread_setspecific(sTlsKey, NULL);
  17176. return NULL;
  17177. }
  17178. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17179. if (!set_uid_option(ctx)) {
  17180. const char *err_msg = "Failed to run as configured user";
  17181. /* Fatal error - abort start. */
  17182. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17183. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17184. mg_snprintf(NULL,
  17185. NULL, /* No truncation check for error buffers */
  17186. error->text,
  17187. error->text_buffer_size,
  17188. "%s",
  17189. err_msg);
  17190. }
  17191. free_context(ctx);
  17192. pthread_setspecific(sTlsKey, NULL);
  17193. return NULL;
  17194. }
  17195. #endif
  17196. if (!set_acl_option(ctx)) {
  17197. const char *err_msg = "Failed to setup access control list";
  17198. /* Fatal error - abort start. */
  17199. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17200. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17201. mg_snprintf(NULL,
  17202. NULL, /* No truncation check for error buffers */
  17203. error->text,
  17204. error->text_buffer_size,
  17205. "%s",
  17206. err_msg);
  17207. }
  17208. free_context(ctx);
  17209. pthread_setspecific(sTlsKey, NULL);
  17210. return NULL;
  17211. }
  17212. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17213. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17214. sizeof(pthread_t),
  17215. ctx);
  17216. if (ctx->worker_threadids == NULL) {
  17217. const char *err_msg = "Not enough memory for worker thread ID array";
  17218. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17219. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17220. mg_snprintf(NULL,
  17221. NULL, /* No truncation check for error buffers */
  17222. error->text,
  17223. error->text_buffer_size,
  17224. "%s",
  17225. err_msg);
  17226. }
  17227. free_context(ctx);
  17228. pthread_setspecific(sTlsKey, NULL);
  17229. return NULL;
  17230. }
  17231. ctx->worker_connections =
  17232. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17233. sizeof(struct mg_connection),
  17234. ctx);
  17235. if (ctx->worker_connections == NULL) {
  17236. const char *err_msg =
  17237. "Not enough memory for worker thread connection array";
  17238. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17239. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17240. mg_snprintf(NULL,
  17241. NULL, /* No truncation check for error buffers */
  17242. error->text,
  17243. error->text_buffer_size,
  17244. "%s",
  17245. err_msg);
  17246. }
  17247. free_context(ctx);
  17248. pthread_setspecific(sTlsKey, NULL);
  17249. return NULL;
  17250. }
  17251. #if defined(ALTERNATIVE_QUEUE)
  17252. ctx->client_wait_events =
  17253. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17254. sizeof(ctx->client_wait_events[0]),
  17255. ctx);
  17256. if (ctx->client_wait_events == NULL) {
  17257. const char *err_msg = "Not enough memory for worker event array";
  17258. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17259. mg_free(ctx->worker_threadids);
  17260. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17261. mg_snprintf(NULL,
  17262. NULL, /* No truncation check for error buffers */
  17263. error->text,
  17264. error->text_buffer_size,
  17265. "%s",
  17266. err_msg);
  17267. }
  17268. free_context(ctx);
  17269. pthread_setspecific(sTlsKey, NULL);
  17270. return NULL;
  17271. }
  17272. ctx->client_socks =
  17273. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17274. sizeof(ctx->client_socks[0]),
  17275. ctx);
  17276. if (ctx->client_socks == NULL) {
  17277. const char *err_msg = "Not enough memory for worker socket array";
  17278. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17279. mg_free(ctx->client_wait_events);
  17280. mg_free(ctx->worker_threadids);
  17281. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17282. mg_snprintf(NULL,
  17283. NULL, /* No truncation check for error buffers */
  17284. error->text,
  17285. error->text_buffer_size,
  17286. "%s",
  17287. err_msg);
  17288. }
  17289. free_context(ctx);
  17290. pthread_setspecific(sTlsKey, NULL);
  17291. return NULL;
  17292. }
  17293. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17294. ctx->client_wait_events[i] = event_create();
  17295. if (ctx->client_wait_events[i] == 0) {
  17296. const char *err_msg = "Error creating worker event %i";
  17297. mg_cry_ctx_internal(ctx, err_msg, i);
  17298. while (i > 0) {
  17299. i--;
  17300. event_destroy(ctx->client_wait_events[i]);
  17301. }
  17302. mg_free(ctx->client_socks);
  17303. mg_free(ctx->client_wait_events);
  17304. mg_free(ctx->worker_threadids);
  17305. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17306. mg_snprintf(NULL,
  17307. NULL, /* No truncation check for error buffers */
  17308. error->text,
  17309. error->text_buffer_size,
  17310. err_msg,
  17311. i);
  17312. }
  17313. free_context(ctx);
  17314. pthread_setspecific(sTlsKey, NULL);
  17315. return NULL;
  17316. }
  17317. }
  17318. #endif
  17319. #if defined(USE_TIMERS)
  17320. if (timers_init(ctx) != 0) {
  17321. const char *err_msg = "Error creating timers";
  17322. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17323. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17324. mg_snprintf(NULL,
  17325. NULL, /* No truncation check for error buffers */
  17326. error->text,
  17327. error->text_buffer_size,
  17328. "%s",
  17329. err_msg);
  17330. }
  17331. free_context(ctx);
  17332. pthread_setspecific(sTlsKey, NULL);
  17333. return NULL;
  17334. }
  17335. #endif
  17336. /* Context has been created - init user libraries */
  17337. if (ctx->callbacks.init_context) {
  17338. ctx->callbacks.init_context(ctx);
  17339. }
  17340. /* From now, the context is successfully created.
  17341. * When it is destroyed, the exit callback should be called. */
  17342. ctx->callbacks.exit_context = exit_callback;
  17343. ctx->context_type = CONTEXT_SERVER; /* server context */
  17344. /* Start worker threads */
  17345. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17346. /* worker_thread sets up the other fields */
  17347. ctx->worker_connections[i].phys_ctx = ctx;
  17348. if (mg_start_thread_with_id(worker_thread,
  17349. &ctx->worker_connections[i],
  17350. &ctx->worker_threadids[i])
  17351. != 0) {
  17352. long error_no = (long)ERRNO;
  17353. /* thread was not created */
  17354. if (i > 0) {
  17355. /* If the second, third, ... thread cannot be created, set a
  17356. * warning, but keep running. */
  17357. mg_cry_ctx_internal(ctx,
  17358. "Cannot start worker thread %i: error %ld",
  17359. i + 1,
  17360. error_no);
  17361. /* If the server initialization should stop here, all
  17362. * threads that have already been created must be stopped
  17363. * first, before any free_context(ctx) call.
  17364. */
  17365. } else {
  17366. /* If the first worker thread cannot be created, stop
  17367. * initialization and free the entire server context. */
  17368. mg_cry_ctx_internal(ctx,
  17369. "Cannot create threads: error %ld",
  17370. error_no);
  17371. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17372. mg_snprintf(
  17373. NULL,
  17374. NULL, /* No truncation check for error buffers */
  17375. error->text,
  17376. error->text_buffer_size,
  17377. "Cannot create first worker thread: error %ld",
  17378. error_no);
  17379. }
  17380. free_context(ctx);
  17381. pthread_setspecific(sTlsKey, NULL);
  17382. return NULL;
  17383. }
  17384. break;
  17385. }
  17386. }
  17387. /* Start master (listening) thread */
  17388. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17389. pthread_setspecific(sTlsKey, NULL);
  17390. return ctx;
  17391. }
  17392. struct mg_context *
  17393. mg_start(const struct mg_callbacks *callbacks,
  17394. void *user_data,
  17395. const char **options)
  17396. {
  17397. struct mg_init_data init = {0};
  17398. init.callbacks = callbacks;
  17399. init.user_data = user_data;
  17400. init.configuration_options = options;
  17401. return mg_start2(&init, NULL);
  17402. }
  17403. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17404. /* Add an additional domain to an already running web server. */
  17405. int
  17406. mg_start_domain2(struct mg_context *ctx,
  17407. const char **options,
  17408. struct mg_error_data *error)
  17409. {
  17410. const char *name;
  17411. const char *value;
  17412. const char *default_value;
  17413. struct mg_domain_context *new_dom;
  17414. struct mg_domain_context *dom;
  17415. int idx, i;
  17416. if (error != NULL) {
  17417. error->code = 0;
  17418. if (error->text_buffer_size > 0) {
  17419. *error->text = 0;
  17420. }
  17421. }
  17422. if ((ctx == NULL) || (options == NULL)) {
  17423. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17424. mg_snprintf(NULL,
  17425. NULL, /* No truncation check for error buffers */
  17426. error->text,
  17427. error->text_buffer_size,
  17428. "%s",
  17429. "Invalid parameters");
  17430. }
  17431. return -1;
  17432. }
  17433. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17434. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17435. mg_snprintf(NULL,
  17436. NULL, /* No truncation check for error buffers */
  17437. error->text,
  17438. error->text_buffer_size,
  17439. "%s",
  17440. "Server already stopped");
  17441. }
  17442. return -1;
  17443. }
  17444. new_dom = (struct mg_domain_context *)
  17445. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17446. if (!new_dom) {
  17447. /* Out of memory */
  17448. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17449. mg_snprintf(NULL,
  17450. NULL, /* No truncation check for error buffers */
  17451. error->text,
  17452. error->text_buffer_size,
  17453. "%s",
  17454. "Out or memory");
  17455. }
  17456. return -6;
  17457. }
  17458. /* Store options - TODO: unite duplicate code */
  17459. while (options && (name = *options++) != NULL) {
  17460. if ((idx = get_option_index(name)) == -1) {
  17461. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17462. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17463. mg_snprintf(NULL,
  17464. NULL, /* No truncation check for error buffers */
  17465. error->text,
  17466. error->text_buffer_size,
  17467. "Invalid option: %s",
  17468. name);
  17469. }
  17470. mg_free(new_dom);
  17471. return -2;
  17472. } else if ((value = *options++) == NULL) {
  17473. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17474. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17475. mg_snprintf(NULL,
  17476. NULL, /* No truncation check for error buffers */
  17477. error->text,
  17478. error->text_buffer_size,
  17479. "Invalid option value: %s",
  17480. name);
  17481. }
  17482. mg_free(new_dom);
  17483. return -2;
  17484. }
  17485. if (new_dom->config[idx] != NULL) {
  17486. /* Duplicate option: Later values overwrite earlier ones. */
  17487. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17488. mg_free(new_dom->config[idx]);
  17489. }
  17490. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17491. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17492. }
  17493. /* Authentication domain is mandatory */
  17494. /* TODO: Maybe use a new option hostname? */
  17495. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17496. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17497. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17498. mg_snprintf(NULL,
  17499. NULL, /* No truncation check for error buffers */
  17500. error->text,
  17501. error->text_buffer_size,
  17502. "Mandatory option %s missing",
  17503. config_options[AUTHENTICATION_DOMAIN].name);
  17504. }
  17505. mg_free(new_dom);
  17506. return -4;
  17507. }
  17508. /* Set default value if needed. Take the config value from
  17509. * ctx as a default value. */
  17510. for (i = 0; config_options[i].name != NULL; i++) {
  17511. default_value = ctx->dd.config[i];
  17512. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17513. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17514. }
  17515. }
  17516. new_dom->handlers = NULL;
  17517. new_dom->next = NULL;
  17518. new_dom->nonce_count = 0;
  17519. new_dom->auth_nonce_mask =
  17520. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17521. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17522. new_dom->shared_lua_websockets = NULL;
  17523. #endif
  17524. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  17525. if (!init_ssl_ctx(ctx, new_dom)) {
  17526. /* Init SSL failed */
  17527. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17528. mg_snprintf(NULL,
  17529. NULL, /* No truncation check for error buffers */
  17530. error->text,
  17531. error->text_buffer_size,
  17532. "%s",
  17533. "Initializing SSL context failed");
  17534. }
  17535. mg_free(new_dom);
  17536. return -3;
  17537. }
  17538. #endif
  17539. /* Add element to linked list. */
  17540. mg_lock_context(ctx);
  17541. idx = 0;
  17542. dom = &(ctx->dd);
  17543. for (;;) {
  17544. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17545. dom->config[AUTHENTICATION_DOMAIN])) {
  17546. /* Domain collision */
  17547. mg_cry_ctx_internal(ctx,
  17548. "domain %s already in use",
  17549. new_dom->config[AUTHENTICATION_DOMAIN]);
  17550. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17551. mg_snprintf(NULL,
  17552. NULL, /* No truncation check for error buffers */
  17553. error->text,
  17554. error->text_buffer_size,
  17555. "Domain %s specified by %s is already in use",
  17556. new_dom->config[AUTHENTICATION_DOMAIN],
  17557. config_options[AUTHENTICATION_DOMAIN].name);
  17558. }
  17559. mg_free(new_dom);
  17560. mg_unlock_context(ctx);
  17561. return -5;
  17562. }
  17563. /* Count number of domains */
  17564. idx++;
  17565. if (dom->next == NULL) {
  17566. dom->next = new_dom;
  17567. break;
  17568. }
  17569. dom = dom->next;
  17570. }
  17571. mg_unlock_context(ctx);
  17572. /* Return domain number */
  17573. return idx;
  17574. }
  17575. int
  17576. mg_start_domain(struct mg_context *ctx, const char **options)
  17577. {
  17578. return mg_start_domain2(ctx, options, NULL);
  17579. }
  17580. #endif
  17581. /* Feature check API function */
  17582. unsigned
  17583. mg_check_feature(unsigned feature)
  17584. {
  17585. static const unsigned feature_set = 0
  17586. /* Set bits for available features according to API documentation.
  17587. * This bit mask is created at compile time, according to the active
  17588. * preprocessor defines. It is a single const value at runtime. */
  17589. #if !defined(NO_FILES)
  17590. | MG_FEATURES_FILES
  17591. #endif
  17592. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17593. | MG_FEATURES_SSL
  17594. #endif
  17595. #if !defined(NO_CGI)
  17596. | MG_FEATURES_CGI
  17597. #endif
  17598. #if defined(USE_IPV6)
  17599. | MG_FEATURES_IPV6
  17600. #endif
  17601. #if defined(USE_WEBSOCKET)
  17602. | MG_FEATURES_WEBSOCKET
  17603. #endif
  17604. #if defined(USE_LUA)
  17605. | MG_FEATURES_LUA
  17606. #endif
  17607. #if defined(USE_DUKTAPE)
  17608. | MG_FEATURES_SSJS
  17609. #endif
  17610. #if !defined(NO_CACHING)
  17611. | MG_FEATURES_CACHE
  17612. #endif
  17613. #if defined(USE_SERVER_STATS)
  17614. | MG_FEATURES_STATS
  17615. #endif
  17616. #if defined(USE_ZLIB)
  17617. | MG_FEATURES_COMPRESSION
  17618. #endif
  17619. #if defined(USE_HTTP2)
  17620. | MG_FEATURES_HTTP2
  17621. #endif
  17622. #if defined(USE_X_DOM_SOCKET)
  17623. | MG_FEATURES_X_DOMAIN_SOCKET
  17624. #endif
  17625. /* Set some extra bits not defined in the API documentation.
  17626. * These bits may change without further notice. */
  17627. #if defined(MG_LEGACY_INTERFACE)
  17628. | 0x80000000u
  17629. #endif
  17630. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17631. | 0x40000000u
  17632. #endif
  17633. #if !defined(NO_RESPONSE_BUFFERING)
  17634. | 0x20000000u
  17635. #endif
  17636. #if defined(MEMORY_DEBUGGING)
  17637. | 0x10000000u
  17638. #endif
  17639. ;
  17640. return (feature & feature_set);
  17641. }
  17642. static size_t
  17643. mg_str_append(char **dst, char *end, const char *src)
  17644. {
  17645. size_t len = strlen(src);
  17646. if (*dst != end) {
  17647. /* Append src if enough space, or close dst. */
  17648. if ((size_t)(end - *dst) > len) {
  17649. strcpy(*dst, src);
  17650. *dst += len;
  17651. } else {
  17652. *dst = end;
  17653. }
  17654. }
  17655. return len;
  17656. }
  17657. /* Get system information. It can be printed or stored by the caller.
  17658. * Return the size of available information. */
  17659. int
  17660. mg_get_system_info(char *buffer, int buflen)
  17661. {
  17662. char *end, *append_eoobj = NULL, block[256];
  17663. size_t system_info_length = 0;
  17664. #if defined(_WIN32)
  17665. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17666. #else
  17667. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17668. #endif
  17669. if ((buffer == NULL) || (buflen < 1)) {
  17670. buflen = 0;
  17671. end = buffer;
  17672. } else {
  17673. *buffer = 0;
  17674. end = buffer + buflen;
  17675. }
  17676. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17677. /* has enough space to append eoobj */
  17678. append_eoobj = buffer;
  17679. if (end) {
  17680. end -= sizeof(eoobj) - 1;
  17681. }
  17682. }
  17683. system_info_length += mg_str_append(&buffer, end, "{");
  17684. /* Server version */
  17685. {
  17686. const char *version = mg_version();
  17687. mg_snprintf(NULL,
  17688. NULL,
  17689. block,
  17690. sizeof(block),
  17691. "%s\"version\" : \"%s\"",
  17692. eol,
  17693. version);
  17694. system_info_length += mg_str_append(&buffer, end, block);
  17695. }
  17696. /* System info */
  17697. {
  17698. #if defined(_WIN32)
  17699. DWORD dwVersion = 0;
  17700. DWORD dwMajorVersion = 0;
  17701. DWORD dwMinorVersion = 0;
  17702. SYSTEM_INFO si;
  17703. GetSystemInfo(&si);
  17704. #if defined(_MSC_VER)
  17705. #pragma warning(push)
  17706. /* GetVersion was declared deprecated */
  17707. #pragma warning(disable : 4996)
  17708. #endif
  17709. dwVersion = GetVersion();
  17710. #if defined(_MSC_VER)
  17711. #pragma warning(pop)
  17712. #endif
  17713. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17714. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17715. mg_snprintf(NULL,
  17716. NULL,
  17717. block,
  17718. sizeof(block),
  17719. ",%s\"os\" : \"Windows %u.%u\"",
  17720. eol,
  17721. (unsigned)dwMajorVersion,
  17722. (unsigned)dwMinorVersion);
  17723. system_info_length += mg_str_append(&buffer, end, block);
  17724. mg_snprintf(NULL,
  17725. NULL,
  17726. block,
  17727. sizeof(block),
  17728. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17729. eol,
  17730. (unsigned)si.wProcessorArchitecture,
  17731. (unsigned)si.dwNumberOfProcessors,
  17732. (unsigned)si.dwActiveProcessorMask);
  17733. system_info_length += mg_str_append(&buffer, end, block);
  17734. #elif defined(__ZEPHYR__)
  17735. mg_snprintf(NULL,
  17736. NULL,
  17737. block,
  17738. sizeof(block),
  17739. ",%s\"os\" : \"%s %s\"",
  17740. eol,
  17741. "Zephyr OS",
  17742. ZEPHYR_VERSION);
  17743. system_info_length += mg_str_append(&buffer, end, block);
  17744. #else
  17745. struct utsname name;
  17746. memset(&name, 0, sizeof(name));
  17747. uname(&name);
  17748. mg_snprintf(NULL,
  17749. NULL,
  17750. block,
  17751. sizeof(block),
  17752. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17753. eol,
  17754. name.sysname,
  17755. name.version,
  17756. name.release,
  17757. name.machine);
  17758. system_info_length += mg_str_append(&buffer, end, block);
  17759. #endif
  17760. }
  17761. /* Features */
  17762. {
  17763. mg_snprintf(NULL,
  17764. NULL,
  17765. block,
  17766. sizeof(block),
  17767. ",%s\"features\" : %lu"
  17768. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17769. eol,
  17770. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17771. eol,
  17772. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17773. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17774. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17775. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17776. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17777. : "",
  17778. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17779. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17780. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17781. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17782. system_info_length += mg_str_append(&buffer, end, block);
  17783. #if defined(USE_LUA)
  17784. mg_snprintf(NULL,
  17785. NULL,
  17786. block,
  17787. sizeof(block),
  17788. ",%s\"lua_version\" : \"%u (%s)\"",
  17789. eol,
  17790. (unsigned)LUA_VERSION_NUM,
  17791. LUA_RELEASE);
  17792. system_info_length += mg_str_append(&buffer, end, block);
  17793. #endif
  17794. #if defined(USE_DUKTAPE)
  17795. mg_snprintf(NULL,
  17796. NULL,
  17797. block,
  17798. sizeof(block),
  17799. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17800. eol,
  17801. (unsigned)DUK_VERSION / 10000,
  17802. ((unsigned)DUK_VERSION / 100) % 100,
  17803. (unsigned)DUK_VERSION % 100);
  17804. system_info_length += mg_str_append(&buffer, end, block);
  17805. #endif
  17806. }
  17807. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  17808. {
  17809. #if defined(BUILD_DATE)
  17810. const char *bd = BUILD_DATE;
  17811. #else
  17812. #if defined(GCC_DIAGNOSTIC)
  17813. #if GCC_VERSION >= 40900
  17814. #pragma GCC diagnostic push
  17815. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  17816. * does not work in some versions. If "BUILD_DATE" is defined to some
  17817. * string, it is used instead of __DATE__. */
  17818. #pragma GCC diagnostic ignored "-Wdate-time"
  17819. #endif
  17820. #endif
  17821. const char *bd = __DATE__;
  17822. #if defined(GCC_DIAGNOSTIC)
  17823. #if GCC_VERSION >= 40900
  17824. #pragma GCC diagnostic pop
  17825. #endif
  17826. #endif
  17827. #endif
  17828. mg_snprintf(
  17829. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17830. system_info_length += mg_str_append(&buffer, end, block);
  17831. }
  17832. /* Compiler information */
  17833. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17834. {
  17835. #if defined(_MSC_VER)
  17836. mg_snprintf(NULL,
  17837. NULL,
  17838. block,
  17839. sizeof(block),
  17840. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17841. eol,
  17842. (unsigned)_MSC_VER,
  17843. (unsigned)_MSC_FULL_VER);
  17844. system_info_length += mg_str_append(&buffer, end, block);
  17845. #elif defined(__MINGW64__)
  17846. mg_snprintf(NULL,
  17847. NULL,
  17848. block,
  17849. sizeof(block),
  17850. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17851. eol,
  17852. (unsigned)__MINGW64_VERSION_MAJOR,
  17853. (unsigned)__MINGW64_VERSION_MINOR);
  17854. system_info_length += mg_str_append(&buffer, end, block);
  17855. mg_snprintf(NULL,
  17856. NULL,
  17857. block,
  17858. sizeof(block),
  17859. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17860. eol,
  17861. (unsigned)__MINGW32_MAJOR_VERSION,
  17862. (unsigned)__MINGW32_MINOR_VERSION);
  17863. system_info_length += mg_str_append(&buffer, end, block);
  17864. #elif defined(__MINGW32__)
  17865. mg_snprintf(NULL,
  17866. NULL,
  17867. block,
  17868. sizeof(block),
  17869. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17870. eol,
  17871. (unsigned)__MINGW32_MAJOR_VERSION,
  17872. (unsigned)__MINGW32_MINOR_VERSION);
  17873. system_info_length += mg_str_append(&buffer, end, block);
  17874. #elif defined(__clang__)
  17875. mg_snprintf(NULL,
  17876. NULL,
  17877. block,
  17878. sizeof(block),
  17879. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17880. eol,
  17881. __clang_major__,
  17882. __clang_minor__,
  17883. __clang_patchlevel__,
  17884. __clang_version__);
  17885. system_info_length += mg_str_append(&buffer, end, block);
  17886. #elif defined(__GNUC__)
  17887. mg_snprintf(NULL,
  17888. NULL,
  17889. block,
  17890. sizeof(block),
  17891. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17892. eol,
  17893. (unsigned)__GNUC__,
  17894. (unsigned)__GNUC_MINOR__,
  17895. (unsigned)__GNUC_PATCHLEVEL__);
  17896. system_info_length += mg_str_append(&buffer, end, block);
  17897. #elif defined(__INTEL_COMPILER)
  17898. mg_snprintf(NULL,
  17899. NULL,
  17900. block,
  17901. sizeof(block),
  17902. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17903. eol,
  17904. (unsigned)__INTEL_COMPILER);
  17905. system_info_length += mg_str_append(&buffer, end, block);
  17906. #elif defined(__BORLANDC__)
  17907. mg_snprintf(NULL,
  17908. NULL,
  17909. block,
  17910. sizeof(block),
  17911. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17912. eol,
  17913. (unsigned)__BORLANDC__);
  17914. system_info_length += mg_str_append(&buffer, end, block);
  17915. #elif defined(__SUNPRO_C)
  17916. mg_snprintf(NULL,
  17917. NULL,
  17918. block,
  17919. sizeof(block),
  17920. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17921. eol,
  17922. (unsigned)__SUNPRO_C);
  17923. system_info_length += mg_str_append(&buffer, end, block);
  17924. #else
  17925. mg_snprintf(NULL,
  17926. NULL,
  17927. block,
  17928. sizeof(block),
  17929. ",%s\"compiler\" : \"other\"",
  17930. eol);
  17931. system_info_length += mg_str_append(&buffer, end, block);
  17932. #endif
  17933. }
  17934. /* Determine 32/64 bit data mode.
  17935. * see https://en.wikipedia.org/wiki/64-bit_computing */
  17936. {
  17937. mg_snprintf(NULL,
  17938. NULL,
  17939. block,
  17940. sizeof(block),
  17941. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  17942. "char:%u/%u, "
  17943. "ptr:%u, size:%u, time:%u\"",
  17944. eol,
  17945. (unsigned)sizeof(short),
  17946. (unsigned)sizeof(int),
  17947. (unsigned)sizeof(long),
  17948. (unsigned)sizeof(long long),
  17949. (unsigned)sizeof(float),
  17950. (unsigned)sizeof(double),
  17951. (unsigned)sizeof(long double),
  17952. (unsigned)sizeof(char),
  17953. (unsigned)sizeof(wchar_t),
  17954. (unsigned)sizeof(void *),
  17955. (unsigned)sizeof(size_t),
  17956. (unsigned)sizeof(time_t));
  17957. system_info_length += mg_str_append(&buffer, end, block);
  17958. }
  17959. /* Terminate string */
  17960. if (append_eoobj) {
  17961. strcat(append_eoobj, eoobj);
  17962. }
  17963. system_info_length += sizeof(eoobj) - 1;
  17964. return (int)system_info_length;
  17965. }
  17966. /* Get context information. It can be printed or stored by the caller.
  17967. * Return the size of available information. */
  17968. int
  17969. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17970. {
  17971. #if defined(USE_SERVER_STATS)
  17972. char *end, *append_eoobj = NULL, block[256];
  17973. size_t context_info_length = 0;
  17974. #if defined(_WIN32)
  17975. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17976. #else
  17977. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17978. #endif
  17979. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  17980. if ((buffer == NULL) || (buflen < 1)) {
  17981. buflen = 0;
  17982. end = buffer;
  17983. } else {
  17984. *buffer = 0;
  17985. end = buffer + buflen;
  17986. }
  17987. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17988. /* has enough space to append eoobj */
  17989. append_eoobj = buffer;
  17990. end -= sizeof(eoobj) - 1;
  17991. }
  17992. context_info_length += mg_str_append(&buffer, end, "{");
  17993. if (ms) { /* <-- should be always true */
  17994. /* Memory information */
  17995. int blockCount = (int)ms->blockCount;
  17996. int64_t totalMemUsed = ms->totalMemUsed;
  17997. int64_t maxMemUsed = ms->maxMemUsed;
  17998. if (totalMemUsed > maxMemUsed) {
  17999. maxMemUsed = totalMemUsed;
  18000. }
  18001. mg_snprintf(NULL,
  18002. NULL,
  18003. block,
  18004. sizeof(block),
  18005. "%s\"memory\" : {%s"
  18006. "\"blocks\" : %i,%s"
  18007. "\"used\" : %" INT64_FMT ",%s"
  18008. "\"maxUsed\" : %" INT64_FMT "%s"
  18009. "}",
  18010. eol,
  18011. eol,
  18012. blockCount,
  18013. eol,
  18014. totalMemUsed,
  18015. eol,
  18016. maxMemUsed,
  18017. eol);
  18018. context_info_length += mg_str_append(&buffer, end, block);
  18019. }
  18020. if (ctx) {
  18021. /* Declare all variables at begin of the block, to comply
  18022. * with old C standards. */
  18023. char start_time_str[64] = {0};
  18024. char now_str[64] = {0};
  18025. time_t start_time = ctx->start_time;
  18026. time_t now = time(NULL);
  18027. int64_t total_data_read, total_data_written;
  18028. int active_connections = (int)ctx->active_connections;
  18029. int max_active_connections = (int)ctx->max_active_connections;
  18030. int total_connections = (int)ctx->total_connections;
  18031. if (active_connections > max_active_connections) {
  18032. max_active_connections = active_connections;
  18033. }
  18034. if (active_connections > total_connections) {
  18035. total_connections = active_connections;
  18036. }
  18037. /* Connections information */
  18038. mg_snprintf(NULL,
  18039. NULL,
  18040. block,
  18041. sizeof(block),
  18042. ",%s\"connections\" : {%s"
  18043. "\"active\" : %i,%s"
  18044. "\"maxActive\" : %i,%s"
  18045. "\"total\" : %i%s"
  18046. "}",
  18047. eol,
  18048. eol,
  18049. active_connections,
  18050. eol,
  18051. max_active_connections,
  18052. eol,
  18053. total_connections,
  18054. eol);
  18055. context_info_length += mg_str_append(&buffer, end, block);
  18056. /* Queue information */
  18057. #if !defined(ALTERNATIVE_QUEUE)
  18058. mg_snprintf(NULL,
  18059. NULL,
  18060. block,
  18061. sizeof(block),
  18062. ",%s\"queue\" : {%s"
  18063. "\"length\" : %i,%s"
  18064. "\"filled\" : %i,%s"
  18065. "\"maxFilled\" : %i,%s"
  18066. "\"full\" : %s%s"
  18067. "}",
  18068. eol,
  18069. eol,
  18070. ctx->sq_size,
  18071. eol,
  18072. ctx->sq_head - ctx->sq_tail,
  18073. eol,
  18074. ctx->sq_max_fill,
  18075. eol,
  18076. (ctx->sq_blocked ? "true" : "false"),
  18077. eol);
  18078. context_info_length += mg_str_append(&buffer, end, block);
  18079. #endif
  18080. /* Requests information */
  18081. mg_snprintf(NULL,
  18082. NULL,
  18083. block,
  18084. sizeof(block),
  18085. ",%s\"requests\" : {%s"
  18086. "\"total\" : %lu%s"
  18087. "}",
  18088. eol,
  18089. eol,
  18090. (unsigned long)ctx->total_requests,
  18091. eol);
  18092. context_info_length += mg_str_append(&buffer, end, block);
  18093. /* Data information */
  18094. total_data_read =
  18095. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18096. total_data_written =
  18097. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18098. mg_snprintf(NULL,
  18099. NULL,
  18100. block,
  18101. sizeof(block),
  18102. ",%s\"data\" : {%s"
  18103. "\"read\" : %" INT64_FMT ",%s"
  18104. "\"written\" : %" INT64_FMT "%s"
  18105. "}",
  18106. eol,
  18107. eol,
  18108. total_data_read,
  18109. eol,
  18110. total_data_written,
  18111. eol);
  18112. context_info_length += mg_str_append(&buffer, end, block);
  18113. /* Execution time information */
  18114. gmt_time_string(start_time_str,
  18115. sizeof(start_time_str) - 1,
  18116. &start_time);
  18117. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18118. mg_snprintf(NULL,
  18119. NULL,
  18120. block,
  18121. sizeof(block),
  18122. ",%s\"time\" : {%s"
  18123. "\"uptime\" : %.0f,%s"
  18124. "\"start\" : \"%s\",%s"
  18125. "\"now\" : \"%s\"%s"
  18126. "}",
  18127. eol,
  18128. eol,
  18129. difftime(now, start_time),
  18130. eol,
  18131. start_time_str,
  18132. eol,
  18133. now_str,
  18134. eol);
  18135. context_info_length += mg_str_append(&buffer, end, block);
  18136. }
  18137. /* Terminate string */
  18138. if (append_eoobj) {
  18139. strcat(append_eoobj, eoobj);
  18140. }
  18141. context_info_length += sizeof(eoobj) - 1;
  18142. return (int)context_info_length;
  18143. #else
  18144. (void)ctx;
  18145. if ((buffer != NULL) && (buflen > 0)) {
  18146. *buffer = 0;
  18147. }
  18148. return 0;
  18149. #endif
  18150. }
  18151. void
  18152. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18153. {
  18154. /* https://github.com/civetweb/civetweb/issues/727 */
  18155. if (conn != NULL) {
  18156. conn->must_close = 1;
  18157. }
  18158. }
  18159. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18160. /* Get connection information. It can be printed or stored by the caller.
  18161. * Return the size of available information. */
  18162. int
  18163. mg_get_connection_info(const struct mg_context *ctx,
  18164. int idx,
  18165. char *buffer,
  18166. int buflen)
  18167. {
  18168. const struct mg_connection *conn;
  18169. const struct mg_request_info *ri;
  18170. char *end, *append_eoobj = NULL, block[256];
  18171. size_t connection_info_length = 0;
  18172. int state = 0;
  18173. const char *state_str = "unknown";
  18174. #if defined(_WIN32)
  18175. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18176. #else
  18177. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18178. #endif
  18179. if ((buffer == NULL) || (buflen < 1)) {
  18180. buflen = 0;
  18181. end = buffer;
  18182. } else {
  18183. *buffer = 0;
  18184. end = buffer + buflen;
  18185. }
  18186. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18187. /* has enough space to append eoobj */
  18188. append_eoobj = buffer;
  18189. end -= sizeof(eoobj) - 1;
  18190. }
  18191. if ((ctx == NULL) || (idx < 0)) {
  18192. /* Parameter error */
  18193. return 0;
  18194. }
  18195. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18196. /* Out of range */
  18197. return 0;
  18198. }
  18199. /* Take connection [idx]. This connection is not locked in
  18200. * any way, so some other thread might use it. */
  18201. conn = (ctx->worker_connections) + idx;
  18202. /* Initialize output string */
  18203. connection_info_length += mg_str_append(&buffer, end, "{");
  18204. /* Init variables */
  18205. ri = &(conn->request_info);
  18206. #if defined(USE_SERVER_STATS)
  18207. state = conn->conn_state;
  18208. /* State as string */
  18209. switch (state) {
  18210. case 0:
  18211. state_str = "undefined";
  18212. break;
  18213. case 1:
  18214. state_str = "not used";
  18215. break;
  18216. case 2:
  18217. state_str = "init";
  18218. break;
  18219. case 3:
  18220. state_str = "ready";
  18221. break;
  18222. case 4:
  18223. state_str = "processing";
  18224. break;
  18225. case 5:
  18226. state_str = "processed";
  18227. break;
  18228. case 6:
  18229. state_str = "to close";
  18230. break;
  18231. case 7:
  18232. state_str = "closing";
  18233. break;
  18234. case 8:
  18235. state_str = "closed";
  18236. break;
  18237. case 9:
  18238. state_str = "done";
  18239. break;
  18240. }
  18241. #endif
  18242. /* Connection info */
  18243. if ((state >= 3) && (state < 9)) {
  18244. mg_snprintf(NULL,
  18245. NULL,
  18246. block,
  18247. sizeof(block),
  18248. "%s\"connection\" : {%s"
  18249. "\"remote\" : {%s"
  18250. "\"protocol\" : \"%s\",%s"
  18251. "\"addr\" : \"%s\",%s"
  18252. "\"port\" : %u%s"
  18253. "},%s"
  18254. "\"handled_requests\" : %u%s"
  18255. "}",
  18256. eol,
  18257. eol,
  18258. eol,
  18259. get_proto_name(conn),
  18260. eol,
  18261. ri->remote_addr,
  18262. eol,
  18263. ri->remote_port,
  18264. eol,
  18265. eol,
  18266. conn->handled_requests,
  18267. eol);
  18268. connection_info_length += mg_str_append(&buffer, end, block);
  18269. }
  18270. /* Request info */
  18271. if ((state >= 4) && (state < 6)) {
  18272. mg_snprintf(NULL,
  18273. NULL,
  18274. block,
  18275. sizeof(block),
  18276. "%s%s\"request_info\" : {%s"
  18277. "\"method\" : \"%s\",%s"
  18278. "\"uri\" : \"%s\",%s"
  18279. "\"query\" : %s%s%s%s"
  18280. "}",
  18281. (connection_info_length > 1 ? "," : ""),
  18282. eol,
  18283. eol,
  18284. ri->request_method,
  18285. eol,
  18286. ri->request_uri,
  18287. eol,
  18288. ri->query_string ? "\"" : "",
  18289. ri->query_string ? ri->query_string : "null",
  18290. ri->query_string ? "\"" : "",
  18291. eol);
  18292. connection_info_length += mg_str_append(&buffer, end, block);
  18293. }
  18294. /* Execution time information */
  18295. if ((state >= 2) && (state < 9)) {
  18296. char start_time_str[64] = {0};
  18297. char close_time_str[64] = {0};
  18298. time_t start_time = conn->conn_birth_time;
  18299. time_t close_time = 0;
  18300. double time_diff;
  18301. gmt_time_string(start_time_str,
  18302. sizeof(start_time_str) - 1,
  18303. &start_time);
  18304. #if defined(USE_SERVER_STATS)
  18305. close_time = conn->conn_close_time;
  18306. #endif
  18307. if (close_time != 0) {
  18308. time_diff = difftime(close_time, start_time);
  18309. gmt_time_string(close_time_str,
  18310. sizeof(close_time_str) - 1,
  18311. &close_time);
  18312. } else {
  18313. time_t now = time(NULL);
  18314. time_diff = difftime(now, start_time);
  18315. close_time_str[0] = 0; /* or use "now" ? */
  18316. }
  18317. mg_snprintf(NULL,
  18318. NULL,
  18319. block,
  18320. sizeof(block),
  18321. "%s%s\"time\" : {%s"
  18322. "\"uptime\" : %.0f,%s"
  18323. "\"start\" : \"%s\",%s"
  18324. "\"closed\" : \"%s\"%s"
  18325. "}",
  18326. (connection_info_length > 1 ? "," : ""),
  18327. eol,
  18328. eol,
  18329. time_diff,
  18330. eol,
  18331. start_time_str,
  18332. eol,
  18333. close_time_str,
  18334. eol);
  18335. connection_info_length += mg_str_append(&buffer, end, block);
  18336. }
  18337. /* Remote user name */
  18338. if ((ri->remote_user) && (state < 9)) {
  18339. mg_snprintf(NULL,
  18340. NULL,
  18341. block,
  18342. sizeof(block),
  18343. "%s%s\"user\" : {%s"
  18344. "\"name\" : \"%s\",%s"
  18345. "}",
  18346. (connection_info_length > 1 ? "," : ""),
  18347. eol,
  18348. eol,
  18349. ri->remote_user,
  18350. eol);
  18351. connection_info_length += mg_str_append(&buffer, end, block);
  18352. }
  18353. /* Data block */
  18354. if (state >= 3) {
  18355. mg_snprintf(NULL,
  18356. NULL,
  18357. block,
  18358. sizeof(block),
  18359. "%s%s\"data\" : {%s"
  18360. "\"read\" : %" INT64_FMT ",%s"
  18361. "\"written\" : %" INT64_FMT "%s"
  18362. "}",
  18363. (connection_info_length > 1 ? "," : ""),
  18364. eol,
  18365. eol,
  18366. conn->consumed_content,
  18367. eol,
  18368. conn->num_bytes_sent,
  18369. eol);
  18370. connection_info_length += mg_str_append(&buffer, end, block);
  18371. }
  18372. /* State */
  18373. mg_snprintf(NULL,
  18374. NULL,
  18375. block,
  18376. sizeof(block),
  18377. "%s%s\"state\" : \"%s\"",
  18378. (connection_info_length > 1 ? "," : ""),
  18379. eol,
  18380. state_str);
  18381. connection_info_length += mg_str_append(&buffer, end, block);
  18382. /* Terminate string */
  18383. if (append_eoobj) {
  18384. strcat(append_eoobj, eoobj);
  18385. }
  18386. connection_info_length += sizeof(eoobj) - 1;
  18387. return (int)connection_info_length;
  18388. }
  18389. #endif
  18390. /* Initialize this library. This function does not need to be thread safe.
  18391. */
  18392. unsigned
  18393. mg_init_library(unsigned features)
  18394. {
  18395. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18396. unsigned features_inited = features_to_init;
  18397. if (mg_init_library_called <= 0) {
  18398. /* Not initialized yet */
  18399. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18400. return 0;
  18401. }
  18402. }
  18403. mg_global_lock();
  18404. if (mg_init_library_called <= 0) {
  18405. #if defined(_WIN32)
  18406. int file_mutex_init = 1;
  18407. int wsa = 1;
  18408. #else
  18409. int mutexattr_init = 1;
  18410. #endif
  18411. int failed = 1;
  18412. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18413. if (key_create == 0) {
  18414. #if defined(_WIN32)
  18415. file_mutex_init =
  18416. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18417. if (file_mutex_init == 0) {
  18418. /* Start WinSock */
  18419. WSADATA data;
  18420. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18421. }
  18422. #else
  18423. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18424. if (mutexattr_init == 0) {
  18425. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18426. PTHREAD_MUTEX_RECURSIVE);
  18427. }
  18428. #endif
  18429. }
  18430. if (failed) {
  18431. #if defined(_WIN32)
  18432. if (wsa == 0) {
  18433. (void)WSACleanup();
  18434. }
  18435. if (file_mutex_init == 0) {
  18436. (void)pthread_mutex_destroy(&global_log_file_lock);
  18437. }
  18438. #else
  18439. if (mutexattr_init == 0) {
  18440. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18441. }
  18442. #endif
  18443. if (key_create == 0) {
  18444. (void)pthread_key_delete(sTlsKey);
  18445. }
  18446. mg_global_unlock();
  18447. (void)pthread_mutex_destroy(&global_lock_mutex);
  18448. return 0;
  18449. }
  18450. #if defined(USE_LUA)
  18451. lua_init_optional_libraries();
  18452. #endif
  18453. }
  18454. mg_global_unlock();
  18455. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) && !defined(NO_SSL)
  18456. if (features_to_init & MG_FEATURES_SSL) {
  18457. if (!mg_openssl_initialized) {
  18458. char ebuf[128];
  18459. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  18460. mg_openssl_initialized = 1;
  18461. } else {
  18462. (void)ebuf;
  18463. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18464. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18465. }
  18466. } else {
  18467. /* ssl already initialized */
  18468. }
  18469. }
  18470. #endif
  18471. mg_global_lock();
  18472. if (mg_init_library_called <= 0) {
  18473. mg_init_library_called = 1;
  18474. } else {
  18475. mg_init_library_called++;
  18476. }
  18477. mg_global_unlock();
  18478. return features_inited;
  18479. }
  18480. /* Un-initialize this library. */
  18481. unsigned
  18482. mg_exit_library(void)
  18483. {
  18484. if (mg_init_library_called <= 0) {
  18485. return 0;
  18486. }
  18487. mg_global_lock();
  18488. mg_init_library_called--;
  18489. if (mg_init_library_called == 0) {
  18490. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  18491. if (mg_openssl_initialized) {
  18492. uninitialize_openssl();
  18493. mg_openssl_initialized = 0;
  18494. }
  18495. #endif
  18496. #if defined(_WIN32)
  18497. (void)WSACleanup();
  18498. (void)pthread_mutex_destroy(&global_log_file_lock);
  18499. #else
  18500. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18501. #endif
  18502. (void)pthread_key_delete(sTlsKey);
  18503. #if defined(USE_LUA)
  18504. lua_exit_optional_libraries();
  18505. #endif
  18506. mg_global_unlock();
  18507. (void)pthread_mutex_destroy(&global_lock_mutex);
  18508. return 1;
  18509. }
  18510. mg_global_unlock();
  18511. return 1;
  18512. }
  18513. /* End of civetweb.c */