civetweb.c 570 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484
  1. /* Copyright (c) 2013-2021 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0502
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE (1024 * 16)
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #if !defined(DEBUG_TRACE_STREAM)
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #include <stdlib.h>
  220. #define DEBUG_ASSERT(cond) \
  221. do { \
  222. if (!(cond)) { \
  223. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  224. exit(2); /* Exit with error */ \
  225. } \
  226. } while (0)
  227. #else
  228. #define DEBUG_ASSERT(cond)
  229. #endif /* DEBUG */
  230. #endif
  231. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  232. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  233. __attribute__((no_instrument_function));
  234. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void
  237. __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. {
  239. if ((void *)this_fn != (void *)printf) {
  240. printf("E %p %p\n", this_fn, call_site);
  241. }
  242. }
  243. void
  244. __cyg_profile_func_exit(void *this_fn, void *call_site)
  245. {
  246. if ((void *)this_fn != (void *)printf) {
  247. printf("X %p %p\n", this_fn, call_site);
  248. }
  249. }
  250. #endif
  251. #if !defined(IGNORE_UNUSED_RESULT)
  252. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  253. #endif
  254. #if defined(__GNUC__) || defined(__MINGW32__)
  255. /* GCC unused function attribute seems fundamentally broken.
  256. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  257. * OR UNUSED" for individual functions failed.
  258. * Either the compiler creates an "unused-function" warning if a
  259. * function is not marked with __attribute__((unused)).
  260. * On the other hand, if the function is marked with this attribute,
  261. * but is used, the compiler raises a completely idiotic
  262. * "used-but-marked-unused" warning - and
  263. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  264. * raises error: unknown option after "#pragma GCC diagnostic".
  265. * Disable this warning completely, until the GCC guys sober up
  266. * again.
  267. */
  268. #pragma GCC diagnostic ignored "-Wunused-function"
  269. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  270. #else
  271. #define FUNCTION_MAY_BE_UNUSED
  272. #endif
  273. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  274. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  275. #include <errno.h>
  276. #include <fcntl.h>
  277. #include <signal.h>
  278. #include <stdlib.h>
  279. #include <sys/stat.h>
  280. #include <sys/types.h>
  281. #endif /* !_WIN32_WCE */
  282. #if defined(__clang__)
  283. /* When using -Weverything, clang does not accept it's own headers
  284. * in a release build configuration. Disable what is too much in
  285. * -Weverything. */
  286. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  287. #endif
  288. #if defined(__GNUC__) || defined(__MINGW32__)
  289. /* Who on earth came to the conclusion, using __DATE__ should rise
  290. * an "expansion of date or time macro is not reproducible"
  291. * warning. That's exactly what was intended by using this macro.
  292. * Just disable this nonsense warning. */
  293. /* And disabling them does not work either:
  294. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  295. * #pragma clang diagnostic ignored "-Wdate-time"
  296. * So we just have to disable ALL warnings for some lines
  297. * of code.
  298. * This seems to be a known GCC bug, not resolved since 2012:
  299. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  300. */
  301. #endif
  302. #if defined(__MACH__) /* Apple OSX section */
  303. #if defined(__clang__)
  304. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  305. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  306. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  307. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  308. #endif
  309. #endif
  310. #ifndef CLOCK_MONOTONIC
  311. #define CLOCK_MONOTONIC (1)
  312. #endif
  313. #ifndef CLOCK_REALTIME
  314. #define CLOCK_REALTIME (2)
  315. #endif
  316. #include <mach/clock.h>
  317. #include <mach/mach.h>
  318. #include <mach/mach_time.h>
  319. #include <sys/errno.h>
  320. #include <sys/time.h>
  321. /* clock_gettime is not implemented on OSX prior to 10.12 */
  322. static int
  323. _civet_clock_gettime(int clk_id, struct timespec *t)
  324. {
  325. memset(t, 0, sizeof(*t));
  326. if (clk_id == CLOCK_REALTIME) {
  327. struct timeval now;
  328. int rv = gettimeofday(&now, NULL);
  329. if (rv) {
  330. return rv;
  331. }
  332. t->tv_sec = now.tv_sec;
  333. t->tv_nsec = now.tv_usec * 1000;
  334. return 0;
  335. } else if (clk_id == CLOCK_MONOTONIC) {
  336. static uint64_t clock_start_time = 0;
  337. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  338. uint64_t now = mach_absolute_time();
  339. if (clock_start_time == 0) {
  340. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  341. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  342. /* appease "unused variable" warning for release builds */
  343. (void)mach_status;
  344. clock_start_time = now;
  345. }
  346. now = (uint64_t)((double)(now - clock_start_time)
  347. * (double)timebase_ifo.numer
  348. / (double)timebase_ifo.denom);
  349. t->tv_sec = now / 1000000000;
  350. t->tv_nsec = now % 1000000000;
  351. return 0;
  352. }
  353. return -1; /* EINVAL - Clock ID is unknown */
  354. }
  355. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  356. #if defined(__CLOCK_AVAILABILITY)
  357. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  358. * declared but it may be NULL at runtime. So we need to check before using
  359. * it. */
  360. static int
  361. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  362. {
  363. if (clock_gettime) {
  364. return clock_gettime(clk_id, t);
  365. }
  366. return _civet_clock_gettime(clk_id, t);
  367. }
  368. #define clock_gettime _civet_safe_clock_gettime
  369. #else
  370. #define clock_gettime _civet_clock_gettime
  371. #endif
  372. #endif
  373. #if !defined(_WIN32)
  374. /* Unix might return different error codes indicating to try again.
  375. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  376. * decades ago, but better check both and let the compile optimize it. */
  377. #define ERROR_TRY_AGAIN(err) \
  378. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  379. #endif
  380. #if defined(USE_ZLIB)
  381. #include "zconf.h"
  382. #include "zlib.h"
  383. #endif
  384. /********************************************************************/
  385. /* CivetWeb configuration defines */
  386. /********************************************************************/
  387. /* Maximum number of threads that can be configured.
  388. * The number of threads actually created depends on the "num_threads"
  389. * configuration parameter, but this is the upper limit. */
  390. #if !defined(MAX_WORKER_THREADS)
  391. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  392. #endif
  393. /* Timeout interval for select/poll calls.
  394. * The timeouts depend on "*_timeout_ms" configuration values, but long
  395. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  396. * This reduces the time required to stop the server. */
  397. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  398. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  399. #endif
  400. /* Do not try to compress files smaller than this limit. */
  401. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  402. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  403. #endif
  404. #if !defined(PASSWORDS_FILE_NAME)
  405. #define PASSWORDS_FILE_NAME ".htpasswd"
  406. #endif
  407. #if !defined(MODIFY_PASSWORD_TEMP_EXT)
  408. #define MODIFY_PASSWORD_TEMP_EXT ".htpasswd_tmp"
  409. #endif
  410. /* Initial buffer size for all CGI environment variables. In case there is
  411. * not enough space, another block is allocated. */
  412. #if !defined(CGI_ENVIRONMENT_SIZE)
  413. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  414. #endif
  415. /* Maximum number of environment variables. */
  416. #if !defined(MAX_CGI_ENVIR_VARS)
  417. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  418. #endif
  419. /* General purpose buffer size. */
  420. #if !defined(MG_BUF_LEN) /* in bytes */
  421. #define MG_BUF_LEN (1024 * 8)
  422. #endif
  423. /********************************************************************/
  424. /* Helper makros */
  425. #if !defined(ARRAY_SIZE)
  426. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  427. #endif
  428. #include <stdint.h>
  429. /* Standard defines */
  430. #if !defined(INT64_MAX)
  431. #define INT64_MAX (9223372036854775807)
  432. #endif
  433. #define SHUTDOWN_RD (0)
  434. #define SHUTDOWN_WR (1)
  435. #define SHUTDOWN_BOTH (2)
  436. mg_static_assert(MAX_WORKER_THREADS >= 1,
  437. "worker threads must be a positive number");
  438. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  439. "size_t data type size check");
  440. #if defined(_WIN32) /* WINDOWS include block */
  441. #include <malloc.h> /* *alloc( */
  442. #include <stdlib.h> /* *alloc( */
  443. #include <time.h> /* struct timespec */
  444. #include <windows.h>
  445. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  446. #include <ws2tcpip.h>
  447. typedef const char *SOCK_OPT_TYPE;
  448. /* For a detailed description of these *_PATH_MAX defines, see
  449. * https://github.com/civetweb/civetweb/issues/937. */
  450. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  451. * null termination, rounded up to the next 4 bytes boundary */
  452. #define UTF8_PATH_MAX (3 * 260)
  453. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  454. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  455. #define UTF16_PATH_MAX (260)
  456. #if !defined(_IN_PORT_T)
  457. #if !defined(in_port_t)
  458. #define in_port_t u_short
  459. #endif
  460. #endif
  461. #if defined(_WIN32_WCE)
  462. #error "WinCE support has ended"
  463. #endif
  464. #include <direct.h>
  465. #include <io.h>
  466. #include <process.h>
  467. #define MAKEUQUAD(lo, hi) \
  468. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  469. #define RATE_DIFF (10000000) /* 100 nsecs */
  470. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  471. #define SYS2UNIX_TIME(lo, hi) \
  472. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  473. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  474. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  475. * Also use _strtoui64 on modern M$ compilers */
  476. #if defined(_MSC_VER)
  477. #if (_MSC_VER < 1300)
  478. #define STRX(x) #x
  479. #define STR(x) STRX(x)
  480. #define __func__ __FILE__ ":" STR(__LINE__)
  481. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  482. #define strtoll(x, y, z) (_atoi64(x))
  483. #else
  484. #define __func__ __FUNCTION__
  485. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  486. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  487. #endif
  488. #endif /* _MSC_VER */
  489. #define ERRNO ((int)(GetLastError()))
  490. #define NO_SOCKLEN_T
  491. #if defined(_WIN64) || defined(__MINGW64__)
  492. #if !defined(SSL_LIB)
  493. #if defined(OPENSSL_API_3_0)
  494. #define SSL_LIB "libssl-3-x64.dll"
  495. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  496. #endif
  497. #if defined(OPENSSL_API_1_1)
  498. #define SSL_LIB "libssl-1_1-x64.dll"
  499. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  500. #endif /* OPENSSL_API_1_1 */
  501. #if defined(OPENSSL_API_1_0)
  502. #define SSL_LIB "ssleay64.dll"
  503. #define CRYPTO_LIB "libeay64.dll"
  504. #endif /* OPENSSL_API_1_0 */
  505. #endif
  506. #else /* defined(_WIN64) || defined(__MINGW64__) */
  507. #if !defined(SSL_LIB)
  508. #if defined(OPENSSL_API_3_0)
  509. #define SSL_LIB "libssl-3.dll"
  510. #define CRYPTO_LIB "libcrypto-3.dll"
  511. #endif
  512. #if defined(OPENSSL_API_1_1)
  513. #define SSL_LIB "libssl-1_1.dll"
  514. #define CRYPTO_LIB "libcrypto-1_1.dll"
  515. #endif /* OPENSSL_API_1_1 */
  516. #if defined(OPENSSL_API_1_0)
  517. #define SSL_LIB "ssleay32.dll"
  518. #define CRYPTO_LIB "libeay32.dll"
  519. #endif /* OPENSSL_API_1_0 */
  520. #endif /* SSL_LIB */
  521. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  522. #define O_NONBLOCK (0)
  523. #if !defined(W_OK)
  524. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  525. #endif
  526. #define _POSIX_
  527. #define INT64_FMT "I64d"
  528. #define UINT64_FMT "I64u"
  529. #define WINCDECL __cdecl
  530. #define vsnprintf_impl _vsnprintf
  531. #define access _access
  532. #define mg_sleep(x) (Sleep(x))
  533. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  534. #if !defined(popen)
  535. #define popen(x, y) (_popen(x, y))
  536. #endif
  537. #if !defined(pclose)
  538. #define pclose(x) (_pclose(x))
  539. #endif
  540. #define close(x) (_close(x))
  541. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  542. #define RTLD_LAZY (0)
  543. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  544. #define fdopen(x, y) (_fdopen((x), (y)))
  545. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  546. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  547. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  548. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  549. #define sleep(x) (Sleep((x)*1000))
  550. #define rmdir(x) (_rmdir(x))
  551. #if defined(_WIN64) || !defined(__MINGW32__)
  552. /* Only MinGW 32 bit is missing this function */
  553. #define timegm(x) (_mkgmtime(x))
  554. #else
  555. time_t timegm(struct tm *tm);
  556. #define NEED_TIMEGM
  557. #endif
  558. #if !defined(fileno)
  559. #define fileno(x) (_fileno(x))
  560. #endif /* !fileno MINGW #defines fileno */
  561. typedef struct {
  562. CRITICAL_SECTION sec; /* Immovable */
  563. } pthread_mutex_t;
  564. typedef DWORD pthread_key_t;
  565. typedef HANDLE pthread_t;
  566. typedef struct {
  567. pthread_mutex_t threadIdSec;
  568. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  569. } pthread_cond_t;
  570. #if !defined(__clockid_t_defined)
  571. typedef DWORD clockid_t;
  572. #endif
  573. #if !defined(CLOCK_MONOTONIC)
  574. #define CLOCK_MONOTONIC (1)
  575. #endif
  576. #if !defined(CLOCK_REALTIME)
  577. #define CLOCK_REALTIME (2)
  578. #endif
  579. #if !defined(CLOCK_THREAD)
  580. #define CLOCK_THREAD (3)
  581. #endif
  582. #if !defined(CLOCK_PROCESS)
  583. #define CLOCK_PROCESS (4)
  584. #endif
  585. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  586. #define _TIMESPEC_DEFINED
  587. #endif
  588. #if !defined(_TIMESPEC_DEFINED)
  589. struct timespec {
  590. time_t tv_sec; /* seconds */
  591. long tv_nsec; /* nanoseconds */
  592. };
  593. #endif
  594. #if !defined(WIN_PTHREADS_TIME_H)
  595. #define MUST_IMPLEMENT_CLOCK_GETTIME
  596. #endif
  597. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  598. #define clock_gettime mg_clock_gettime
  599. static int
  600. clock_gettime(clockid_t clk_id, struct timespec *tp)
  601. {
  602. FILETIME ft;
  603. ULARGE_INTEGER li, li2;
  604. BOOL ok = FALSE;
  605. double d;
  606. static double perfcnt_per_sec = 0.0;
  607. static BOOL initialized = FALSE;
  608. if (!initialized) {
  609. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  610. perfcnt_per_sec = 1.0 / li.QuadPart;
  611. initialized = TRUE;
  612. }
  613. if (tp) {
  614. memset(tp, 0, sizeof(*tp));
  615. if (clk_id == CLOCK_REALTIME) {
  616. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  617. GetSystemTimeAsFileTime(&ft);
  618. li.LowPart = ft.dwLowDateTime;
  619. li.HighPart = ft.dwHighDateTime;
  620. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  621. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  622. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  623. ok = TRUE;
  624. /* END: CLOCK_REALTIME */
  625. } else if (clk_id == CLOCK_MONOTONIC) {
  626. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  627. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  628. d = li.QuadPart * perfcnt_per_sec;
  629. tp->tv_sec = (time_t)d;
  630. d -= (double)tp->tv_sec;
  631. tp->tv_nsec = (long)(d * 1.0E9);
  632. ok = TRUE;
  633. /* END: CLOCK_MONOTONIC */
  634. } else if (clk_id == CLOCK_THREAD) {
  635. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  636. FILETIME t_create, t_exit, t_kernel, t_user;
  637. if (GetThreadTimes(GetCurrentThread(),
  638. &t_create,
  639. &t_exit,
  640. &t_kernel,
  641. &t_user)) {
  642. li.LowPart = t_user.dwLowDateTime;
  643. li.HighPart = t_user.dwHighDateTime;
  644. li2.LowPart = t_kernel.dwLowDateTime;
  645. li2.HighPart = t_kernel.dwHighDateTime;
  646. li.QuadPart += li2.QuadPart;
  647. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  648. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  649. ok = TRUE;
  650. }
  651. /* END: CLOCK_THREAD */
  652. } else if (clk_id == CLOCK_PROCESS) {
  653. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  654. FILETIME t_create, t_exit, t_kernel, t_user;
  655. if (GetProcessTimes(GetCurrentProcess(),
  656. &t_create,
  657. &t_exit,
  658. &t_kernel,
  659. &t_user)) {
  660. li.LowPart = t_user.dwLowDateTime;
  661. li.HighPart = t_user.dwHighDateTime;
  662. li2.LowPart = t_kernel.dwLowDateTime;
  663. li2.HighPart = t_kernel.dwHighDateTime;
  664. li.QuadPart += li2.QuadPart;
  665. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  666. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  667. ok = TRUE;
  668. }
  669. /* END: CLOCK_PROCESS */
  670. } else {
  671. /* BEGIN: unknown clock */
  672. /* ok = FALSE; already set by init */
  673. /* END: unknown clock */
  674. }
  675. }
  676. return ok ? 0 : -1;
  677. }
  678. #endif
  679. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  680. static int pthread_mutex_lock(pthread_mutex_t *);
  681. static int pthread_mutex_unlock(pthread_mutex_t *);
  682. static void path_to_unicode(const struct mg_connection *conn,
  683. const char *path,
  684. wchar_t *wbuf,
  685. size_t wbuf_len);
  686. /* All file operations need to be rewritten to solve #246. */
  687. struct mg_file;
  688. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  689. /* POSIX dirent interface */
  690. struct dirent {
  691. char d_name[UTF8_PATH_MAX];
  692. };
  693. typedef struct DIR {
  694. HANDLE handle;
  695. WIN32_FIND_DATAW info;
  696. struct dirent result;
  697. } DIR;
  698. #if defined(HAVE_POLL)
  699. #define mg_pollfd pollfd
  700. #else
  701. struct mg_pollfd {
  702. SOCKET fd;
  703. short events;
  704. short revents;
  705. };
  706. #endif
  707. /* Mark required libraries */
  708. #if defined(_MSC_VER)
  709. #pragma comment(lib, "Ws2_32.lib")
  710. #endif
  711. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  712. #include <inttypes.h>
  713. /* Linux & co. internally use UTF8 */
  714. #define UTF8_PATH_MAX (PATH_MAX)
  715. typedef const void *SOCK_OPT_TYPE;
  716. #if defined(ANDROID)
  717. typedef unsigned short int in_port_t;
  718. #endif
  719. #if !defined(__ZEPHYR__)
  720. #include <arpa/inet.h>
  721. #include <ctype.h>
  722. #include <dirent.h>
  723. #include <grp.h>
  724. #include <limits.h>
  725. #include <netdb.h>
  726. #include <netinet/in.h>
  727. #include <netinet/tcp.h>
  728. #include <pthread.h>
  729. #include <pwd.h>
  730. #include <stdarg.h>
  731. #include <stddef.h>
  732. #include <stdio.h>
  733. #include <stdlib.h>
  734. #include <string.h>
  735. #include <sys/poll.h>
  736. #include <sys/socket.h>
  737. #include <sys/time.h>
  738. #include <sys/utsname.h>
  739. #include <sys/wait.h>
  740. #include <time.h>
  741. #include <unistd.h>
  742. #if defined(USE_X_DOM_SOCKET)
  743. #include <sys/un.h>
  744. #endif
  745. #endif
  746. #define vsnprintf_impl vsnprintf
  747. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  748. #include <dlfcn.h>
  749. #endif
  750. #if defined(__MACH__)
  751. #define SSL_LIB "libssl.dylib"
  752. #define CRYPTO_LIB "libcrypto.dylib"
  753. #else
  754. #if !defined(SSL_LIB)
  755. #define SSL_LIB "libssl.so"
  756. #endif
  757. #if !defined(CRYPTO_LIB)
  758. #define CRYPTO_LIB "libcrypto.so"
  759. #endif
  760. #endif
  761. #if !defined(O_BINARY)
  762. #define O_BINARY (0)
  763. #endif /* O_BINARY */
  764. #define closesocket(a) (close(a))
  765. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  766. #define mg_remove(conn, x) (remove(x))
  767. #define mg_sleep(x) (usleep((x)*1000))
  768. #define mg_opendir(conn, x) (opendir(x))
  769. #define mg_closedir(x) (closedir(x))
  770. #define mg_readdir(x) (readdir(x))
  771. #define ERRNO (errno)
  772. #define INVALID_SOCKET (-1)
  773. #define INT64_FMT PRId64
  774. #define UINT64_FMT PRIu64
  775. typedef int SOCKET;
  776. #define WINCDECL
  777. #if defined(__hpux)
  778. /* HPUX 11 does not have monotonic, fall back to realtime */
  779. #if !defined(CLOCK_MONOTONIC)
  780. #define CLOCK_MONOTONIC CLOCK_REALTIME
  781. #endif
  782. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  783. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  784. * the prototypes use int* rather than socklen_t* which matches the
  785. * actual library expectation. When called with the wrong size arg
  786. * accept() returns a zero client inet addr and check_acl() always
  787. * fails. Since socklen_t is widely used below, just force replace
  788. * their typedef with int. - DTL
  789. */
  790. #define socklen_t int
  791. #endif /* hpux */
  792. #define mg_pollfd pollfd
  793. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  794. /* In case our C library is missing "timegm", provide an implementation */
  795. #if defined(NEED_TIMEGM)
  796. static inline int
  797. is_leap(int y)
  798. {
  799. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  800. }
  801. static inline int
  802. count_leap(int y)
  803. {
  804. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  805. }
  806. time_t
  807. timegm(struct tm *tm)
  808. {
  809. static const unsigned short ydays[] = {
  810. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  811. int year = tm->tm_year + 1900;
  812. int mon = tm->tm_mon;
  813. int mday = tm->tm_mday - 1;
  814. int hour = tm->tm_hour;
  815. int min = tm->tm_min;
  816. int sec = tm->tm_sec;
  817. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  818. || (mday >= ydays[mon + 1] - ydays[mon]
  819. + (mon == 1 && is_leap(year) ? 1 : 0))
  820. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  821. return -1;
  822. time_t res = year - 1970;
  823. res *= 365;
  824. res += mday;
  825. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  826. res += count_leap(year);
  827. res *= 24;
  828. res += hour;
  829. res *= 60;
  830. res += min;
  831. res *= 60;
  832. res += sec;
  833. return res;
  834. }
  835. #endif /* NEED_TIMEGM */
  836. /* va_copy should always be a macro, C99 and C++11 - DTL */
  837. #if !defined(va_copy)
  838. #define va_copy(x, y) ((x) = (y))
  839. #endif
  840. #if defined(_WIN32)
  841. /* Create substitutes for POSIX functions in Win32. */
  842. #if defined(GCC_DIAGNOSTIC)
  843. /* Show no warning in case system functions are not used. */
  844. #pragma GCC diagnostic push
  845. #pragma GCC diagnostic ignored "-Wunused-function"
  846. #endif
  847. static pthread_mutex_t global_log_file_lock;
  848. FUNCTION_MAY_BE_UNUSED
  849. static DWORD
  850. pthread_self(void)
  851. {
  852. return GetCurrentThreadId();
  853. }
  854. FUNCTION_MAY_BE_UNUSED
  855. static int
  856. pthread_key_create(
  857. pthread_key_t *key,
  858. void (*_ignored)(void *) /* destructor not supported for Windows */
  859. )
  860. {
  861. (void)_ignored;
  862. if ((key != 0)) {
  863. *key = TlsAlloc();
  864. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  865. }
  866. return -2;
  867. }
  868. FUNCTION_MAY_BE_UNUSED
  869. static int
  870. pthread_key_delete(pthread_key_t key)
  871. {
  872. return TlsFree(key) ? 0 : 1;
  873. }
  874. FUNCTION_MAY_BE_UNUSED
  875. static int
  876. pthread_setspecific(pthread_key_t key, void *value)
  877. {
  878. return TlsSetValue(key, value) ? 0 : 1;
  879. }
  880. FUNCTION_MAY_BE_UNUSED
  881. static void *
  882. pthread_getspecific(pthread_key_t key)
  883. {
  884. return TlsGetValue(key);
  885. }
  886. #if defined(GCC_DIAGNOSTIC)
  887. /* Enable unused function warning again */
  888. #pragma GCC diagnostic pop
  889. #endif
  890. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  891. #else
  892. static pthread_mutexattr_t pthread_mutex_attr;
  893. #endif /* _WIN32 */
  894. #if defined(GCC_DIAGNOSTIC)
  895. /* Show no warning in case system functions are not used. */
  896. #pragma GCC diagnostic push
  897. #pragma GCC diagnostic ignored "-Wunused-function"
  898. #endif /* defined(GCC_DIAGNOSTIC) */
  899. #if defined(__clang__)
  900. /* Show no warning in case system functions are not used. */
  901. #pragma clang diagnostic push
  902. #pragma clang diagnostic ignored "-Wunused-function"
  903. #endif
  904. static pthread_mutex_t global_lock_mutex;
  905. FUNCTION_MAY_BE_UNUSED
  906. static void
  907. mg_global_lock(void)
  908. {
  909. (void)pthread_mutex_lock(&global_lock_mutex);
  910. }
  911. FUNCTION_MAY_BE_UNUSED
  912. static void
  913. mg_global_unlock(void)
  914. {
  915. (void)pthread_mutex_unlock(&global_lock_mutex);
  916. }
  917. #if defined(_WIN64)
  918. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  919. #elif defined(_WIN32)
  920. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  921. #endif
  922. /* Atomic functions working on ptrdiff_t ("signed size_t").
  923. * Operations: Increment, Decrement, Add, Maximum.
  924. * Up to size_t, they do not an atomic "load" operation.
  925. */
  926. FUNCTION_MAY_BE_UNUSED
  927. static ptrdiff_t
  928. mg_atomic_inc(volatile ptrdiff_t *addr)
  929. {
  930. ptrdiff_t ret;
  931. #if defined(_WIN64) && !defined(NO_ATOMICS)
  932. ret = InterlockedIncrement64(addr);
  933. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  934. ret = InterlockedIncrement(addr);
  935. #elif defined(__GNUC__) \
  936. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  937. && !defined(NO_ATOMICS)
  938. ret = __sync_add_and_fetch(addr, 1);
  939. #else
  940. mg_global_lock();
  941. ret = (++(*addr));
  942. mg_global_unlock();
  943. #endif
  944. return ret;
  945. }
  946. FUNCTION_MAY_BE_UNUSED
  947. static ptrdiff_t
  948. mg_atomic_dec(volatile ptrdiff_t *addr)
  949. {
  950. ptrdiff_t ret;
  951. #if defined(_WIN64) && !defined(NO_ATOMICS)
  952. ret = InterlockedDecrement64(addr);
  953. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  954. ret = InterlockedDecrement(addr);
  955. #elif defined(__GNUC__) \
  956. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  957. && !defined(NO_ATOMICS)
  958. ret = __sync_sub_and_fetch(addr, 1);
  959. #else
  960. mg_global_lock();
  961. ret = (--(*addr));
  962. mg_global_unlock();
  963. #endif
  964. return ret;
  965. }
  966. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  967. static ptrdiff_t
  968. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  969. {
  970. ptrdiff_t ret;
  971. #if defined(_WIN64) && !defined(NO_ATOMICS)
  972. ret = InterlockedAdd64(addr, value);
  973. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  974. ret = InterlockedExchangeAdd(addr, value) + value;
  975. #elif defined(__GNUC__) \
  976. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  977. && !defined(NO_ATOMICS)
  978. ret = __sync_add_and_fetch(addr, value);
  979. #else
  980. mg_global_lock();
  981. *addr += value;
  982. ret = (*addr);
  983. mg_global_unlock();
  984. #endif
  985. return ret;
  986. }
  987. FUNCTION_MAY_BE_UNUSED
  988. static ptrdiff_t
  989. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  990. ptrdiff_t oldval,
  991. ptrdiff_t newval)
  992. {
  993. ptrdiff_t ret;
  994. #if defined(_WIN64) && !defined(NO_ATOMICS)
  995. ret = InterlockedCompareExchange64(addr, newval, oldval);
  996. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  997. ret = InterlockedCompareExchange(addr, newval, oldval);
  998. #elif defined(__GNUC__) \
  999. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1000. && !defined(NO_ATOMICS)
  1001. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1002. #else
  1003. mg_global_lock();
  1004. ret = *addr;
  1005. if ((ret != newval) && (ret == oldval)) {
  1006. *addr = newval;
  1007. }
  1008. mg_global_unlock();
  1009. #endif
  1010. return ret;
  1011. }
  1012. static void
  1013. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1014. {
  1015. register ptrdiff_t tmp = *addr;
  1016. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1017. while (tmp < value) {
  1018. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1019. }
  1020. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1021. while (tmp < value) {
  1022. tmp = InterlockedCompareExchange(addr, value, tmp);
  1023. }
  1024. #elif defined(__GNUC__) \
  1025. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1026. && !defined(NO_ATOMICS)
  1027. while (tmp < value) {
  1028. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1029. }
  1030. #else
  1031. mg_global_lock();
  1032. if (*addr < value) {
  1033. *addr = value;
  1034. }
  1035. mg_global_unlock();
  1036. #endif
  1037. }
  1038. static int64_t
  1039. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1040. {
  1041. int64_t ret;
  1042. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1043. ret = InterlockedAdd64(addr, value);
  1044. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1045. ret = InterlockedExchangeAdd64(addr, value) + value;
  1046. #elif defined(__GNUC__) \
  1047. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1048. && !defined(NO_ATOMICS)
  1049. ret = __sync_add_and_fetch(addr, value);
  1050. #else
  1051. mg_global_lock();
  1052. *addr += value;
  1053. ret = (*addr);
  1054. mg_global_unlock();
  1055. #endif
  1056. return ret;
  1057. }
  1058. #endif
  1059. #if defined(GCC_DIAGNOSTIC)
  1060. /* Show no warning in case system functions are not used. */
  1061. #pragma GCC diagnostic pop
  1062. #endif /* defined(GCC_DIAGNOSTIC) */
  1063. #if defined(__clang__)
  1064. /* Show no warning in case system functions are not used. */
  1065. #pragma clang diagnostic pop
  1066. #endif
  1067. #if defined(USE_SERVER_STATS)
  1068. struct mg_memory_stat {
  1069. volatile ptrdiff_t totalMemUsed;
  1070. volatile ptrdiff_t maxMemUsed;
  1071. volatile ptrdiff_t blockCount;
  1072. };
  1073. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1074. static void *
  1075. mg_malloc_ex(size_t size,
  1076. struct mg_context *ctx,
  1077. const char *file,
  1078. unsigned line)
  1079. {
  1080. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1081. void *memory = 0;
  1082. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1083. #if defined(MEMORY_DEBUGGING)
  1084. char mallocStr[256];
  1085. #else
  1086. (void)file;
  1087. (void)line;
  1088. #endif
  1089. if (data) {
  1090. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1091. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1092. mg_atomic_inc(&mstat->blockCount);
  1093. ((uintptr_t *)data)[0] = size;
  1094. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1095. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1096. }
  1097. #if defined(MEMORY_DEBUGGING)
  1098. sprintf(mallocStr,
  1099. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1100. memory,
  1101. (unsigned long)size,
  1102. (unsigned long)mstat->totalMemUsed,
  1103. (unsigned long)mstat->blockCount,
  1104. file,
  1105. line);
  1106. DEBUG_TRACE("%s", mallocStr);
  1107. #endif
  1108. return memory;
  1109. }
  1110. static void *
  1111. mg_calloc_ex(size_t count,
  1112. size_t size,
  1113. struct mg_context *ctx,
  1114. const char *file,
  1115. unsigned line)
  1116. {
  1117. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1118. if (data) {
  1119. memset(data, 0, size * count);
  1120. }
  1121. return data;
  1122. }
  1123. static void
  1124. mg_free_ex(void *memory, const char *file, unsigned line)
  1125. {
  1126. #if defined(MEMORY_DEBUGGING)
  1127. char mallocStr[256];
  1128. #else
  1129. (void)file;
  1130. (void)line;
  1131. #endif
  1132. if (memory) {
  1133. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1134. uintptr_t size = ((uintptr_t *)data)[0];
  1135. struct mg_memory_stat *mstat =
  1136. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1137. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1138. mg_atomic_dec(&mstat->blockCount);
  1139. #if defined(MEMORY_DEBUGGING)
  1140. sprintf(mallocStr,
  1141. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1142. memory,
  1143. (unsigned long)size,
  1144. (unsigned long)mstat->totalMemUsed,
  1145. (unsigned long)mstat->blockCount,
  1146. file,
  1147. line);
  1148. DEBUG_TRACE("%s", mallocStr);
  1149. #endif
  1150. free(data);
  1151. }
  1152. }
  1153. static void *
  1154. mg_realloc_ex(void *memory,
  1155. size_t newsize,
  1156. struct mg_context *ctx,
  1157. const char *file,
  1158. unsigned line)
  1159. {
  1160. void *data;
  1161. void *_realloc;
  1162. uintptr_t oldsize;
  1163. #if defined(MEMORY_DEBUGGING)
  1164. char mallocStr[256];
  1165. #else
  1166. (void)file;
  1167. (void)line;
  1168. #endif
  1169. if (newsize) {
  1170. if (memory) {
  1171. /* Reallocate existing block */
  1172. struct mg_memory_stat *mstat;
  1173. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1174. oldsize = ((uintptr_t *)data)[0];
  1175. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1176. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1177. if (_realloc) {
  1178. data = _realloc;
  1179. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)oldsize,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. DEBUG_TRACE("%s", mallocStr);
  1190. #endif
  1191. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1192. #if defined(MEMORY_DEBUGGING)
  1193. sprintf(mallocStr,
  1194. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1195. memory,
  1196. (unsigned long)newsize,
  1197. (unsigned long)mstat->totalMemUsed,
  1198. (unsigned long)mstat->blockCount,
  1199. file,
  1200. line);
  1201. DEBUG_TRACE("%s", mallocStr);
  1202. #endif
  1203. *(uintptr_t *)data = newsize;
  1204. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1205. } else {
  1206. #if defined(MEMORY_DEBUGGING)
  1207. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1208. #endif
  1209. return _realloc;
  1210. }
  1211. } else {
  1212. /* Allocate new block */
  1213. data = mg_malloc_ex(newsize, ctx, file, line);
  1214. }
  1215. } else {
  1216. /* Free existing block */
  1217. data = 0;
  1218. mg_free_ex(memory, file, line);
  1219. }
  1220. return data;
  1221. }
  1222. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1223. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1224. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1225. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1226. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1227. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1228. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1229. #else /* USE_SERVER_STATS */
  1230. static __inline void *
  1231. mg_malloc(size_t a)
  1232. {
  1233. return malloc(a);
  1234. }
  1235. static __inline void *
  1236. mg_calloc(size_t a, size_t b)
  1237. {
  1238. return calloc(a, b);
  1239. }
  1240. static __inline void *
  1241. mg_realloc(void *a, size_t b)
  1242. {
  1243. return realloc(a, b);
  1244. }
  1245. static __inline void
  1246. mg_free(void *a)
  1247. {
  1248. free(a);
  1249. }
  1250. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1251. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1252. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1253. #define mg_free_ctx(a, c) mg_free(a)
  1254. #endif /* USE_SERVER_STATS */
  1255. static void mg_vsnprintf(const struct mg_connection *conn,
  1256. int *truncated,
  1257. char *buf,
  1258. size_t buflen,
  1259. const char *fmt,
  1260. va_list ap);
  1261. static void mg_snprintf(const struct mg_connection *conn,
  1262. int *truncated,
  1263. char *buf,
  1264. size_t buflen,
  1265. PRINTF_FORMAT_STRING(const char *fmt),
  1266. ...) PRINTF_ARGS(5, 6);
  1267. /* This following lines are just meant as a reminder to use the mg-functions
  1268. * for memory management */
  1269. #if defined(malloc)
  1270. #undef malloc
  1271. #endif
  1272. #if defined(calloc)
  1273. #undef calloc
  1274. #endif
  1275. #if defined(realloc)
  1276. #undef realloc
  1277. #endif
  1278. #if defined(free)
  1279. #undef free
  1280. #endif
  1281. #if defined(snprintf)
  1282. #undef snprintf
  1283. #endif
  1284. #if defined(vsnprintf)
  1285. #undef vsnprintf
  1286. #endif
  1287. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1288. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1289. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1290. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1291. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1292. #if defined(_WIN32)
  1293. /* vsnprintf must not be used in any system,
  1294. * but this define only works well for Windows. */
  1295. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1296. #endif
  1297. /* mg_init_library counter */
  1298. static int mg_init_library_called = 0;
  1299. #if !defined(NO_SSL)
  1300. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1301. || defined(OPENSSL_API_3_0)
  1302. static int mg_openssl_initialized = 0;
  1303. #endif
  1304. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1305. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1306. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1307. #endif
  1308. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1309. && defined(OPENSSL_API_3_0)
  1310. #error "Multiple OPENSSL_API versions defined"
  1311. #endif
  1312. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1313. || defined(OPENSSL_API_3_0)) \
  1314. && defined(USE_MBEDTLS)
  1315. #error "Multiple SSL libraries defined"
  1316. #endif
  1317. #endif
  1318. static pthread_key_t sTlsKey; /* Thread local storage index */
  1319. static volatile ptrdiff_t thread_idx_max = 0;
  1320. #if defined(MG_LEGACY_INTERFACE)
  1321. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1322. #endif
  1323. struct mg_workerTLS {
  1324. int is_master;
  1325. unsigned long thread_idx;
  1326. void *user_ptr;
  1327. #if defined(_WIN32)
  1328. HANDLE pthread_cond_helper_mutex;
  1329. struct mg_workerTLS *next_waiting_thread;
  1330. #endif
  1331. const char *alpn_proto;
  1332. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1333. char txtbuf[4];
  1334. #endif
  1335. };
  1336. #if defined(GCC_DIAGNOSTIC)
  1337. /* Show no warning in case system functions are not used. */
  1338. #pragma GCC diagnostic push
  1339. #pragma GCC diagnostic ignored "-Wunused-function"
  1340. #endif /* defined(GCC_DIAGNOSTIC) */
  1341. #if defined(__clang__)
  1342. /* Show no warning in case system functions are not used. */
  1343. #pragma clang diagnostic push
  1344. #pragma clang diagnostic ignored "-Wunused-function"
  1345. #endif
  1346. /* Get a unique thread ID as unsigned long, independent from the data type
  1347. * of thread IDs defined by the operating system API.
  1348. * If two calls to mg_current_thread_id return the same value, they calls
  1349. * are done from the same thread. If they return different values, they are
  1350. * done from different threads. (Provided this function is used in the same
  1351. * process context and threads are not repeatedly created and deleted, but
  1352. * CivetWeb does not do that).
  1353. * This function must match the signature required for SSL id callbacks:
  1354. * CRYPTO_set_id_callback
  1355. */
  1356. FUNCTION_MAY_BE_UNUSED
  1357. static unsigned long
  1358. mg_current_thread_id(void)
  1359. {
  1360. #if defined(_WIN32)
  1361. return GetCurrentThreadId();
  1362. #else
  1363. #if defined(__clang__)
  1364. #pragma clang diagnostic push
  1365. #pragma clang diagnostic ignored "-Wunreachable-code"
  1366. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1367. * or not, so one of the two conditions will be unreachable by construction.
  1368. * Unfortunately the C standard does not define a way to check this at
  1369. * compile time, since the #if preprocessor conditions can not use the
  1370. * sizeof operator as an argument. */
  1371. #endif
  1372. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1373. /* This is the problematic case for CRYPTO_set_id_callback:
  1374. * The OS pthread_t can not be cast to unsigned long. */
  1375. struct mg_workerTLS *tls =
  1376. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1377. if (tls == NULL) {
  1378. /* SSL called from an unknown thread: Create some thread index.
  1379. */
  1380. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1381. tls->is_master = -2; /* -2 means "3rd party thread" */
  1382. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1383. pthread_setspecific(sTlsKey, tls);
  1384. }
  1385. return tls->thread_idx;
  1386. } else {
  1387. /* pthread_t may be any data type, so a simple cast to unsigned long
  1388. * can rise a warning/error, depending on the platform.
  1389. * Here memcpy is used as an anything-to-anything cast. */
  1390. unsigned long ret = 0;
  1391. pthread_t t = pthread_self();
  1392. memcpy(&ret, &t, sizeof(pthread_t));
  1393. return ret;
  1394. }
  1395. #if defined(__clang__)
  1396. #pragma clang diagnostic pop
  1397. #endif
  1398. #endif
  1399. }
  1400. FUNCTION_MAY_BE_UNUSED
  1401. static uint64_t
  1402. mg_get_current_time_ns(void)
  1403. {
  1404. struct timespec tsnow;
  1405. clock_gettime(CLOCK_REALTIME, &tsnow);
  1406. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1407. }
  1408. #if defined(GCC_DIAGNOSTIC)
  1409. /* Show no warning in case system functions are not used. */
  1410. #pragma GCC diagnostic pop
  1411. #endif /* defined(GCC_DIAGNOSTIC) */
  1412. #if defined(__clang__)
  1413. /* Show no warning in case system functions are not used. */
  1414. #pragma clang diagnostic pop
  1415. #endif
  1416. #if defined(NEED_DEBUG_TRACE_FUNC)
  1417. static void
  1418. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1419. {
  1420. va_list args;
  1421. struct timespec tsnow;
  1422. /* Get some operating system independent thread id */
  1423. unsigned long thread_id = mg_current_thread_id();
  1424. clock_gettime(CLOCK_REALTIME, &tsnow);
  1425. flockfile(DEBUG_TRACE_STREAM);
  1426. fprintf(DEBUG_TRACE_STREAM,
  1427. "*** %lu.%09lu %lu %s:%u: ",
  1428. (unsigned long)tsnow.tv_sec,
  1429. (unsigned long)tsnow.tv_nsec,
  1430. thread_id,
  1431. func,
  1432. line);
  1433. va_start(args, fmt);
  1434. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1435. va_end(args);
  1436. putc('\n', DEBUG_TRACE_STREAM);
  1437. fflush(DEBUG_TRACE_STREAM);
  1438. funlockfile(DEBUG_TRACE_STREAM);
  1439. }
  1440. #endif /* NEED_DEBUG_TRACE_FUNC */
  1441. #define MD5_STATIC static
  1442. #include "md5.inl"
  1443. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1444. #if defined(NO_SOCKLEN_T)
  1445. typedef int socklen_t;
  1446. #endif /* NO_SOCKLEN_T */
  1447. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1448. #if !defined(MSG_NOSIGNAL)
  1449. #define MSG_NOSIGNAL (0)
  1450. #endif
  1451. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1452. #if defined(USE_MBEDTLS)
  1453. /* mbedTLS */
  1454. #include "mod_mbedtls.inl"
  1455. #elif defined(NO_SSL)
  1456. /* no SSL */
  1457. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1458. typedef struct SSL_CTX SSL_CTX;
  1459. #elif defined(NO_SSL_DL)
  1460. /* OpenSSL without dynamic loading */
  1461. #include <openssl/bn.h>
  1462. #include <openssl/conf.h>
  1463. #include <openssl/crypto.h>
  1464. #include <openssl/dh.h>
  1465. #include <openssl/engine.h>
  1466. #include <openssl/err.h>
  1467. #include <openssl/opensslv.h>
  1468. #include <openssl/pem.h>
  1469. #include <openssl/ssl.h>
  1470. #include <openssl/tls1.h>
  1471. #include <openssl/x509.h>
  1472. #if defined(WOLFSSL_VERSION)
  1473. /* Additional defines for WolfSSL, see
  1474. * https://github.com/civetweb/civetweb/issues/583 */
  1475. #include "wolfssl_extras.inl"
  1476. #endif
  1477. #if defined(OPENSSL_IS_BORINGSSL)
  1478. /* From boringssl/src/include/openssl/mem.h:
  1479. *
  1480. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1481. * However, that was written in a time before Valgrind and ASAN. Since we now
  1482. * have those tools, the OpenSSL allocation functions are simply macros around
  1483. * the standard memory functions.
  1484. *
  1485. * #define OPENSSL_free free */
  1486. #define free free
  1487. // disable for boringssl
  1488. #define CONF_modules_unload(a) ((void)0)
  1489. #define ENGINE_cleanup() ((void)0)
  1490. #endif
  1491. /* If OpenSSL headers are included, automatically select the API version */
  1492. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1493. #if !defined(OPENSSL_API_3_0)
  1494. #define OPENSSL_API_3_0
  1495. #endif
  1496. #define OPENSSL_REMOVE_THREAD_STATE()
  1497. #else
  1498. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1499. #if !defined(OPENSSL_API_1_1)
  1500. #define OPENSSL_API_1_1
  1501. #endif
  1502. #define OPENSSL_REMOVE_THREAD_STATE()
  1503. #else
  1504. #if !defined(OPENSSL_API_1_0)
  1505. #define OPENSSL_API_1_0
  1506. #endif
  1507. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1508. #endif
  1509. #endif
  1510. #else
  1511. /* SSL loaded dynamically from DLL / shared object */
  1512. /* Add all prototypes here, to be independent from OpenSSL source
  1513. * installation. */
  1514. #include "openssl_dl.inl"
  1515. #endif /* Various SSL bindings */
  1516. #if !defined(NO_CACHING)
  1517. static const char month_names[][4] = {"Jan",
  1518. "Feb",
  1519. "Mar",
  1520. "Apr",
  1521. "May",
  1522. "Jun",
  1523. "Jul",
  1524. "Aug",
  1525. "Sep",
  1526. "Oct",
  1527. "Nov",
  1528. "Dec"};
  1529. #endif /* !NO_CACHING */
  1530. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1531. * the union u. */
  1532. union usa {
  1533. struct sockaddr sa;
  1534. struct sockaddr_in sin;
  1535. #if defined(USE_IPV6)
  1536. struct sockaddr_in6 sin6;
  1537. #endif
  1538. #if defined(USE_X_DOM_SOCKET)
  1539. struct sockaddr_un sun;
  1540. #endif
  1541. };
  1542. #if defined(USE_X_DOM_SOCKET)
  1543. static unsigned short
  1544. USA_IN_PORT_UNSAFE(union usa *s)
  1545. {
  1546. if (s->sa.sa_family == AF_INET)
  1547. return s->sin.sin_port;
  1548. #if defined(USE_IPV6)
  1549. if (s->sa.sa_family == AF_INET6)
  1550. return s->sin6.sin6_port;
  1551. #endif
  1552. return 0;
  1553. }
  1554. #endif
  1555. #if defined(USE_IPV6)
  1556. #define USA_IN_PORT_UNSAFE(s) \
  1557. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1558. #else
  1559. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1560. #endif
  1561. /* Describes a string (chunk of memory). */
  1562. struct vec {
  1563. const char *ptr;
  1564. size_t len;
  1565. };
  1566. struct mg_file_stat {
  1567. /* File properties filled by mg_stat: */
  1568. uint64_t size;
  1569. time_t last_modified;
  1570. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1571. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1572. * case we need a "Content-Eencoding: gzip" header */
  1573. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1574. };
  1575. struct mg_file_access {
  1576. /* File properties filled by mg_fopen: */
  1577. FILE *fp;
  1578. };
  1579. struct mg_file {
  1580. struct mg_file_stat stat;
  1581. struct mg_file_access access;
  1582. };
  1583. #define STRUCT_FILE_INITIALIZER \
  1584. { \
  1585. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1586. { \
  1587. (FILE *)NULL \
  1588. } \
  1589. }
  1590. /* Describes listening socket, or socket which was accept()-ed by the master
  1591. * thread and queued for future handling by the worker thread. */
  1592. struct socket {
  1593. SOCKET sock; /* Listening socket */
  1594. union usa lsa; /* Local socket address */
  1595. union usa rsa; /* Remote socket address */
  1596. unsigned char is_ssl; /* Is port SSL-ed */
  1597. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1598. * port */
  1599. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1600. };
  1601. /* Enum const for all options must be in sync with
  1602. * static struct mg_option config_options[]
  1603. * This is tested in the unit test (test/private.c)
  1604. * "Private Config Options"
  1605. */
  1606. enum {
  1607. /* Once for each server */
  1608. LISTENING_PORTS,
  1609. NUM_THREADS,
  1610. RUN_AS_USER,
  1611. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1612. * socket option typedef TCP_NODELAY. */
  1613. MAX_REQUEST_SIZE,
  1614. LINGER_TIMEOUT,
  1615. CONNECTION_QUEUE_SIZE,
  1616. LISTEN_BACKLOG_SIZE,
  1617. #if defined(__linux__)
  1618. ALLOW_SENDFILE_CALL,
  1619. #endif
  1620. #if defined(_WIN32)
  1621. CASE_SENSITIVE_FILES,
  1622. #endif
  1623. THROTTLE,
  1624. ENABLE_KEEP_ALIVE,
  1625. REQUEST_TIMEOUT,
  1626. KEEP_ALIVE_TIMEOUT,
  1627. #if defined(USE_WEBSOCKET)
  1628. WEBSOCKET_TIMEOUT,
  1629. ENABLE_WEBSOCKET_PING_PONG,
  1630. #endif
  1631. DECODE_URL,
  1632. DECODE_QUERY_STRING,
  1633. #if defined(USE_LUA)
  1634. LUA_BACKGROUND_SCRIPT,
  1635. LUA_BACKGROUND_SCRIPT_PARAMS,
  1636. #endif
  1637. #if defined(USE_HTTP2)
  1638. ENABLE_HTTP2,
  1639. #endif
  1640. /* Once for each domain */
  1641. DOCUMENT_ROOT,
  1642. ACCESS_LOG_FILE,
  1643. ERROR_LOG_FILE,
  1644. CGI_EXTENSIONS,
  1645. CGI_ENVIRONMENT,
  1646. CGI_INTERPRETER,
  1647. CGI_INTERPRETER_ARGS,
  1648. #if defined(USE_TIMERS)
  1649. CGI_TIMEOUT,
  1650. #endif
  1651. CGI2_EXTENSIONS,
  1652. CGI2_ENVIRONMENT,
  1653. CGI2_INTERPRETER,
  1654. CGI2_INTERPRETER_ARGS,
  1655. #if defined(USE_TIMERS)
  1656. CGI2_TIMEOUT,
  1657. #endif
  1658. #if defined(USE_4_CGI)
  1659. CGI3_EXTENSIONS,
  1660. CGI3_ENVIRONMENT,
  1661. CGI3_INTERPRETER,
  1662. CGI3_INTERPRETER_ARGS,
  1663. #if defined(USE_TIMERS)
  1664. CGI3_TIMEOUT,
  1665. #endif
  1666. CGI4_EXTENSIONS,
  1667. CGI4_ENVIRONMENT,
  1668. CGI4_INTERPRETER,
  1669. CGI4_INTERPRETER_ARGS,
  1670. #if defined(USE_TIMERS)
  1671. CGI4_TIMEOUT,
  1672. #endif
  1673. #endif
  1674. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1675. PROTECT_URI,
  1676. AUTHENTICATION_DOMAIN,
  1677. ENABLE_AUTH_DOMAIN_CHECK,
  1678. SSI_EXTENSIONS,
  1679. ENABLE_DIRECTORY_LISTING,
  1680. GLOBAL_PASSWORDS_FILE,
  1681. INDEX_FILES,
  1682. ACCESS_CONTROL_LIST,
  1683. EXTRA_MIME_TYPES,
  1684. SSL_CERTIFICATE,
  1685. SSL_CERTIFICATE_CHAIN,
  1686. URL_REWRITE_PATTERN,
  1687. HIDE_FILES,
  1688. SSL_DO_VERIFY_PEER,
  1689. SSL_CACHE_TIMEOUT,
  1690. SSL_CA_PATH,
  1691. SSL_CA_FILE,
  1692. SSL_VERIFY_DEPTH,
  1693. SSL_DEFAULT_VERIFY_PATHS,
  1694. SSL_CIPHER_LIST,
  1695. SSL_PROTOCOL_VERSION,
  1696. SSL_SHORT_TRUST,
  1697. #if defined(USE_LUA)
  1698. LUA_PRELOAD_FILE,
  1699. LUA_SCRIPT_EXTENSIONS,
  1700. LUA_SERVER_PAGE_EXTENSIONS,
  1701. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1702. LUA_DEBUG_PARAMS,
  1703. #endif
  1704. #endif
  1705. #if defined(USE_DUKTAPE)
  1706. DUKTAPE_SCRIPT_EXTENSIONS,
  1707. #endif
  1708. #if defined(USE_WEBSOCKET)
  1709. WEBSOCKET_ROOT,
  1710. #endif
  1711. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1712. LUA_WEBSOCKET_EXTENSIONS,
  1713. #endif
  1714. ACCESS_CONTROL_ALLOW_ORIGIN,
  1715. ACCESS_CONTROL_ALLOW_METHODS,
  1716. ACCESS_CONTROL_ALLOW_HEADERS,
  1717. ERROR_PAGES,
  1718. #if !defined(NO_CACHING)
  1719. STATIC_FILE_MAX_AGE,
  1720. STATIC_FILE_CACHE_CONTROL,
  1721. #endif
  1722. #if !defined(NO_SSL)
  1723. STRICT_HTTPS_MAX_AGE,
  1724. #endif
  1725. ADDITIONAL_HEADER,
  1726. ALLOW_INDEX_SCRIPT_SUB_RES,
  1727. NUM_OPTIONS
  1728. };
  1729. /* Config option name, config types, default value.
  1730. * Must be in the same order as the enum const above.
  1731. */
  1732. static const struct mg_option config_options[] = {
  1733. /* Once for each server */
  1734. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1735. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1736. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1737. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1738. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1739. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1740. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1741. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1742. #if defined(__linux__)
  1743. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1744. #endif
  1745. #if defined(_WIN32)
  1746. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1747. #endif
  1748. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1749. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1750. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1751. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1752. #if defined(USE_WEBSOCKET)
  1753. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1754. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1755. #endif
  1756. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1757. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1758. #if defined(USE_LUA)
  1759. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1760. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1761. #endif
  1762. #if defined(USE_HTTP2)
  1763. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1764. #endif
  1765. /* Once for each domain */
  1766. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1767. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1768. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1769. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1770. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1771. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1772. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1773. #if defined(USE_TIMERS)
  1774. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1775. #endif
  1776. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1777. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1778. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1779. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1780. #if defined(USE_TIMERS)
  1781. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1782. #endif
  1783. #if defined(USE_4_CGI)
  1784. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1785. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1786. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1787. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1788. #if defined(USE_TIMERS)
  1789. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1790. #endif
  1791. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1792. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1793. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1794. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1795. #if defined(USE_TIMERS)
  1796. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1797. #endif
  1798. #endif
  1799. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1800. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1801. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1802. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1803. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1804. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1805. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1806. {"index_files",
  1807. MG_CONFIG_TYPE_STRING_LIST,
  1808. #if defined(USE_LUA)
  1809. "index.xhtml,index.html,index.htm,"
  1810. "index.lp,index.lsp,index.lua,index.cgi,"
  1811. "index.shtml,index.php"},
  1812. #else
  1813. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1814. #endif
  1815. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1816. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1817. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1818. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1819. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1820. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1821. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1822. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1823. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1824. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1825. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1826. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1827. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1828. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1829. * as a minimum in 2020 */
  1830. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1831. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1832. #if defined(USE_LUA)
  1833. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1834. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1835. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1836. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1837. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1838. #endif
  1839. #endif
  1840. #if defined(USE_DUKTAPE)
  1841. /* The support for duktape is still in alpha version state.
  1842. * The name of this config option might change. */
  1843. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1844. #endif
  1845. #if defined(USE_WEBSOCKET)
  1846. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1847. #endif
  1848. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1849. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1850. #endif
  1851. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1852. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1853. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1854. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1855. #if !defined(NO_CACHING)
  1856. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1857. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1858. #endif
  1859. #if !defined(NO_SSL)
  1860. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1861. #endif
  1862. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1863. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1864. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1865. /* Check if the config_options and the corresponding enum have compatible
  1866. * sizes. */
  1867. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1868. == (NUM_OPTIONS + 1),
  1869. "config_options and enum not sync");
  1870. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1871. struct mg_handler_info {
  1872. /* Name/Pattern of the URI. */
  1873. char *uri;
  1874. size_t uri_len;
  1875. /* handler type */
  1876. int handler_type;
  1877. /* Handler for http/https or authorization requests. */
  1878. mg_request_handler handler;
  1879. unsigned int refcount;
  1880. int removing;
  1881. /* Handler for ws/wss (websocket) requests. */
  1882. mg_websocket_connect_handler connect_handler;
  1883. mg_websocket_ready_handler ready_handler;
  1884. mg_websocket_data_handler data_handler;
  1885. mg_websocket_close_handler close_handler;
  1886. /* accepted subprotocols for ws/wss requests. */
  1887. struct mg_websocket_subprotocols *subprotocols;
  1888. /* Handler for authorization requests */
  1889. mg_authorization_handler auth_handler;
  1890. /* User supplied argument for the handler function. */
  1891. void *cbdata;
  1892. /* next handler in a linked list */
  1893. struct mg_handler_info *next;
  1894. };
  1895. enum {
  1896. CONTEXT_INVALID,
  1897. CONTEXT_SERVER,
  1898. CONTEXT_HTTP_CLIENT,
  1899. CONTEXT_WS_CLIENT
  1900. };
  1901. struct mg_domain_context {
  1902. SSL_CTX *ssl_ctx; /* SSL context */
  1903. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1904. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1905. int64_t ssl_cert_last_mtime;
  1906. /* Server nonce */
  1907. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1908. unsigned long nonce_count; /* Used nonces, used for authentication */
  1909. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1910. /* linked list of shared lua websockets */
  1911. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1912. #endif
  1913. /* Linked list of domains */
  1914. struct mg_domain_context *next;
  1915. };
  1916. /* Stop flag can be "volatile" or require a lock.
  1917. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1918. * states a read operation for int is always atomic. */
  1919. #if defined(STOP_FLAG_NEEDS_LOCK)
  1920. typedef ptrdiff_t volatile stop_flag_t;
  1921. static int
  1922. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  1923. {
  1924. stop_flag_t sf = mg_atomic_add(f, 0);
  1925. return (sf == 0);
  1926. }
  1927. static int
  1928. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1929. {
  1930. stop_flag_t sf = mg_atomic_add(f, 0);
  1931. return (sf == 2);
  1932. }
  1933. static void
  1934. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1935. {
  1936. stop_flag_t sf;
  1937. do {
  1938. sf = mg_atomic_compare_and_swap(f, *f, v);
  1939. } while (sf != v);
  1940. }
  1941. #else /* STOP_FLAG_NEEDS_LOCK */
  1942. typedef int volatile stop_flag_t;
  1943. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1944. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1945. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1946. #endif /* STOP_FLAG_NEEDS_LOCK */
  1947. struct mg_context {
  1948. /* Part 1 - Physical context:
  1949. * This holds threads, ports, timeouts, ...
  1950. * set for the entire server, independent from the
  1951. * addressed hostname.
  1952. */
  1953. /* Connection related */
  1954. int context_type; /* See CONTEXT_* above */
  1955. struct socket *listening_sockets;
  1956. struct mg_pollfd *listening_socket_fds;
  1957. unsigned int num_listening_sockets;
  1958. struct mg_connection *worker_connections; /* The connection struct, pre-
  1959. * allocated for each worker */
  1960. #if defined(USE_SERVER_STATS)
  1961. volatile ptrdiff_t active_connections;
  1962. volatile ptrdiff_t max_active_connections;
  1963. volatile ptrdiff_t total_connections;
  1964. volatile ptrdiff_t total_requests;
  1965. volatile int64_t total_data_read;
  1966. volatile int64_t total_data_written;
  1967. #endif
  1968. /* Thread related */
  1969. stop_flag_t stop_flag; /* Should we stop event loop */
  1970. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1971. pthread_t masterthreadid; /* The master thread ID */
  1972. unsigned int
  1973. cfg_worker_threads; /* The number of configured worker threads. */
  1974. pthread_t *worker_threadids; /* The worker thread IDs */
  1975. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1976. /* Connection to thread dispatching */
  1977. #if defined(ALTERNATIVE_QUEUE)
  1978. struct socket *client_socks;
  1979. void **client_wait_events;
  1980. #else
  1981. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  1982. worker thread */
  1983. volatile int sq_head; /* Head of the socket queue */
  1984. volatile int sq_tail; /* Tail of the socket queue */
  1985. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1986. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1987. volatile int sq_blocked; /* Status information: sq is full */
  1988. int sq_size; /* No of elements in socket queue */
  1989. #if defined(USE_SERVER_STATS)
  1990. int sq_max_fill;
  1991. #endif /* USE_SERVER_STATS */
  1992. #endif /* ALTERNATIVE_QUEUE */
  1993. /* Memory related */
  1994. unsigned int max_request_size; /* The max request size */
  1995. #if defined(USE_SERVER_STATS)
  1996. struct mg_memory_stat ctx_memory;
  1997. #endif
  1998. /* Operating system related */
  1999. char *systemName; /* What operating system is running */
  2000. time_t start_time; /* Server start time, used for authentication
  2001. * and for diagnstics. */
  2002. #if defined(USE_TIMERS)
  2003. struct ttimers *timers;
  2004. #endif
  2005. /* Lua specific: Background operations and shared websockets */
  2006. #if defined(USE_LUA)
  2007. void *lua_background_state; /* lua_State (here as void *) */
  2008. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2009. int lua_bg_log_available; /* Use Lua background state for access log */
  2010. #endif
  2011. /* Server nonce */
  2012. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2013. * ssl_cert_last_mtime, nonce_count, and
  2014. * next (linked list) */
  2015. /* Server callbacks */
  2016. struct mg_callbacks callbacks; /* User-defined callback function */
  2017. void *user_data; /* User-defined data */
  2018. /* Part 2 - Logical domain:
  2019. * This holds hostname, TLS certificate, document root, ...
  2020. * set for a domain hosted at the server.
  2021. * There may be multiple domains hosted at one physical server.
  2022. * The default domain "dd" is the first element of a list of
  2023. * domains.
  2024. */
  2025. struct mg_domain_context dd; /* default domain */
  2026. };
  2027. #if defined(USE_SERVER_STATS)
  2028. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2029. static struct mg_memory_stat *
  2030. get_memory_stat(struct mg_context *ctx)
  2031. {
  2032. if (ctx) {
  2033. return &(ctx->ctx_memory);
  2034. }
  2035. return &mg_common_memory;
  2036. }
  2037. #endif
  2038. enum {
  2039. CONNECTION_TYPE_INVALID = 0,
  2040. CONNECTION_TYPE_REQUEST = 1,
  2041. CONNECTION_TYPE_RESPONSE = 2
  2042. };
  2043. enum {
  2044. PROTOCOL_TYPE_HTTP1 = 0,
  2045. PROTOCOL_TYPE_WEBSOCKET = 1,
  2046. PROTOCOL_TYPE_HTTP2 = 2
  2047. };
  2048. #if defined(USE_HTTP2)
  2049. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2050. #define HTTP2_DYN_TABLE_SIZE (256)
  2051. #endif
  2052. struct mg_http2_connection {
  2053. uint32_t stream_id;
  2054. uint32_t dyn_table_size;
  2055. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2056. };
  2057. #endif
  2058. struct mg_connection {
  2059. int connection_type; /* see CONNECTION_TYPE_* above */
  2060. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2061. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2062. fully sent */
  2063. #if defined(USE_HTTP2)
  2064. struct mg_http2_connection http2;
  2065. #endif
  2066. struct mg_request_info request_info;
  2067. struct mg_response_info response_info;
  2068. struct mg_context *phys_ctx;
  2069. struct mg_domain_context *dom_ctx;
  2070. #if defined(USE_SERVER_STATS)
  2071. int conn_state; /* 0 = undef, numerical value may change in different
  2072. * versions. For the current definition, see
  2073. * mg_get_connection_info_impl */
  2074. #endif
  2075. SSL *ssl; /* SSL descriptor */
  2076. struct socket client; /* Connected client */
  2077. time_t conn_birth_time; /* Time (wall clock) when connection was
  2078. * established */
  2079. #if defined(USE_SERVER_STATS)
  2080. time_t conn_close_time; /* Time (wall clock) when connection was
  2081. * closed (or 0 if still open) */
  2082. double processing_time; /* Procesing time for one request. */
  2083. #endif
  2084. struct timespec req_time; /* Time (since system start) when the request
  2085. * was received */
  2086. int64_t num_bytes_sent; /* Total bytes sent to client */
  2087. int64_t content_len; /* How many bytes of content can be read
  2088. * !is_chunked: Content-Length header value
  2089. * or -1 (until connection closed,
  2090. * not allowed for a request)
  2091. * is_chunked: >= 0, appended gradually
  2092. */
  2093. int64_t consumed_content; /* How many bytes of content have been read */
  2094. int is_chunked; /* Transfer-Encoding is chunked:
  2095. * 0 = not chunked,
  2096. * 1 = chunked, not yet, or some data read,
  2097. * 2 = chunked, has error,
  2098. * 3 = chunked, all data read except trailer,
  2099. * 4 = chunked, all data read
  2100. */
  2101. char *buf; /* Buffer for received data */
  2102. char *path_info; /* PATH_INFO part of the URL */
  2103. int must_close; /* 1 if connection must be closed */
  2104. int accept_gzip; /* 1 if gzip encoding is accepted */
  2105. int in_error_handler; /* 1 if in handler for user defined error
  2106. * pages */
  2107. #if defined(USE_WEBSOCKET)
  2108. int in_websocket_handling; /* 1 if in read_websocket */
  2109. #endif
  2110. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2111. && defined(MG_EXPERIMENTAL_INTERFACES)
  2112. /* Parameters for websocket data compression according to rfc7692 */
  2113. int websocket_deflate_server_max_windows_bits;
  2114. int websocket_deflate_client_max_windows_bits;
  2115. int websocket_deflate_server_no_context_takeover;
  2116. int websocket_deflate_client_no_context_takeover;
  2117. int websocket_deflate_initialized;
  2118. int websocket_deflate_flush;
  2119. z_stream websocket_deflate_state;
  2120. z_stream websocket_inflate_state;
  2121. #endif
  2122. int handled_requests; /* Number of requests handled by this connection
  2123. */
  2124. int buf_size; /* Buffer size */
  2125. int request_len; /* Size of the request + headers in a buffer */
  2126. int data_len; /* Total size of data in a buffer */
  2127. int status_code; /* HTTP reply status code, e.g. 200 */
  2128. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2129. * throttle */
  2130. time_t last_throttle_time; /* Last time throttled data was sent */
  2131. int last_throttle_bytes; /* Bytes sent this second */
  2132. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2133. * atomic transmissions for websockets */
  2134. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2135. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2136. #endif
  2137. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2138. * for quick access */
  2139. };
  2140. /* Directory entry */
  2141. struct de {
  2142. struct mg_connection *conn;
  2143. char *file_name;
  2144. struct mg_file_stat file;
  2145. };
  2146. #define mg_cry_internal(conn, fmt, ...) \
  2147. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2148. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2149. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2150. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2151. struct mg_context *ctx,
  2152. const char *func,
  2153. unsigned line,
  2154. const char *fmt,
  2155. ...) PRINTF_ARGS(5, 6);
  2156. #if !defined(NO_THREAD_NAME)
  2157. #if defined(_WIN32) && defined(_MSC_VER)
  2158. /* Set the thread name for debugging purposes in Visual Studio
  2159. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2160. */
  2161. #pragma pack(push, 8)
  2162. typedef struct tagTHREADNAME_INFO {
  2163. DWORD dwType; /* Must be 0x1000. */
  2164. LPCSTR szName; /* Pointer to name (in user addr space). */
  2165. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2166. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2167. } THREADNAME_INFO;
  2168. #pragma pack(pop)
  2169. #elif defined(__linux__)
  2170. #include <sys/prctl.h>
  2171. #include <sys/sendfile.h>
  2172. #if defined(ALTERNATIVE_QUEUE)
  2173. #include <sys/eventfd.h>
  2174. #endif /* ALTERNATIVE_QUEUE */
  2175. #if defined(ALTERNATIVE_QUEUE)
  2176. static void *
  2177. event_create(void)
  2178. {
  2179. int evhdl = eventfd(0, EFD_CLOEXEC);
  2180. int *ret;
  2181. if (evhdl == -1) {
  2182. /* Linux uses -1 on error, Windows NULL. */
  2183. /* However, Linux does not return 0 on success either. */
  2184. return 0;
  2185. }
  2186. ret = (int *)mg_malloc(sizeof(int));
  2187. if (ret) {
  2188. *ret = evhdl;
  2189. } else {
  2190. (void)close(evhdl);
  2191. }
  2192. return (void *)ret;
  2193. }
  2194. static int
  2195. event_wait(void *eventhdl)
  2196. {
  2197. uint64_t u;
  2198. int evhdl, s;
  2199. if (!eventhdl) {
  2200. /* error */
  2201. return 0;
  2202. }
  2203. evhdl = *(int *)eventhdl;
  2204. s = (int)read(evhdl, &u, sizeof(u));
  2205. if (s != sizeof(u)) {
  2206. /* error */
  2207. return 0;
  2208. }
  2209. (void)u; /* the value is not required */
  2210. return 1;
  2211. }
  2212. static int
  2213. event_signal(void *eventhdl)
  2214. {
  2215. uint64_t u = 1;
  2216. int evhdl, s;
  2217. if (!eventhdl) {
  2218. /* error */
  2219. return 0;
  2220. }
  2221. evhdl = *(int *)eventhdl;
  2222. s = (int)write(evhdl, &u, sizeof(u));
  2223. if (s != sizeof(u)) {
  2224. /* error */
  2225. return 0;
  2226. }
  2227. return 1;
  2228. }
  2229. static void
  2230. event_destroy(void *eventhdl)
  2231. {
  2232. int evhdl;
  2233. if (!eventhdl) {
  2234. /* error */
  2235. return;
  2236. }
  2237. evhdl = *(int *)eventhdl;
  2238. close(evhdl);
  2239. mg_free(eventhdl);
  2240. }
  2241. #endif
  2242. #endif
  2243. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2244. struct posix_event {
  2245. pthread_mutex_t mutex;
  2246. pthread_cond_t cond;
  2247. int signaled;
  2248. };
  2249. static void *
  2250. event_create(void)
  2251. {
  2252. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2253. if (ret == 0) {
  2254. /* out of memory */
  2255. return 0;
  2256. }
  2257. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2258. /* pthread mutex not available */
  2259. mg_free(ret);
  2260. return 0;
  2261. }
  2262. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2263. /* pthread cond not available */
  2264. pthread_mutex_destroy(&(ret->mutex));
  2265. mg_free(ret);
  2266. return 0;
  2267. }
  2268. ret->signaled = 0;
  2269. return (void *)ret;
  2270. }
  2271. static int
  2272. event_wait(void *eventhdl)
  2273. {
  2274. struct posix_event *ev = (struct posix_event *)eventhdl;
  2275. pthread_mutex_lock(&(ev->mutex));
  2276. while (!ev->signaled) {
  2277. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2278. }
  2279. ev->signaled = 0;
  2280. pthread_mutex_unlock(&(ev->mutex));
  2281. return 1;
  2282. }
  2283. static int
  2284. event_signal(void *eventhdl)
  2285. {
  2286. struct posix_event *ev = (struct posix_event *)eventhdl;
  2287. pthread_mutex_lock(&(ev->mutex));
  2288. pthread_cond_signal(&(ev->cond));
  2289. ev->signaled = 1;
  2290. pthread_mutex_unlock(&(ev->mutex));
  2291. return 1;
  2292. }
  2293. static void
  2294. event_destroy(void *eventhdl)
  2295. {
  2296. struct posix_event *ev = (struct posix_event *)eventhdl;
  2297. pthread_cond_destroy(&(ev->cond));
  2298. pthread_mutex_destroy(&(ev->mutex));
  2299. mg_free(ev);
  2300. }
  2301. #endif
  2302. static void
  2303. mg_set_thread_name(const char *name)
  2304. {
  2305. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2306. mg_snprintf(
  2307. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2308. #if defined(_WIN32)
  2309. #if defined(_MSC_VER)
  2310. /* Windows and Visual Studio Compiler */
  2311. __try {
  2312. THREADNAME_INFO info;
  2313. info.dwType = 0x1000;
  2314. info.szName = threadName;
  2315. info.dwThreadID = ~0U;
  2316. info.dwFlags = 0;
  2317. RaiseException(0x406D1388,
  2318. 0,
  2319. sizeof(info) / sizeof(ULONG_PTR),
  2320. (ULONG_PTR *)&info);
  2321. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2322. }
  2323. #elif defined(__MINGW32__)
  2324. /* No option known to set thread name for MinGW known */
  2325. #endif
  2326. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2327. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2328. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2329. #if defined(__MACH__)
  2330. /* OS X only current thread name can be changed */
  2331. (void)pthread_setname_np(threadName);
  2332. #else
  2333. (void)pthread_setname_np(pthread_self(), threadName);
  2334. #endif
  2335. #elif defined(__linux__)
  2336. /* On Linux we can use the prctl function.
  2337. * When building for Linux Standard Base (LSB) use
  2338. * NO_THREAD_NAME. However, thread names are a big
  2339. * help for debugging, so the stadard is to set them.
  2340. */
  2341. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2342. #endif
  2343. }
  2344. #else /* !defined(NO_THREAD_NAME) */
  2345. void
  2346. mg_set_thread_name(const char *threadName)
  2347. {
  2348. }
  2349. #endif
  2350. const struct mg_option *
  2351. mg_get_valid_options(void)
  2352. {
  2353. return config_options;
  2354. }
  2355. /* Do not open file (unused) */
  2356. #define MG_FOPEN_MODE_NONE (0)
  2357. /* Open file for read only access */
  2358. #define MG_FOPEN_MODE_READ (1)
  2359. /* Open file for writing, create and overwrite */
  2360. #define MG_FOPEN_MODE_WRITE (2)
  2361. /* Open file for writing, create and append */
  2362. #define MG_FOPEN_MODE_APPEND (4)
  2363. static int
  2364. is_file_opened(const struct mg_file_access *fileacc)
  2365. {
  2366. if (!fileacc) {
  2367. return 0;
  2368. }
  2369. return (fileacc->fp != NULL);
  2370. }
  2371. #if !defined(NO_FILESYSTEMS)
  2372. static int mg_stat(const struct mg_connection *conn,
  2373. const char *path,
  2374. struct mg_file_stat *filep);
  2375. /* Reject files with special characters (for Windows) */
  2376. static int
  2377. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2378. {
  2379. const uint8_t *c = (const uint8_t *)path;
  2380. (void)conn; /* not used */
  2381. if ((c == NULL) || (c[0] == 0)) {
  2382. /* Null pointer or empty path --> suspicious */
  2383. return 1;
  2384. }
  2385. #if defined(_WIN32)
  2386. while (*c) {
  2387. if (*c < 32) {
  2388. /* Control character */
  2389. return 1;
  2390. }
  2391. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2392. /* stdin/stdout redirection character */
  2393. return 1;
  2394. }
  2395. if ((*c == '*') || (*c == '?')) {
  2396. /* Wildcard character */
  2397. return 1;
  2398. }
  2399. if (*c == '"') {
  2400. /* Windows quotation */
  2401. return 1;
  2402. }
  2403. c++;
  2404. }
  2405. #endif
  2406. /* Nothing suspicious found */
  2407. return 0;
  2408. }
  2409. /* mg_fopen will open a file either in memory or on the disk.
  2410. * The input parameter path is a string in UTF-8 encoding.
  2411. * The input parameter mode is MG_FOPEN_MODE_*
  2412. * On success, fp will be set in the output struct mg_file.
  2413. * All status members will also be set.
  2414. * The function returns 1 on success, 0 on error. */
  2415. static int
  2416. mg_fopen(const struct mg_connection *conn,
  2417. const char *path,
  2418. int mode,
  2419. struct mg_file *filep)
  2420. {
  2421. int found;
  2422. if (!filep) {
  2423. return 0;
  2424. }
  2425. filep->access.fp = NULL;
  2426. if (mg_path_suspicious(conn, path)) {
  2427. return 0;
  2428. }
  2429. /* filep is initialized in mg_stat: all fields with memset to,
  2430. * some fields like size and modification date with values */
  2431. found = mg_stat(conn, path, &(filep->stat));
  2432. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2433. /* file does not exist and will not be created */
  2434. return 0;
  2435. }
  2436. #if defined(_WIN32)
  2437. {
  2438. wchar_t wbuf[UTF16_PATH_MAX];
  2439. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2440. switch (mode) {
  2441. case MG_FOPEN_MODE_READ:
  2442. filep->access.fp = _wfopen(wbuf, L"rb");
  2443. break;
  2444. case MG_FOPEN_MODE_WRITE:
  2445. filep->access.fp = _wfopen(wbuf, L"wb");
  2446. break;
  2447. case MG_FOPEN_MODE_APPEND:
  2448. filep->access.fp = _wfopen(wbuf, L"ab");
  2449. break;
  2450. }
  2451. }
  2452. #else
  2453. /* Linux et al already use unicode. No need to convert. */
  2454. switch (mode) {
  2455. case MG_FOPEN_MODE_READ:
  2456. filep->access.fp = fopen(path, "r");
  2457. break;
  2458. case MG_FOPEN_MODE_WRITE:
  2459. filep->access.fp = fopen(path, "w");
  2460. break;
  2461. case MG_FOPEN_MODE_APPEND:
  2462. filep->access.fp = fopen(path, "a");
  2463. break;
  2464. }
  2465. #endif
  2466. if (!found) {
  2467. /* File did not exist before fopen was called.
  2468. * Maybe it has been created now. Get stat info
  2469. * like creation time now. */
  2470. found = mg_stat(conn, path, &(filep->stat));
  2471. (void)found;
  2472. }
  2473. /* return OK if file is opened */
  2474. return (filep->access.fp != NULL);
  2475. }
  2476. /* return 0 on success, just like fclose */
  2477. static int
  2478. mg_fclose(struct mg_file_access *fileacc)
  2479. {
  2480. int ret = -1;
  2481. if (fileacc != NULL) {
  2482. if (fileacc->fp != NULL) {
  2483. ret = fclose(fileacc->fp);
  2484. }
  2485. /* reset all members of fileacc */
  2486. memset(fileacc, 0, sizeof(*fileacc));
  2487. }
  2488. return ret;
  2489. }
  2490. #endif /* NO_FILESYSTEMS */
  2491. static void
  2492. mg_strlcpy(char *dst, const char *src, size_t n)
  2493. {
  2494. for (; *src != '\0' && n > 1; n--) {
  2495. *dst++ = *src++;
  2496. }
  2497. *dst = '\0';
  2498. }
  2499. static int
  2500. lowercase(const char *s)
  2501. {
  2502. return tolower((unsigned char)*s);
  2503. }
  2504. int
  2505. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2506. {
  2507. int diff = 0;
  2508. if (len > 0) {
  2509. do {
  2510. diff = lowercase(s1++) - lowercase(s2++);
  2511. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2512. }
  2513. return diff;
  2514. }
  2515. int
  2516. mg_strcasecmp(const char *s1, const char *s2)
  2517. {
  2518. int diff;
  2519. do {
  2520. diff = lowercase(s1++) - lowercase(s2++);
  2521. } while (diff == 0 && s1[-1] != '\0');
  2522. return diff;
  2523. }
  2524. static char *
  2525. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2526. {
  2527. char *p;
  2528. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2529. * defined */
  2530. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2531. mg_strlcpy(p, ptr, len + 1);
  2532. }
  2533. return p;
  2534. }
  2535. static char *
  2536. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2537. {
  2538. return mg_strndup_ctx(str, strlen(str), ctx);
  2539. }
  2540. static char *
  2541. mg_strdup(const char *str)
  2542. {
  2543. return mg_strndup_ctx(str, strlen(str), NULL);
  2544. }
  2545. static const char *
  2546. mg_strcasestr(const char *big_str, const char *small_str)
  2547. {
  2548. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2549. if (big_len >= small_len) {
  2550. for (i = 0; i <= (big_len - small_len); i++) {
  2551. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2552. return big_str + i;
  2553. }
  2554. }
  2555. }
  2556. return NULL;
  2557. }
  2558. /* Return null terminated string of given maximum length.
  2559. * Report errors if length is exceeded. */
  2560. static void
  2561. mg_vsnprintf(const struct mg_connection *conn,
  2562. int *truncated,
  2563. char *buf,
  2564. size_t buflen,
  2565. const char *fmt,
  2566. va_list ap)
  2567. {
  2568. int n, ok;
  2569. if (buflen == 0) {
  2570. if (truncated) {
  2571. *truncated = 1;
  2572. }
  2573. return;
  2574. }
  2575. #if defined(__clang__)
  2576. #pragma clang diagnostic push
  2577. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2578. /* Using fmt as a non-literal is intended here, since it is mostly called
  2579. * indirectly by mg_snprintf */
  2580. #endif
  2581. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2582. ok = (n >= 0) && ((size_t)n < buflen);
  2583. #if defined(__clang__)
  2584. #pragma clang diagnostic pop
  2585. #endif
  2586. if (ok) {
  2587. if (truncated) {
  2588. *truncated = 0;
  2589. }
  2590. } else {
  2591. if (truncated) {
  2592. *truncated = 1;
  2593. }
  2594. mg_cry_internal(conn,
  2595. "truncating vsnprintf buffer: [%.*s]",
  2596. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2597. buf);
  2598. n = (int)buflen - 1;
  2599. }
  2600. buf[n] = '\0';
  2601. }
  2602. static void
  2603. mg_snprintf(const struct mg_connection *conn,
  2604. int *truncated,
  2605. char *buf,
  2606. size_t buflen,
  2607. const char *fmt,
  2608. ...)
  2609. {
  2610. va_list ap;
  2611. va_start(ap, fmt);
  2612. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2613. va_end(ap);
  2614. }
  2615. static int
  2616. get_option_index(const char *name)
  2617. {
  2618. int i;
  2619. for (i = 0; config_options[i].name != NULL; i++) {
  2620. if (strcmp(config_options[i].name, name) == 0) {
  2621. return i;
  2622. }
  2623. }
  2624. return -1;
  2625. }
  2626. const char *
  2627. mg_get_option(const struct mg_context *ctx, const char *name)
  2628. {
  2629. int i;
  2630. if ((i = get_option_index(name)) == -1) {
  2631. return NULL;
  2632. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2633. return "";
  2634. } else {
  2635. return ctx->dd.config[i];
  2636. }
  2637. }
  2638. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2639. struct mg_context *
  2640. mg_get_context(const struct mg_connection *conn)
  2641. {
  2642. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2643. }
  2644. void *
  2645. mg_get_user_data(const struct mg_context *ctx)
  2646. {
  2647. return (ctx == NULL) ? NULL : ctx->user_data;
  2648. }
  2649. void *
  2650. mg_get_user_context_data(const struct mg_connection *conn)
  2651. {
  2652. return mg_get_user_data(mg_get_context(conn));
  2653. }
  2654. void *
  2655. mg_get_thread_pointer(const struct mg_connection *conn)
  2656. {
  2657. /* both methods should return the same pointer */
  2658. if (conn) {
  2659. /* quick access, in case conn is known */
  2660. return conn->tls_user_ptr;
  2661. } else {
  2662. /* otherwise get pointer from thread local storage (TLS) */
  2663. struct mg_workerTLS *tls =
  2664. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2665. return tls->user_ptr;
  2666. }
  2667. }
  2668. void
  2669. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2670. {
  2671. if (const_conn != NULL) {
  2672. /* Const cast, since "const struct mg_connection *" does not mean
  2673. * the connection object is not modified. Here "const" is used,
  2674. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2675. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2676. conn->request_info.conn_data = data;
  2677. }
  2678. }
  2679. void *
  2680. mg_get_user_connection_data(const struct mg_connection *conn)
  2681. {
  2682. if (conn != NULL) {
  2683. return conn->request_info.conn_data;
  2684. }
  2685. return NULL;
  2686. }
  2687. int
  2688. mg_get_server_ports(const struct mg_context *ctx,
  2689. int size,
  2690. struct mg_server_port *ports)
  2691. {
  2692. int i, cnt = 0;
  2693. if (size <= 0) {
  2694. return -1;
  2695. }
  2696. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2697. if (!ctx) {
  2698. return -1;
  2699. }
  2700. if (!ctx->listening_sockets) {
  2701. return -1;
  2702. }
  2703. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2704. ports[cnt].port =
  2705. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2706. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2707. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2708. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2709. /* IPv4 */
  2710. ports[cnt].protocol = 1;
  2711. cnt++;
  2712. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2713. /* IPv6 */
  2714. ports[cnt].protocol = 3;
  2715. cnt++;
  2716. }
  2717. }
  2718. return cnt;
  2719. }
  2720. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2721. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2722. #endif
  2723. static void
  2724. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2725. {
  2726. buf[0] = '\0';
  2727. if (!usa) {
  2728. return;
  2729. }
  2730. if (usa->sa.sa_family == AF_INET) {
  2731. getnameinfo(&usa->sa,
  2732. sizeof(usa->sin),
  2733. buf,
  2734. (unsigned)len,
  2735. NULL,
  2736. 0,
  2737. NI_NUMERICHOST);
  2738. }
  2739. #if defined(USE_IPV6)
  2740. else if (usa->sa.sa_family == AF_INET6) {
  2741. getnameinfo(&usa->sa,
  2742. sizeof(usa->sin6),
  2743. buf,
  2744. (unsigned)len,
  2745. NULL,
  2746. 0,
  2747. NI_NUMERICHOST);
  2748. }
  2749. #endif
  2750. #if defined(USE_X_DOM_SOCKET)
  2751. else if (usa->sa.sa_family == AF_UNIX) {
  2752. /* TODO: Define a remote address for unix domain sockets.
  2753. * This code will always return "localhost", identical to http+tcp:
  2754. getnameinfo(&usa->sa,
  2755. sizeof(usa->sun),
  2756. buf,
  2757. (unsigned)len,
  2758. NULL,
  2759. 0,
  2760. NI_NUMERICHOST);
  2761. */
  2762. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2763. buf[len] = 0;
  2764. }
  2765. #endif
  2766. }
  2767. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2768. * included in all responses other than 100, 101, 5xx. */
  2769. static void
  2770. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2771. {
  2772. #if !defined(REENTRANT_TIME)
  2773. struct tm *tm;
  2774. tm = ((t != NULL) ? gmtime(t) : NULL);
  2775. if (tm != NULL) {
  2776. #else
  2777. struct tm _tm;
  2778. struct tm *tm = &_tm;
  2779. if (t != NULL) {
  2780. gmtime_r(t, tm);
  2781. #endif
  2782. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2783. } else {
  2784. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2785. buf[buf_len - 1] = '\0';
  2786. }
  2787. }
  2788. /* difftime for struct timespec. Return value is in seconds. */
  2789. static double
  2790. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2791. {
  2792. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2793. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2794. }
  2795. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2796. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2797. const char *func,
  2798. unsigned line,
  2799. const char *fmt,
  2800. va_list ap);
  2801. #include "external_mg_cry_internal_impl.inl"
  2802. #elif !defined(NO_FILESYSTEMS)
  2803. /* Print error message to the opened error log stream. */
  2804. static void
  2805. mg_cry_internal_impl(const struct mg_connection *conn,
  2806. const char *func,
  2807. unsigned line,
  2808. const char *fmt,
  2809. va_list ap)
  2810. {
  2811. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2812. struct mg_file fi;
  2813. time_t timestamp;
  2814. /* Unused, in the RELEASE build */
  2815. (void)func;
  2816. (void)line;
  2817. #if defined(GCC_DIAGNOSTIC)
  2818. #pragma GCC diagnostic push
  2819. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2820. #endif
  2821. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2822. #if defined(GCC_DIAGNOSTIC)
  2823. #pragma GCC diagnostic pop
  2824. #endif
  2825. buf[sizeof(buf) - 1] = 0;
  2826. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2827. if (!conn) {
  2828. puts(buf);
  2829. return;
  2830. }
  2831. /* Do not lock when getting the callback value, here and below.
  2832. * I suppose this is fine, since function cannot disappear in the
  2833. * same way string option can. */
  2834. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2835. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2836. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2837. if (mg_fopen(conn,
  2838. conn->dom_ctx->config[ERROR_LOG_FILE],
  2839. MG_FOPEN_MODE_APPEND,
  2840. &fi)
  2841. == 0) {
  2842. fi.access.fp = NULL;
  2843. }
  2844. } else {
  2845. fi.access.fp = NULL;
  2846. }
  2847. if (fi.access.fp != NULL) {
  2848. flockfile(fi.access.fp);
  2849. timestamp = time(NULL);
  2850. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2851. fprintf(fi.access.fp,
  2852. "[%010lu] [error] [client %s] ",
  2853. (unsigned long)timestamp,
  2854. src_addr);
  2855. if (conn->request_info.request_method != NULL) {
  2856. fprintf(fi.access.fp,
  2857. "%s %s: ",
  2858. conn->request_info.request_method,
  2859. conn->request_info.request_uri
  2860. ? conn->request_info.request_uri
  2861. : "");
  2862. }
  2863. fprintf(fi.access.fp, "%s", buf);
  2864. fputc('\n', fi.access.fp);
  2865. fflush(fi.access.fp);
  2866. funlockfile(fi.access.fp);
  2867. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2868. * mg_cry here anyway ;-) */
  2869. }
  2870. }
  2871. }
  2872. #else
  2873. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2874. #endif /* Externally provided function */
  2875. /* Construct fake connection structure. Used for logging, if connection
  2876. * is not applicable at the moment of logging. */
  2877. static struct mg_connection *
  2878. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2879. {
  2880. static const struct mg_connection conn_zero = {0};
  2881. *fc = conn_zero;
  2882. fc->phys_ctx = ctx;
  2883. fc->dom_ctx = &(ctx->dd);
  2884. return fc;
  2885. }
  2886. static void
  2887. mg_cry_internal_wrap(const struct mg_connection *conn,
  2888. struct mg_context *ctx,
  2889. const char *func,
  2890. unsigned line,
  2891. const char *fmt,
  2892. ...)
  2893. {
  2894. va_list ap;
  2895. va_start(ap, fmt);
  2896. if (!conn && ctx) {
  2897. struct mg_connection fc;
  2898. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2899. } else {
  2900. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2901. }
  2902. va_end(ap);
  2903. }
  2904. void
  2905. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2906. {
  2907. va_list ap;
  2908. va_start(ap, fmt);
  2909. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2910. va_end(ap);
  2911. }
  2912. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2913. const char *
  2914. mg_version(void)
  2915. {
  2916. return CIVETWEB_VERSION;
  2917. }
  2918. const struct mg_request_info *
  2919. mg_get_request_info(const struct mg_connection *conn)
  2920. {
  2921. if (!conn) {
  2922. return NULL;
  2923. }
  2924. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2925. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2926. char txt[16];
  2927. struct mg_workerTLS *tls =
  2928. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2929. sprintf(txt, "%03i", conn->response_info.status_code);
  2930. if (strlen(txt) == 3) {
  2931. memcpy(tls->txtbuf, txt, 4);
  2932. } else {
  2933. strcpy(tls->txtbuf, "ERR");
  2934. }
  2935. ((struct mg_connection *)conn)->request_info.local_uri =
  2936. tls->txtbuf; /* use thread safe buffer */
  2937. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2938. tls->txtbuf; /* use the same thread safe buffer */
  2939. ((struct mg_connection *)conn)->request_info.request_uri =
  2940. tls->txtbuf; /* use the same thread safe buffer */
  2941. ((struct mg_connection *)conn)->request_info.num_headers =
  2942. conn->response_info.num_headers;
  2943. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2944. conn->response_info.http_headers,
  2945. sizeof(conn->response_info.http_headers));
  2946. } else
  2947. #endif
  2948. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2949. return NULL;
  2950. }
  2951. return &conn->request_info;
  2952. }
  2953. const struct mg_response_info *
  2954. mg_get_response_info(const struct mg_connection *conn)
  2955. {
  2956. if (!conn) {
  2957. return NULL;
  2958. }
  2959. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2960. return NULL;
  2961. }
  2962. return &conn->response_info;
  2963. }
  2964. static const char *
  2965. get_proto_name(const struct mg_connection *conn)
  2966. {
  2967. #if defined(__clang__)
  2968. #pragma clang diagnostic push
  2969. #pragma clang diagnostic ignored "-Wunreachable-code"
  2970. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2971. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2972. * unreachable, but splitting into four different #ifdef clauses here is
  2973. * more complicated.
  2974. */
  2975. #endif
  2976. const struct mg_request_info *ri = &conn->request_info;
  2977. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2978. ? (ri->is_ssl ? "wss" : "ws")
  2979. : (ri->is_ssl ? "https" : "http"));
  2980. return proto;
  2981. #if defined(__clang__)
  2982. #pragma clang diagnostic pop
  2983. #endif
  2984. }
  2985. static int
  2986. mg_construct_local_link(const struct mg_connection *conn,
  2987. char *buf,
  2988. size_t buflen,
  2989. const char *define_proto,
  2990. int define_port,
  2991. const char *define_uri)
  2992. {
  2993. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2994. return -1;
  2995. } else {
  2996. int truncated = 0;
  2997. const struct mg_request_info *ri = &conn->request_info;
  2998. const char *proto =
  2999. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3000. const char *uri =
  3001. (define_uri != NULL)
  3002. ? define_uri
  3003. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3004. int port = (define_port > 0) ? define_port : ri->server_port;
  3005. int default_port = 80;
  3006. if (uri == NULL) {
  3007. return -1;
  3008. }
  3009. #if defined(USE_X_DOM_SOCKET)
  3010. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3011. /* TODO: Define and document a link for UNIX domain sockets. */
  3012. /* There seems to be no official standard for this.
  3013. * Common uses seem to be "httpunix://", "http.unix://" or
  3014. * "http+unix://" as a protocol definition string, followed by
  3015. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3016. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3017. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3018. * "" (completely skipping the server name part). In any case, the
  3019. * last part is the server local path. */
  3020. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3021. mg_snprintf(conn,
  3022. &truncated,
  3023. buf,
  3024. buflen,
  3025. "%s.unix://%s%s",
  3026. proto,
  3027. server_name,
  3028. ri->local_uri);
  3029. default_port = 0;
  3030. return 0;
  3031. }
  3032. #endif
  3033. if (define_proto) {
  3034. /* If we got a protocol name, use the default port accordingly. */
  3035. if ((0 == strcmp(define_proto, "https"))
  3036. || (0 == strcmp(define_proto, "wss"))) {
  3037. default_port = 443;
  3038. }
  3039. } else if (ri->is_ssl) {
  3040. /* If we did not get a protocol name, use TLS as default if it is
  3041. * already used. */
  3042. default_port = 443;
  3043. }
  3044. {
  3045. #if defined(USE_IPV6)
  3046. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3047. #endif
  3048. int auth_domain_check_enabled =
  3049. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3050. && (!mg_strcasecmp(
  3051. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3052. const char *server_domain =
  3053. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3054. char portstr[16];
  3055. char server_ip[48];
  3056. if (port != default_port) {
  3057. sprintf(portstr, ":%u", (unsigned)port);
  3058. } else {
  3059. portstr[0] = 0;
  3060. }
  3061. if (!auth_domain_check_enabled || !server_domain) {
  3062. sockaddr_to_string(server_ip,
  3063. sizeof(server_ip),
  3064. &conn->client.lsa);
  3065. server_domain = server_ip;
  3066. }
  3067. mg_snprintf(conn,
  3068. &truncated,
  3069. buf,
  3070. buflen,
  3071. #if defined(USE_IPV6)
  3072. "%s://%s%s%s%s%s",
  3073. proto,
  3074. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3075. server_domain,
  3076. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3077. #else
  3078. "%s://%s%s%s",
  3079. proto,
  3080. server_domain,
  3081. #endif
  3082. portstr,
  3083. ri->local_uri);
  3084. if (truncated) {
  3085. return -1;
  3086. }
  3087. return 0;
  3088. }
  3089. }
  3090. }
  3091. int
  3092. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3093. {
  3094. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3095. }
  3096. /* Skip the characters until one of the delimiters characters found.
  3097. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3098. * Advance pointer to buffer to the next word. Return found 0-terminated
  3099. * word.
  3100. * Delimiters can be quoted with quotechar. */
  3101. static char *
  3102. skip_quoted(char **buf,
  3103. const char *delimiters,
  3104. const char *whitespace,
  3105. char quotechar)
  3106. {
  3107. char *p, *begin_word, *end_word, *end_whitespace;
  3108. begin_word = *buf;
  3109. end_word = begin_word + strcspn(begin_word, delimiters);
  3110. /* Check for quotechar */
  3111. if (end_word > begin_word) {
  3112. p = end_word - 1;
  3113. while (*p == quotechar) {
  3114. /* While the delimiter is quoted, look for the next delimiter.
  3115. */
  3116. /* This happens, e.g., in calls from parse_auth_header,
  3117. * if the user name contains a " character. */
  3118. /* If there is anything beyond end_word, copy it. */
  3119. if (*end_word != '\0') {
  3120. size_t end_off = strcspn(end_word + 1, delimiters);
  3121. memmove(p, end_word, end_off + 1);
  3122. p += end_off; /* p must correspond to end_word - 1 */
  3123. end_word += end_off + 1;
  3124. } else {
  3125. *p = '\0';
  3126. break;
  3127. }
  3128. }
  3129. for (p++; p < end_word; p++) {
  3130. *p = '\0';
  3131. }
  3132. }
  3133. if (*end_word == '\0') {
  3134. *buf = end_word;
  3135. } else {
  3136. #if defined(GCC_DIAGNOSTIC)
  3137. /* Disable spurious conversion warning for GCC */
  3138. #pragma GCC diagnostic push
  3139. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3140. #endif /* defined(GCC_DIAGNOSTIC) */
  3141. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3142. #if defined(GCC_DIAGNOSTIC)
  3143. #pragma GCC diagnostic pop
  3144. #endif /* defined(GCC_DIAGNOSTIC) */
  3145. for (p = end_word; p < end_whitespace; p++) {
  3146. *p = '\0';
  3147. }
  3148. *buf = end_whitespace;
  3149. }
  3150. return begin_word;
  3151. }
  3152. /* Return HTTP header value, or NULL if not found. */
  3153. static const char *
  3154. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3155. {
  3156. int i;
  3157. for (i = 0; i < num_hdr; i++) {
  3158. if (!mg_strcasecmp(name, hdr[i].name)) {
  3159. return hdr[i].value;
  3160. }
  3161. }
  3162. return NULL;
  3163. }
  3164. #if defined(USE_WEBSOCKET)
  3165. /* Retrieve requested HTTP header multiple values, and return the number of
  3166. * found occurrences */
  3167. static int
  3168. get_req_headers(const struct mg_request_info *ri,
  3169. const char *name,
  3170. const char **output,
  3171. int output_max_size)
  3172. {
  3173. int i;
  3174. int cnt = 0;
  3175. if (ri) {
  3176. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3177. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3178. output[cnt++] = ri->http_headers[i].value;
  3179. }
  3180. }
  3181. }
  3182. return cnt;
  3183. }
  3184. #endif
  3185. const char *
  3186. mg_get_header(const struct mg_connection *conn, const char *name)
  3187. {
  3188. if (!conn) {
  3189. return NULL;
  3190. }
  3191. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3192. return get_header(conn->request_info.http_headers,
  3193. conn->request_info.num_headers,
  3194. name);
  3195. }
  3196. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3197. return get_header(conn->response_info.http_headers,
  3198. conn->response_info.num_headers,
  3199. name);
  3200. }
  3201. return NULL;
  3202. }
  3203. static const char *
  3204. get_http_version(const struct mg_connection *conn)
  3205. {
  3206. if (!conn) {
  3207. return NULL;
  3208. }
  3209. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3210. return conn->request_info.http_version;
  3211. }
  3212. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3213. return conn->response_info.http_version;
  3214. }
  3215. return NULL;
  3216. }
  3217. /* A helper function for traversing a comma separated list of values.
  3218. * It returns a list pointer shifted to the next value, or NULL if the end
  3219. * of the list found.
  3220. * Value is stored in val vector. If value has form "x=y", then eq_val
  3221. * vector is initialized to point to the "y" part, and val vector length
  3222. * is adjusted to point only to "x". */
  3223. static const char *
  3224. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3225. {
  3226. int end;
  3227. reparse:
  3228. if (val == NULL || list == NULL || *list == '\0') {
  3229. /* End of the list */
  3230. return NULL;
  3231. }
  3232. /* Skip over leading LWS */
  3233. while (*list == ' ' || *list == '\t')
  3234. list++;
  3235. val->ptr = list;
  3236. if ((list = strchr(val->ptr, ',')) != NULL) {
  3237. /* Comma found. Store length and shift the list ptr */
  3238. val->len = ((size_t)(list - val->ptr));
  3239. list++;
  3240. } else {
  3241. /* This value is the last one */
  3242. list = val->ptr + strlen(val->ptr);
  3243. val->len = ((size_t)(list - val->ptr));
  3244. }
  3245. /* Adjust length for trailing LWS */
  3246. end = (int)val->len - 1;
  3247. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3248. end--;
  3249. val->len = (size_t)(end) + (size_t)(1);
  3250. if (val->len == 0) {
  3251. /* Ignore any empty entries. */
  3252. goto reparse;
  3253. }
  3254. if (eq_val != NULL) {
  3255. /* Value has form "x=y", adjust pointers and lengths
  3256. * so that val points to "x", and eq_val points to "y". */
  3257. eq_val->len = 0;
  3258. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3259. if (eq_val->ptr != NULL) {
  3260. eq_val->ptr++; /* Skip over '=' character */
  3261. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3262. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3263. }
  3264. }
  3265. return list;
  3266. }
  3267. /* A helper function for checking if a comma separated list of values
  3268. * contains
  3269. * the given option (case insensitvely).
  3270. * 'header' can be NULL, in which case false is returned. */
  3271. static int
  3272. header_has_option(const char *header, const char *option)
  3273. {
  3274. struct vec opt_vec;
  3275. struct vec eq_vec;
  3276. DEBUG_ASSERT(option != NULL);
  3277. DEBUG_ASSERT(option[0] != '\0');
  3278. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3279. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3280. return 1;
  3281. }
  3282. return 0;
  3283. }
  3284. /* Perform case-insensitive match of string against pattern */
  3285. static ptrdiff_t
  3286. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3287. {
  3288. const char *or_str;
  3289. ptrdiff_t i, j, len, res;
  3290. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3291. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3292. return (res > 0) ? res
  3293. : match_prefix(or_str + 1,
  3294. (size_t)((pattern + pattern_len)
  3295. - (or_str + 1)),
  3296. str);
  3297. }
  3298. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3299. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3300. continue;
  3301. } else if (pattern[i] == '$') {
  3302. return (str[j] == '\0') ? j : -1;
  3303. } else if (pattern[i] == '*') {
  3304. i++;
  3305. if (pattern[i] == '*') {
  3306. i++;
  3307. len = (ptrdiff_t)strlen(str + j);
  3308. } else {
  3309. len = (ptrdiff_t)strcspn(str + j, "/");
  3310. }
  3311. if (i == (ptrdiff_t)pattern_len) {
  3312. return j + len;
  3313. }
  3314. do {
  3315. res = match_prefix(pattern + i,
  3316. (pattern_len - (size_t)i),
  3317. str + j + len);
  3318. } while (res == -1 && len-- > 0);
  3319. return (res == -1) ? -1 : j + res + len;
  3320. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3321. return -1;
  3322. }
  3323. }
  3324. return (ptrdiff_t)j;
  3325. }
  3326. static ptrdiff_t
  3327. match_prefix_strlen(const char *pattern, const char *str)
  3328. {
  3329. if (pattern == NULL) {
  3330. return -1;
  3331. }
  3332. return match_prefix(pattern, strlen(pattern), str);
  3333. }
  3334. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3335. * This function must tolerate situations when connection info is not
  3336. * set up, for example if request parsing failed. */
  3337. static int
  3338. should_keep_alive(const struct mg_connection *conn)
  3339. {
  3340. const char *http_version;
  3341. const char *header;
  3342. /* First satisfy needs of the server */
  3343. if ((conn == NULL) || conn->must_close) {
  3344. /* Close, if civetweb framework needs to close */
  3345. return 0;
  3346. }
  3347. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3348. /* Close, if keep alive is not enabled */
  3349. return 0;
  3350. }
  3351. /* Check explicit wish of the client */
  3352. header = mg_get_header(conn, "Connection");
  3353. if (header) {
  3354. /* If there is a connection header from the client, obey */
  3355. if (header_has_option(header, "keep-alive")) {
  3356. return 1;
  3357. }
  3358. return 0;
  3359. }
  3360. /* Use default of the standard */
  3361. http_version = get_http_version(conn);
  3362. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3363. /* HTTP 1.1 default is keep alive */
  3364. return 1;
  3365. }
  3366. /* HTTP 1.0 (and earlier) default is to close the connection */
  3367. return 0;
  3368. }
  3369. static int
  3370. should_decode_url(const struct mg_connection *conn)
  3371. {
  3372. if (!conn || !conn->dom_ctx) {
  3373. return 0;
  3374. }
  3375. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3376. }
  3377. static int
  3378. should_decode_query_string(const struct mg_connection *conn)
  3379. {
  3380. if (!conn || !conn->dom_ctx) {
  3381. return 0;
  3382. }
  3383. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3384. == 0);
  3385. }
  3386. static const char *
  3387. suggest_connection_header(const struct mg_connection *conn)
  3388. {
  3389. return should_keep_alive(conn) ? "keep-alive" : "close";
  3390. }
  3391. #include "response.inl"
  3392. static void
  3393. send_no_cache_header(struct mg_connection *conn)
  3394. {
  3395. /* Send all current and obsolete cache opt-out directives. */
  3396. mg_response_header_add(conn,
  3397. "Cache-Control",
  3398. "no-cache, no-store, "
  3399. "must-revalidate, private, max-age=0",
  3400. -1);
  3401. mg_response_header_add(conn, "Expires", "0", -1);
  3402. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3403. /* Obsolete, but still send it for HTTP/1.0 */
  3404. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3405. }
  3406. }
  3407. static void
  3408. send_static_cache_header(struct mg_connection *conn)
  3409. {
  3410. #if !defined(NO_CACHING)
  3411. int max_age;
  3412. char val[64];
  3413. const char *cache_control =
  3414. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3415. /* If there is a full cache-control option configured,0 use it */
  3416. if (cache_control != NULL) {
  3417. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3418. return;
  3419. }
  3420. /* Read the server config to check how long a file may be cached.
  3421. * The configuration is in seconds. */
  3422. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3423. if (max_age <= 0) {
  3424. /* 0 means "do not cache". All values <0 are reserved
  3425. * and may be used differently in the future. */
  3426. /* If a file should not be cached, do not only send
  3427. * max-age=0, but also pragmas and Expires headers. */
  3428. send_no_cache_header(conn);
  3429. return;
  3430. }
  3431. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3432. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3433. /* See also https://www.mnot.net/cache_docs/ */
  3434. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3435. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3436. * leap
  3437. * year to 31622400 seconds. For the moment, we just send whatever has
  3438. * been configured, still the behavior for >1 year should be considered
  3439. * as undefined. */
  3440. mg_snprintf(
  3441. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3442. mg_response_header_add(conn, "Cache-Control", val, -1);
  3443. #else /* NO_CACHING */
  3444. send_no_cache_header(conn);
  3445. #endif /* !NO_CACHING */
  3446. }
  3447. static void
  3448. send_additional_header(struct mg_connection *conn)
  3449. {
  3450. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3451. #if !defined(NO_SSL)
  3452. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3453. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3454. if (max_age >= 0) {
  3455. char val[64];
  3456. mg_snprintf(conn,
  3457. NULL,
  3458. val,
  3459. sizeof(val),
  3460. "max-age=%lu",
  3461. (unsigned long)max_age);
  3462. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3463. }
  3464. }
  3465. #endif
  3466. if (header && header[0]) {
  3467. mg_response_header_add_lines(conn, header);
  3468. }
  3469. }
  3470. #if !defined(NO_FILESYSTEMS)
  3471. static void handle_file_based_request(struct mg_connection *conn,
  3472. const char *path,
  3473. struct mg_file *filep);
  3474. #endif /* NO_FILESYSTEMS */
  3475. const char *
  3476. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3477. {
  3478. /* See IANA HTTP status code assignment:
  3479. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3480. */
  3481. switch (response_code) {
  3482. /* RFC2616 Section 10.1 - Informational 1xx */
  3483. case 100:
  3484. return "Continue"; /* RFC2616 Section 10.1.1 */
  3485. case 101:
  3486. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3487. case 102:
  3488. return "Processing"; /* RFC2518 Section 10.1 */
  3489. /* RFC2616 Section 10.2 - Successful 2xx */
  3490. case 200:
  3491. return "OK"; /* RFC2616 Section 10.2.1 */
  3492. case 201:
  3493. return "Created"; /* RFC2616 Section 10.2.2 */
  3494. case 202:
  3495. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3496. case 203:
  3497. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3498. case 204:
  3499. return "No Content"; /* RFC2616 Section 10.2.5 */
  3500. case 205:
  3501. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3502. case 206:
  3503. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3504. case 207:
  3505. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3506. */
  3507. case 208:
  3508. return "Already Reported"; /* RFC5842 Section 7.1 */
  3509. case 226:
  3510. return "IM used"; /* RFC3229 Section 10.4.1 */
  3511. /* RFC2616 Section 10.3 - Redirection 3xx */
  3512. case 300:
  3513. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3514. case 301:
  3515. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3516. case 302:
  3517. return "Found"; /* RFC2616 Section 10.3.3 */
  3518. case 303:
  3519. return "See Other"; /* RFC2616 Section 10.3.4 */
  3520. case 304:
  3521. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3522. case 305:
  3523. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3524. case 307:
  3525. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3526. case 308:
  3527. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3528. /* RFC2616 Section 10.4 - Client Error 4xx */
  3529. case 400:
  3530. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3531. case 401:
  3532. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3533. case 402:
  3534. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3535. case 403:
  3536. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3537. case 404:
  3538. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3539. case 405:
  3540. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3541. case 406:
  3542. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3543. case 407:
  3544. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3545. case 408:
  3546. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3547. case 409:
  3548. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3549. case 410:
  3550. return "Gone"; /* RFC2616 Section 10.4.11 */
  3551. case 411:
  3552. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3553. case 412:
  3554. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3555. case 413:
  3556. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3557. case 414:
  3558. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3559. case 415:
  3560. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3561. case 416:
  3562. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3563. */
  3564. case 417:
  3565. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3566. case 421:
  3567. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3568. case 422:
  3569. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3570. * Section 11.2 */
  3571. case 423:
  3572. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3573. case 424:
  3574. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3575. * Section 11.4 */
  3576. case 426:
  3577. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3578. case 428:
  3579. return "Precondition Required"; /* RFC 6585, Section 3 */
  3580. case 429:
  3581. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3582. case 431:
  3583. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3584. case 451:
  3585. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3586. * Section 3 */
  3587. /* RFC2616 Section 10.5 - Server Error 5xx */
  3588. case 500:
  3589. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3590. case 501:
  3591. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3592. case 502:
  3593. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3594. case 503:
  3595. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3596. case 504:
  3597. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3598. case 505:
  3599. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3600. case 506:
  3601. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3602. case 507:
  3603. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3604. * Section 11.5 */
  3605. case 508:
  3606. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3607. case 510:
  3608. return "Not Extended"; /* RFC 2774, Section 7 */
  3609. case 511:
  3610. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3611. /* Other status codes, not shown in the IANA HTTP status code
  3612. * assignment.
  3613. * E.g., "de facto" standards due to common use, ... */
  3614. case 418:
  3615. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3616. case 419:
  3617. return "Authentication Timeout"; /* common use */
  3618. case 420:
  3619. return "Enhance Your Calm"; /* common use */
  3620. case 440:
  3621. return "Login Timeout"; /* common use */
  3622. case 509:
  3623. return "Bandwidth Limit Exceeded"; /* common use */
  3624. default:
  3625. /* This error code is unknown. This should not happen. */
  3626. if (conn) {
  3627. mg_cry_internal(conn,
  3628. "Unknown HTTP response code: %u",
  3629. response_code);
  3630. }
  3631. /* Return at least a category according to RFC 2616 Section 10. */
  3632. if (response_code >= 100 && response_code < 200) {
  3633. /* Unknown informational status code */
  3634. return "Information";
  3635. }
  3636. if (response_code >= 200 && response_code < 300) {
  3637. /* Unknown success code */
  3638. return "Success";
  3639. }
  3640. if (response_code >= 300 && response_code < 400) {
  3641. /* Unknown redirection code */
  3642. return "Redirection";
  3643. }
  3644. if (response_code >= 400 && response_code < 500) {
  3645. /* Unknown request error code */
  3646. return "Client Error";
  3647. }
  3648. if (response_code >= 500 && response_code < 600) {
  3649. /* Unknown server error code */
  3650. return "Server Error";
  3651. }
  3652. /* Response code not even within reasonable range */
  3653. return "";
  3654. }
  3655. }
  3656. static int
  3657. mg_send_http_error_impl(struct mg_connection *conn,
  3658. int status,
  3659. const char *fmt,
  3660. va_list args)
  3661. {
  3662. char errmsg_buf[MG_BUF_LEN];
  3663. va_list ap;
  3664. int has_body;
  3665. #if !defined(NO_FILESYSTEMS)
  3666. char path_buf[UTF8_PATH_MAX];
  3667. int len, i, page_handler_found, scope, truncated;
  3668. const char *error_handler = NULL;
  3669. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3670. const char *error_page_file_ext, *tstr;
  3671. #endif /* NO_FILESYSTEMS */
  3672. int handled_by_callback = 0;
  3673. if ((conn == NULL) || (fmt == NULL)) {
  3674. return -2;
  3675. }
  3676. /* Set status (for log) */
  3677. conn->status_code = status;
  3678. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3679. has_body = ((status > 199) && (status != 204) && (status != 304));
  3680. /* Prepare message in buf, if required */
  3681. if (has_body
  3682. || (!conn->in_error_handler
  3683. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3684. /* Store error message in errmsg_buf */
  3685. va_copy(ap, args);
  3686. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3687. va_end(ap);
  3688. /* In a debug build, print all html errors */
  3689. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3690. }
  3691. /* If there is a http_error callback, call it.
  3692. * But don't do it recursively, if callback calls mg_send_http_error again.
  3693. */
  3694. if (!conn->in_error_handler
  3695. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3696. /* Mark in_error_handler to avoid recursion and call user callback. */
  3697. conn->in_error_handler = 1;
  3698. handled_by_callback =
  3699. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3700. == 0);
  3701. conn->in_error_handler = 0;
  3702. }
  3703. if (!handled_by_callback) {
  3704. /* Check for recursion */
  3705. if (conn->in_error_handler) {
  3706. DEBUG_TRACE(
  3707. "Recursion when handling error %u - fall back to default",
  3708. status);
  3709. #if !defined(NO_FILESYSTEMS)
  3710. } else {
  3711. /* Send user defined error pages, if defined */
  3712. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3713. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3714. page_handler_found = 0;
  3715. if (error_handler != NULL) {
  3716. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3717. switch (scope) {
  3718. case 1: /* Handler for specific error, e.g. 404 error */
  3719. mg_snprintf(conn,
  3720. &truncated,
  3721. path_buf,
  3722. sizeof(path_buf) - 32,
  3723. "%serror%03u.",
  3724. error_handler,
  3725. status);
  3726. break;
  3727. case 2: /* Handler for error group, e.g., 5xx error
  3728. * handler
  3729. * for all server errors (500-599) */
  3730. mg_snprintf(conn,
  3731. &truncated,
  3732. path_buf,
  3733. sizeof(path_buf) - 32,
  3734. "%serror%01uxx.",
  3735. error_handler,
  3736. status / 100);
  3737. break;
  3738. default: /* Handler for all errors */
  3739. mg_snprintf(conn,
  3740. &truncated,
  3741. path_buf,
  3742. sizeof(path_buf) - 32,
  3743. "%serror.",
  3744. error_handler);
  3745. break;
  3746. }
  3747. /* String truncation in buf may only occur if
  3748. * error_handler is too long. This string is
  3749. * from the config, not from a client. */
  3750. (void)truncated;
  3751. /* The following code is redundant, but it should avoid
  3752. * false positives in static source code analyzers and
  3753. * vulnerability scanners.
  3754. */
  3755. path_buf[sizeof(path_buf) - 32] = 0;
  3756. len = (int)strlen(path_buf);
  3757. if (len > (int)sizeof(path_buf) - 32) {
  3758. len = (int)sizeof(path_buf) - 32;
  3759. }
  3760. /* Start with the file extenstion from the configuration. */
  3761. tstr = strchr(error_page_file_ext, '.');
  3762. while (tstr) {
  3763. for (i = 1;
  3764. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3765. i++) {
  3766. /* buffer overrun is not possible here, since
  3767. * (i < 32) && (len < sizeof(path_buf) - 32)
  3768. * ==> (i + len) < sizeof(path_buf) */
  3769. path_buf[len + i - 1] = tstr[i];
  3770. }
  3771. /* buffer overrun is not possible here, since
  3772. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3773. * ==> (i + len) <= sizeof(path_buf) */
  3774. path_buf[len + i - 1] = 0;
  3775. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3776. DEBUG_TRACE("Check error page %s - found",
  3777. path_buf);
  3778. page_handler_found = 1;
  3779. break;
  3780. }
  3781. DEBUG_TRACE("Check error page %s - not found",
  3782. path_buf);
  3783. /* Continue with the next file extenstion from the
  3784. * configuration (if there is a next one). */
  3785. tstr = strchr(tstr + i, '.');
  3786. }
  3787. }
  3788. }
  3789. if (page_handler_found) {
  3790. conn->in_error_handler = 1;
  3791. handle_file_based_request(conn, path_buf, &error_page_file);
  3792. conn->in_error_handler = 0;
  3793. return 0;
  3794. }
  3795. #endif /* NO_FILESYSTEMS */
  3796. }
  3797. /* No custom error page. Send default error page. */
  3798. conn->must_close = 1;
  3799. mg_response_header_start(conn, status);
  3800. send_no_cache_header(conn);
  3801. send_additional_header(conn);
  3802. if (has_body) {
  3803. mg_response_header_add(conn,
  3804. "Content-Type",
  3805. "text/plain; charset=utf-8",
  3806. -1);
  3807. }
  3808. mg_response_header_send(conn);
  3809. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3810. if (has_body) {
  3811. /* For other errors, send a generic error message. */
  3812. const char *status_text = mg_get_response_code_text(conn, status);
  3813. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3814. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3815. } else {
  3816. /* No body allowed. Close the connection. */
  3817. DEBUG_TRACE("Error %i", status);
  3818. }
  3819. }
  3820. return 0;
  3821. }
  3822. int
  3823. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3824. {
  3825. va_list ap;
  3826. int ret;
  3827. va_start(ap, fmt);
  3828. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3829. va_end(ap);
  3830. return ret;
  3831. }
  3832. int
  3833. mg_send_http_ok(struct mg_connection *conn,
  3834. const char *mime_type,
  3835. long long content_length)
  3836. {
  3837. if ((mime_type == NULL) || (*mime_type == 0)) {
  3838. /* No content type defined: default to text/html */
  3839. mime_type = "text/html";
  3840. }
  3841. mg_response_header_start(conn, 200);
  3842. send_no_cache_header(conn);
  3843. send_additional_header(conn);
  3844. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3845. if (content_length < 0) {
  3846. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3847. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3848. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3849. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3850. }
  3851. } else {
  3852. char len[32];
  3853. int trunc = 0;
  3854. mg_snprintf(conn,
  3855. &trunc,
  3856. len,
  3857. sizeof(len),
  3858. "%" UINT64_FMT,
  3859. (uint64_t)content_length);
  3860. if (!trunc) {
  3861. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3862. * !trunc is always true */
  3863. mg_response_header_add(conn, "Content-Length", len, -1);
  3864. }
  3865. }
  3866. mg_response_header_send(conn);
  3867. return 0;
  3868. }
  3869. int
  3870. mg_send_http_redirect(struct mg_connection *conn,
  3871. const char *target_url,
  3872. int redirect_code)
  3873. {
  3874. /* Send a 30x redirect response.
  3875. *
  3876. * Redirect types (status codes):
  3877. *
  3878. * Status | Perm/Temp | Method | Version
  3879. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3880. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3881. * 303 | temporary | always use GET | HTTP/1.1
  3882. * 307 | temporary | always keep method | HTTP/1.1
  3883. * 308 | permanent | always keep method | HTTP/1.1
  3884. */
  3885. const char *redirect_text;
  3886. int ret;
  3887. size_t content_len = 0;
  3888. #if defined(MG_SEND_REDIRECT_BODY)
  3889. char reply[MG_BUF_LEN];
  3890. #endif
  3891. /* In case redirect_code=0, use 307. */
  3892. if (redirect_code == 0) {
  3893. redirect_code = 307;
  3894. }
  3895. /* In case redirect_code is none of the above, return error. */
  3896. if ((redirect_code != 301) && (redirect_code != 302)
  3897. && (redirect_code != 303) && (redirect_code != 307)
  3898. && (redirect_code != 308)) {
  3899. /* Parameter error */
  3900. return -2;
  3901. }
  3902. /* Get proper text for response code */
  3903. redirect_text = mg_get_response_code_text(conn, redirect_code);
  3904. /* If target_url is not defined, redirect to "/". */
  3905. if ((target_url == NULL) || (*target_url == 0)) {
  3906. target_url = "/";
  3907. }
  3908. #if defined(MG_SEND_REDIRECT_BODY)
  3909. /* TODO: condition name? */
  3910. /* Prepare a response body with a hyperlink.
  3911. *
  3912. * According to RFC2616 (and RFC1945 before):
  3913. * Unless the request method was HEAD, the entity of the
  3914. * response SHOULD contain a short hypertext note with a hyperlink to
  3915. * the new URI(s).
  3916. *
  3917. * However, this response body is not useful in M2M communication.
  3918. * Probably the original reason in the RFC was, clients not supporting
  3919. * a 30x HTTP redirect could still show the HTML page and let the user
  3920. * press the link. Since current browsers support 30x HTTP, the additional
  3921. * HTML body does not seem to make sense anymore.
  3922. *
  3923. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3924. * but it only notes:
  3925. * The server's response payload usually contains a short
  3926. * hypertext note with a hyperlink to the new URI(s).
  3927. *
  3928. * Deactivated by default. If you need the 30x body, set the define.
  3929. */
  3930. mg_snprintf(
  3931. conn,
  3932. NULL /* ignore truncation */,
  3933. reply,
  3934. sizeof(reply),
  3935. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3936. redirect_text,
  3937. target_url,
  3938. target_url);
  3939. content_len = strlen(reply);
  3940. #endif
  3941. /* Do not send any additional header. For all other options,
  3942. * including caching, there are suitable defaults. */
  3943. ret = mg_printf(conn,
  3944. "HTTP/1.1 %i %s\r\n"
  3945. "Location: %s\r\n"
  3946. "Content-Length: %u\r\n"
  3947. "Connection: %s\r\n\r\n",
  3948. redirect_code,
  3949. redirect_text,
  3950. target_url,
  3951. (unsigned int)content_len,
  3952. suggest_connection_header(conn));
  3953. #if defined(MG_SEND_REDIRECT_BODY)
  3954. /* Send response body */
  3955. if (ret > 0) {
  3956. /* ... unless it is a HEAD request */
  3957. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3958. ret = mg_write(conn, reply, content_len);
  3959. }
  3960. }
  3961. #endif
  3962. return (ret > 0) ? ret : -1;
  3963. }
  3964. #if defined(_WIN32)
  3965. /* Create substitutes for POSIX functions in Win32. */
  3966. #if defined(GCC_DIAGNOSTIC)
  3967. /* Show no warning in case system functions are not used. */
  3968. #pragma GCC diagnostic push
  3969. #pragma GCC diagnostic ignored "-Wunused-function"
  3970. #endif
  3971. static int
  3972. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3973. {
  3974. (void)unused;
  3975. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3976. InitializeCriticalSection(&mutex->sec);
  3977. return 0;
  3978. }
  3979. static int
  3980. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3981. {
  3982. DeleteCriticalSection(&mutex->sec);
  3983. return 0;
  3984. }
  3985. static int
  3986. pthread_mutex_lock(pthread_mutex_t *mutex)
  3987. {
  3988. EnterCriticalSection(&mutex->sec);
  3989. return 0;
  3990. }
  3991. static int
  3992. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3993. {
  3994. LeaveCriticalSection(&mutex->sec);
  3995. return 0;
  3996. }
  3997. FUNCTION_MAY_BE_UNUSED
  3998. static int
  3999. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4000. {
  4001. (void)unused;
  4002. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4003. cv->waiting_thread = NULL;
  4004. return 0;
  4005. }
  4006. FUNCTION_MAY_BE_UNUSED
  4007. static int
  4008. pthread_cond_timedwait(pthread_cond_t *cv,
  4009. pthread_mutex_t *mutex,
  4010. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4011. {
  4012. struct mg_workerTLS **ptls,
  4013. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4014. int ok;
  4015. uint64_t nsnow, nswaitabs;
  4016. int64_t nswaitrel;
  4017. DWORD mswaitrel;
  4018. pthread_mutex_lock(&cv->threadIdSec);
  4019. /* Add this thread to cv's waiting list */
  4020. ptls = &cv->waiting_thread;
  4021. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4022. ;
  4023. tls->next_waiting_thread = NULL;
  4024. *ptls = tls;
  4025. pthread_mutex_unlock(&cv->threadIdSec);
  4026. if (abstime) {
  4027. nsnow = mg_get_current_time_ns();
  4028. nswaitabs =
  4029. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4030. nswaitrel = nswaitabs - nsnow;
  4031. if (nswaitrel < 0) {
  4032. nswaitrel = 0;
  4033. }
  4034. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4035. } else {
  4036. mswaitrel = (DWORD)INFINITE;
  4037. }
  4038. pthread_mutex_unlock(mutex);
  4039. ok = (WAIT_OBJECT_0
  4040. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4041. if (!ok) {
  4042. ok = 1;
  4043. pthread_mutex_lock(&cv->threadIdSec);
  4044. ptls = &cv->waiting_thread;
  4045. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4046. if (*ptls == tls) {
  4047. *ptls = tls->next_waiting_thread;
  4048. ok = 0;
  4049. break;
  4050. }
  4051. }
  4052. pthread_mutex_unlock(&cv->threadIdSec);
  4053. if (ok) {
  4054. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4055. (DWORD)INFINITE);
  4056. }
  4057. }
  4058. /* This thread has been removed from cv's waiting list */
  4059. pthread_mutex_lock(mutex);
  4060. return ok ? 0 : -1;
  4061. }
  4062. FUNCTION_MAY_BE_UNUSED
  4063. static int
  4064. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4065. {
  4066. return pthread_cond_timedwait(cv, mutex, NULL);
  4067. }
  4068. FUNCTION_MAY_BE_UNUSED
  4069. static int
  4070. pthread_cond_signal(pthread_cond_t *cv)
  4071. {
  4072. HANDLE wkup = NULL;
  4073. BOOL ok = FALSE;
  4074. pthread_mutex_lock(&cv->threadIdSec);
  4075. if (cv->waiting_thread) {
  4076. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4077. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4078. ok = SetEvent(wkup);
  4079. DEBUG_ASSERT(ok);
  4080. }
  4081. pthread_mutex_unlock(&cv->threadIdSec);
  4082. return ok ? 0 : 1;
  4083. }
  4084. FUNCTION_MAY_BE_UNUSED
  4085. static int
  4086. pthread_cond_broadcast(pthread_cond_t *cv)
  4087. {
  4088. pthread_mutex_lock(&cv->threadIdSec);
  4089. while (cv->waiting_thread) {
  4090. pthread_cond_signal(cv);
  4091. }
  4092. pthread_mutex_unlock(&cv->threadIdSec);
  4093. return 0;
  4094. }
  4095. FUNCTION_MAY_BE_UNUSED
  4096. static int
  4097. pthread_cond_destroy(pthread_cond_t *cv)
  4098. {
  4099. pthread_mutex_lock(&cv->threadIdSec);
  4100. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4101. pthread_mutex_unlock(&cv->threadIdSec);
  4102. pthread_mutex_destroy(&cv->threadIdSec);
  4103. return 0;
  4104. }
  4105. #if defined(ALTERNATIVE_QUEUE)
  4106. FUNCTION_MAY_BE_UNUSED
  4107. static void *
  4108. event_create(void)
  4109. {
  4110. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4111. }
  4112. FUNCTION_MAY_BE_UNUSED
  4113. static int
  4114. event_wait(void *eventhdl)
  4115. {
  4116. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4117. return (res == WAIT_OBJECT_0);
  4118. }
  4119. FUNCTION_MAY_BE_UNUSED
  4120. static int
  4121. event_signal(void *eventhdl)
  4122. {
  4123. return (int)SetEvent((HANDLE)eventhdl);
  4124. }
  4125. FUNCTION_MAY_BE_UNUSED
  4126. static void
  4127. event_destroy(void *eventhdl)
  4128. {
  4129. CloseHandle((HANDLE)eventhdl);
  4130. }
  4131. #endif
  4132. #if defined(GCC_DIAGNOSTIC)
  4133. /* Enable unused function warning again */
  4134. #pragma GCC diagnostic pop
  4135. #endif
  4136. /* For Windows, change all slashes to backslashes in path names. */
  4137. static void
  4138. change_slashes_to_backslashes(char *path)
  4139. {
  4140. int i;
  4141. for (i = 0; path[i] != '\0'; i++) {
  4142. if (path[i] == '/') {
  4143. path[i] = '\\';
  4144. }
  4145. /* remove double backslash (check i > 0 to preserve UNC paths,
  4146. * like \\server\file.txt) */
  4147. if ((i > 0) && (path[i] == '\\')) {
  4148. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4149. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4150. }
  4151. }
  4152. }
  4153. }
  4154. static int
  4155. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4156. {
  4157. int diff;
  4158. do {
  4159. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4160. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4161. s1++;
  4162. s2++;
  4163. } while ((diff == 0) && (s1[-1] != L'\0'));
  4164. return diff;
  4165. }
  4166. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4167. * wbuf and wbuf_len is a target buffer and its length. */
  4168. static void
  4169. path_to_unicode(const struct mg_connection *conn,
  4170. const char *path,
  4171. wchar_t *wbuf,
  4172. size_t wbuf_len)
  4173. {
  4174. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4175. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4176. DWORD long_len, err;
  4177. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4178. mg_strlcpy(buf, path, sizeof(buf));
  4179. change_slashes_to_backslashes(buf);
  4180. /* Convert to Unicode and back. If doubly-converted string does not
  4181. * match the original, something is fishy, reject. */
  4182. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4183. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4184. WideCharToMultiByte(
  4185. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4186. if (strcmp(buf, buf2) != 0) {
  4187. wbuf[0] = L'\0';
  4188. }
  4189. /* Windows file systems are not case sensitive, but you can still use
  4190. * uppercase and lowercase letters (on all modern file systems).
  4191. * The server can check if the URI uses the same upper/lowercase
  4192. * letters an the file system, effectively making Windows servers
  4193. * case sensitive (like Linux servers are). It is still not possible
  4194. * to use two files with the same name in different cases on Windows
  4195. * (like /a and /A) - this would be possible in Linux.
  4196. * As a default, Windows is not case sensitive, but the case sensitive
  4197. * file name check can be activated by an additional configuration. */
  4198. if (conn) {
  4199. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4200. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4201. "yes")) {
  4202. /* Use case sensitive compare function */
  4203. fcompare = wcscmp;
  4204. }
  4205. }
  4206. (void)conn; /* conn is currently unused */
  4207. /* Only accept a full file path, not a Windows short (8.3) path. */
  4208. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4209. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4210. if (long_len == 0) {
  4211. err = GetLastError();
  4212. if (err == ERROR_FILE_NOT_FOUND) {
  4213. /* File does not exist. This is not always a problem here. */
  4214. return;
  4215. }
  4216. }
  4217. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4218. /* Short name is used. */
  4219. wbuf[0] = L'\0';
  4220. }
  4221. }
  4222. #if !defined(NO_FILESYSTEMS)
  4223. /* Get file information, return 1 if file exists, 0 if not */
  4224. static int
  4225. mg_stat(const struct mg_connection *conn,
  4226. const char *path,
  4227. struct mg_file_stat *filep)
  4228. {
  4229. wchar_t wbuf[UTF16_PATH_MAX];
  4230. WIN32_FILE_ATTRIBUTE_DATA info;
  4231. time_t creation_time;
  4232. size_t len;
  4233. if (!filep) {
  4234. return 0;
  4235. }
  4236. memset(filep, 0, sizeof(*filep));
  4237. if (mg_path_suspicious(conn, path)) {
  4238. return 0;
  4239. }
  4240. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4241. /* Windows happily opens files with some garbage at the end of file name.
  4242. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4243. * "a.cgi", despite one would expect an error back. */
  4244. len = strlen(path);
  4245. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4246. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4247. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4248. filep->last_modified =
  4249. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4250. info.ftLastWriteTime.dwHighDateTime);
  4251. /* On Windows, the file creation time can be higher than the
  4252. * modification time, e.g. when a file is copied.
  4253. * Since the Last-Modified timestamp is used for caching
  4254. * it should be based on the most recent timestamp. */
  4255. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4256. info.ftCreationTime.dwHighDateTime);
  4257. if (creation_time > filep->last_modified) {
  4258. filep->last_modified = creation_time;
  4259. }
  4260. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4261. return 1;
  4262. }
  4263. return 0;
  4264. }
  4265. #endif
  4266. static int
  4267. mg_remove(const struct mg_connection *conn, const char *path)
  4268. {
  4269. wchar_t wbuf[UTF16_PATH_MAX];
  4270. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4271. return DeleteFileW(wbuf) ? 0 : -1;
  4272. }
  4273. static int
  4274. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4275. {
  4276. wchar_t wbuf[UTF16_PATH_MAX];
  4277. (void)mode;
  4278. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4279. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4280. }
  4281. /* Create substitutes for POSIX functions in Win32. */
  4282. #if defined(GCC_DIAGNOSTIC)
  4283. /* Show no warning in case system functions are not used. */
  4284. #pragma GCC diagnostic push
  4285. #pragma GCC diagnostic ignored "-Wunused-function"
  4286. #endif
  4287. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4288. FUNCTION_MAY_BE_UNUSED
  4289. static DIR *
  4290. mg_opendir(const struct mg_connection *conn, const char *name)
  4291. {
  4292. DIR *dir = NULL;
  4293. wchar_t wpath[UTF16_PATH_MAX];
  4294. DWORD attrs;
  4295. if (name == NULL) {
  4296. SetLastError(ERROR_BAD_ARGUMENTS);
  4297. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4298. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4299. } else {
  4300. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4301. attrs = GetFileAttributesW(wpath);
  4302. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4303. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4304. (void)wcscat(wpath, L"\\*");
  4305. dir->handle = FindFirstFileW(wpath, &dir->info);
  4306. dir->result.d_name[0] = '\0';
  4307. } else {
  4308. mg_free(dir);
  4309. dir = NULL;
  4310. }
  4311. }
  4312. return dir;
  4313. }
  4314. FUNCTION_MAY_BE_UNUSED
  4315. static int
  4316. mg_closedir(DIR *dir)
  4317. {
  4318. int result = 0;
  4319. if (dir != NULL) {
  4320. if (dir->handle != INVALID_HANDLE_VALUE)
  4321. result = FindClose(dir->handle) ? 0 : -1;
  4322. mg_free(dir);
  4323. } else {
  4324. result = -1;
  4325. SetLastError(ERROR_BAD_ARGUMENTS);
  4326. }
  4327. return result;
  4328. }
  4329. FUNCTION_MAY_BE_UNUSED
  4330. static struct dirent *
  4331. mg_readdir(DIR *dir)
  4332. {
  4333. struct dirent *result = 0;
  4334. if (dir) {
  4335. if (dir->handle != INVALID_HANDLE_VALUE) {
  4336. result = &dir->result;
  4337. (void)WideCharToMultiByte(CP_UTF8,
  4338. 0,
  4339. dir->info.cFileName,
  4340. -1,
  4341. result->d_name,
  4342. sizeof(result->d_name),
  4343. NULL,
  4344. NULL);
  4345. if (!FindNextFileW(dir->handle, &dir->info)) {
  4346. (void)FindClose(dir->handle);
  4347. dir->handle = INVALID_HANDLE_VALUE;
  4348. }
  4349. } else {
  4350. SetLastError(ERROR_FILE_NOT_FOUND);
  4351. }
  4352. } else {
  4353. SetLastError(ERROR_BAD_ARGUMENTS);
  4354. }
  4355. return result;
  4356. }
  4357. #if !defined(HAVE_POLL)
  4358. #undef POLLIN
  4359. #undef POLLPRI
  4360. #undef POLLOUT
  4361. #undef POLLERR
  4362. #define POLLIN (1) /* Data ready - read will not block. */
  4363. #define POLLPRI (2) /* Priority data ready. */
  4364. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4365. #define POLLERR (8) /* Error event */
  4366. FUNCTION_MAY_BE_UNUSED
  4367. static int
  4368. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4369. {
  4370. struct timeval tv;
  4371. fd_set rset;
  4372. fd_set wset;
  4373. fd_set eset;
  4374. unsigned int i;
  4375. int result;
  4376. SOCKET maxfd = 0;
  4377. memset(&tv, 0, sizeof(tv));
  4378. tv.tv_sec = milliseconds / 1000;
  4379. tv.tv_usec = (milliseconds % 1000) * 1000;
  4380. FD_ZERO(&rset);
  4381. FD_ZERO(&wset);
  4382. FD_ZERO(&eset);
  4383. for (i = 0; i < n; i++) {
  4384. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4385. if (pfd[i].events & POLLIN) {
  4386. FD_SET(pfd[i].fd, &rset);
  4387. }
  4388. if (pfd[i].events & POLLOUT) {
  4389. FD_SET(pfd[i].fd, &wset);
  4390. }
  4391. /* Check for errors for any FD in the set */
  4392. FD_SET(pfd[i].fd, &eset);
  4393. }
  4394. pfd[i].revents = 0;
  4395. if (pfd[i].fd > maxfd) {
  4396. maxfd = pfd[i].fd;
  4397. }
  4398. }
  4399. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4400. for (i = 0; i < n; i++) {
  4401. if (FD_ISSET(pfd[i].fd, &rset)) {
  4402. pfd[i].revents |= POLLIN;
  4403. }
  4404. if (FD_ISSET(pfd[i].fd, &wset)) {
  4405. pfd[i].revents |= POLLOUT;
  4406. }
  4407. if (FD_ISSET(pfd[i].fd, &eset)) {
  4408. pfd[i].revents |= POLLERR;
  4409. }
  4410. }
  4411. }
  4412. /* We should subtract the time used in select from remaining
  4413. * "milliseconds", in particular if called from mg_poll with a
  4414. * timeout quantum.
  4415. * Unfortunately, the remaining time is not stored in "tv" in all
  4416. * implementations, so the result in "tv" must be considered undefined.
  4417. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4418. return result;
  4419. }
  4420. #endif /* HAVE_POLL */
  4421. #if defined(GCC_DIAGNOSTIC)
  4422. /* Enable unused function warning again */
  4423. #pragma GCC diagnostic pop
  4424. #endif
  4425. static void
  4426. set_close_on_exec(SOCKET sock,
  4427. const struct mg_connection *conn /* may be null */,
  4428. struct mg_context *ctx /* may be null */)
  4429. {
  4430. (void)conn; /* Unused. */
  4431. (void)ctx;
  4432. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4433. }
  4434. int
  4435. mg_start_thread(mg_thread_func_t f, void *p)
  4436. {
  4437. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4438. /* Compile-time option to control stack size, e.g.
  4439. * -DUSE_STACK_SIZE=16384
  4440. */
  4441. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4442. == ((uintptr_t)(-1L)))
  4443. ? -1
  4444. : 0);
  4445. #else
  4446. return (
  4447. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4448. ? -1
  4449. : 0);
  4450. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4451. }
  4452. /* Start a thread storing the thread context. */
  4453. static int
  4454. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4455. void *p,
  4456. pthread_t *threadidptr)
  4457. {
  4458. uintptr_t uip;
  4459. HANDLE threadhandle;
  4460. int result = -1;
  4461. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4462. threadhandle = (HANDLE)uip;
  4463. if ((uip != 0) && (threadidptr != NULL)) {
  4464. *threadidptr = threadhandle;
  4465. result = 0;
  4466. }
  4467. return result;
  4468. }
  4469. /* Wait for a thread to finish. */
  4470. static int
  4471. mg_join_thread(pthread_t threadid)
  4472. {
  4473. int result;
  4474. DWORD dwevent;
  4475. result = -1;
  4476. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4477. if (dwevent == WAIT_FAILED) {
  4478. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4479. } else {
  4480. if (dwevent == WAIT_OBJECT_0) {
  4481. CloseHandle(threadid);
  4482. result = 0;
  4483. }
  4484. }
  4485. return result;
  4486. }
  4487. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4488. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4489. /* Create substitutes for POSIX functions in Win32. */
  4490. #if defined(GCC_DIAGNOSTIC)
  4491. /* Show no warning in case system functions are not used. */
  4492. #pragma GCC diagnostic push
  4493. #pragma GCC diagnostic ignored "-Wunused-function"
  4494. #endif
  4495. FUNCTION_MAY_BE_UNUSED
  4496. static HANDLE
  4497. dlopen(const char *dll_name, int flags)
  4498. {
  4499. wchar_t wbuf[UTF16_PATH_MAX];
  4500. (void)flags;
  4501. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4502. return LoadLibraryW(wbuf);
  4503. }
  4504. FUNCTION_MAY_BE_UNUSED
  4505. static int
  4506. dlclose(void *handle)
  4507. {
  4508. int result;
  4509. if (FreeLibrary((HMODULE)handle) != 0) {
  4510. result = 0;
  4511. } else {
  4512. result = -1;
  4513. }
  4514. return result;
  4515. }
  4516. #if defined(GCC_DIAGNOSTIC)
  4517. /* Enable unused function warning again */
  4518. #pragma GCC diagnostic pop
  4519. #endif
  4520. #endif
  4521. #if !defined(NO_CGI)
  4522. #define SIGKILL (0)
  4523. static int
  4524. kill(pid_t pid, int sig_num)
  4525. {
  4526. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4527. (void)CloseHandle((HANDLE)pid);
  4528. return 0;
  4529. }
  4530. #if !defined(WNOHANG)
  4531. #define WNOHANG (1)
  4532. #endif
  4533. static pid_t
  4534. waitpid(pid_t pid, int *status, int flags)
  4535. {
  4536. DWORD timeout = INFINITE;
  4537. DWORD waitres;
  4538. (void)status; /* Currently not used by any client here */
  4539. if ((flags | WNOHANG) == WNOHANG) {
  4540. timeout = 0;
  4541. }
  4542. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4543. if (waitres == WAIT_OBJECT_0) {
  4544. return pid;
  4545. }
  4546. if (waitres == WAIT_TIMEOUT) {
  4547. return 0;
  4548. }
  4549. return (pid_t)-1;
  4550. }
  4551. static void
  4552. trim_trailing_whitespaces(char *s)
  4553. {
  4554. char *e = s + strlen(s);
  4555. while ((e > s) && isspace((unsigned char)e[-1])) {
  4556. *(--e) = '\0';
  4557. }
  4558. }
  4559. static pid_t
  4560. spawn_process(struct mg_connection *conn,
  4561. const char *prog,
  4562. char *envblk,
  4563. char *envp[],
  4564. int fdin[2],
  4565. int fdout[2],
  4566. int fderr[2],
  4567. const char *dir,
  4568. unsigned char cgi_config_idx)
  4569. {
  4570. HANDLE me;
  4571. char *interp;
  4572. char *interp_arg = 0;
  4573. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4574. int truncated;
  4575. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4576. STARTUPINFOA si;
  4577. PROCESS_INFORMATION pi = {0};
  4578. (void)envp;
  4579. memset(&si, 0, sizeof(si));
  4580. si.cb = sizeof(si);
  4581. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4582. si.wShowWindow = SW_HIDE;
  4583. me = GetCurrentProcess();
  4584. DuplicateHandle(me,
  4585. (HANDLE)_get_osfhandle(fdin[0]),
  4586. me,
  4587. &si.hStdInput,
  4588. 0,
  4589. TRUE,
  4590. DUPLICATE_SAME_ACCESS);
  4591. DuplicateHandle(me,
  4592. (HANDLE)_get_osfhandle(fdout[1]),
  4593. me,
  4594. &si.hStdOutput,
  4595. 0,
  4596. TRUE,
  4597. DUPLICATE_SAME_ACCESS);
  4598. DuplicateHandle(me,
  4599. (HANDLE)_get_osfhandle(fderr[1]),
  4600. me,
  4601. &si.hStdError,
  4602. 0,
  4603. TRUE,
  4604. DUPLICATE_SAME_ACCESS);
  4605. /* Mark handles that should not be inherited. See
  4606. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4607. */
  4608. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4609. HANDLE_FLAG_INHERIT,
  4610. 0);
  4611. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4612. HANDLE_FLAG_INHERIT,
  4613. 0);
  4614. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4615. HANDLE_FLAG_INHERIT,
  4616. 0);
  4617. /* First check, if there is a CGI interpreter configured for all CGI
  4618. * scripts. */
  4619. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4620. if (interp != NULL) {
  4621. /* If there is a configured interpreter, check for additional arguments
  4622. */
  4623. interp_arg =
  4624. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4625. } else {
  4626. /* Otherwise, the interpreter must be stated in the first line of the
  4627. * CGI script file, after a #! (shebang) mark. */
  4628. buf[0] = buf[1] = '\0';
  4629. /* Get the full script path */
  4630. mg_snprintf(
  4631. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4632. if (truncated) {
  4633. pi.hProcess = (pid_t)-1;
  4634. goto spawn_cleanup;
  4635. }
  4636. /* Open the script file, to read the first line */
  4637. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4638. /* Read the first line of the script into the buffer */
  4639. mg_fgets(buf, sizeof(buf), &file);
  4640. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4641. buf[sizeof(buf) - 1] = '\0';
  4642. }
  4643. if ((buf[0] == '#') && (buf[1] == '!')) {
  4644. trim_trailing_whitespaces(buf + 2);
  4645. } else {
  4646. buf[2] = '\0';
  4647. }
  4648. interp = buf + 2;
  4649. }
  4650. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4651. if (interp[0] != '\0') {
  4652. /* This is an interpreted script file. We must call the interpreter. */
  4653. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4654. mg_snprintf(conn,
  4655. &truncated,
  4656. cmdline,
  4657. sizeof(cmdline),
  4658. "\"%s\" %s \"%s\\%s\"",
  4659. interp,
  4660. interp_arg,
  4661. full_dir,
  4662. prog);
  4663. } else {
  4664. mg_snprintf(conn,
  4665. &truncated,
  4666. cmdline,
  4667. sizeof(cmdline),
  4668. "\"%s\" \"%s\\%s\"",
  4669. interp,
  4670. full_dir,
  4671. prog);
  4672. }
  4673. } else {
  4674. /* This is (probably) a compiled program. We call it directly. */
  4675. mg_snprintf(conn,
  4676. &truncated,
  4677. cmdline,
  4678. sizeof(cmdline),
  4679. "\"%s\\%s\"",
  4680. full_dir,
  4681. prog);
  4682. }
  4683. if (truncated) {
  4684. pi.hProcess = (pid_t)-1;
  4685. goto spawn_cleanup;
  4686. }
  4687. DEBUG_TRACE("Running [%s]", cmdline);
  4688. if (CreateProcessA(NULL,
  4689. cmdline,
  4690. NULL,
  4691. NULL,
  4692. TRUE,
  4693. CREATE_NEW_PROCESS_GROUP,
  4694. envblk,
  4695. NULL,
  4696. &si,
  4697. &pi)
  4698. == 0) {
  4699. mg_cry_internal(
  4700. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4701. pi.hProcess = (pid_t)-1;
  4702. /* goto spawn_cleanup; */
  4703. }
  4704. spawn_cleanup:
  4705. (void)CloseHandle(si.hStdOutput);
  4706. (void)CloseHandle(si.hStdError);
  4707. (void)CloseHandle(si.hStdInput);
  4708. if (pi.hThread != NULL) {
  4709. (void)CloseHandle(pi.hThread);
  4710. }
  4711. return (pid_t)pi.hProcess;
  4712. }
  4713. #endif /* !NO_CGI */
  4714. static int
  4715. set_blocking_mode(SOCKET sock)
  4716. {
  4717. unsigned long non_blocking = 0;
  4718. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4719. }
  4720. static int
  4721. set_non_blocking_mode(SOCKET sock)
  4722. {
  4723. unsigned long non_blocking = 1;
  4724. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4725. }
  4726. #else
  4727. #if !defined(NO_FILESYSTEMS)
  4728. static int
  4729. mg_stat(const struct mg_connection *conn,
  4730. const char *path,
  4731. struct mg_file_stat *filep)
  4732. {
  4733. struct stat st;
  4734. if (!filep) {
  4735. return 0;
  4736. }
  4737. memset(filep, 0, sizeof(*filep));
  4738. if (mg_path_suspicious(conn, path)) {
  4739. return 0;
  4740. }
  4741. if (0 == stat(path, &st)) {
  4742. filep->size = (uint64_t)(st.st_size);
  4743. filep->last_modified = st.st_mtime;
  4744. filep->is_directory = S_ISDIR(st.st_mode);
  4745. return 1;
  4746. }
  4747. return 0;
  4748. }
  4749. #endif /* NO_FILESYSTEMS */
  4750. static void
  4751. set_close_on_exec(int fd,
  4752. const struct mg_connection *conn /* may be null */,
  4753. struct mg_context *ctx /* may be null */)
  4754. {
  4755. #if defined(__ZEPHYR__)
  4756. (void)fd;
  4757. (void)conn;
  4758. (void)ctx;
  4759. #else
  4760. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4761. if (conn || ctx) {
  4762. struct mg_connection fc;
  4763. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4764. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4765. __func__,
  4766. strerror(ERRNO));
  4767. }
  4768. }
  4769. #endif
  4770. }
  4771. int
  4772. mg_start_thread(mg_thread_func_t func, void *param)
  4773. {
  4774. pthread_t thread_id;
  4775. pthread_attr_t attr;
  4776. int result;
  4777. (void)pthread_attr_init(&attr);
  4778. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4779. #if defined(__ZEPHYR__)
  4780. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4781. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4782. /* Compile-time option to control stack size,
  4783. * e.g. -DUSE_STACK_SIZE=16384 */
  4784. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4785. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4786. result = pthread_create(&thread_id, &attr, func, param);
  4787. pthread_attr_destroy(&attr);
  4788. return result;
  4789. }
  4790. /* Start a thread storing the thread context. */
  4791. static int
  4792. mg_start_thread_with_id(mg_thread_func_t func,
  4793. void *param,
  4794. pthread_t *threadidptr)
  4795. {
  4796. pthread_t thread_id;
  4797. pthread_attr_t attr;
  4798. int result;
  4799. (void)pthread_attr_init(&attr);
  4800. #if defined(__ZEPHYR__)
  4801. pthread_attr_setstack(&attr,
  4802. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4803. ZEPHYR_STACK_SIZE);
  4804. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4805. /* Compile-time option to control stack size,
  4806. * e.g. -DUSE_STACK_SIZE=16384 */
  4807. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4808. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4809. result = pthread_create(&thread_id, &attr, func, param);
  4810. pthread_attr_destroy(&attr);
  4811. if ((result == 0) && (threadidptr != NULL)) {
  4812. *threadidptr = thread_id;
  4813. }
  4814. return result;
  4815. }
  4816. /* Wait for a thread to finish. */
  4817. static int
  4818. mg_join_thread(pthread_t threadid)
  4819. {
  4820. int result;
  4821. result = pthread_join(threadid, NULL);
  4822. return result;
  4823. }
  4824. #if !defined(NO_CGI)
  4825. static pid_t
  4826. spawn_process(struct mg_connection *conn,
  4827. const char *prog,
  4828. char *envblk,
  4829. char *envp[],
  4830. int fdin[2],
  4831. int fdout[2],
  4832. int fderr[2],
  4833. const char *dir,
  4834. unsigned char cgi_config_idx)
  4835. {
  4836. pid_t pid;
  4837. const char *interp;
  4838. (void)envblk;
  4839. if ((pid = fork()) == -1) {
  4840. /* Parent */
  4841. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4842. } else if (pid != 0) {
  4843. /* Make sure children close parent-side descriptors.
  4844. * The caller will close the child-side immediately. */
  4845. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4846. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4847. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4848. } else {
  4849. /* Child */
  4850. if (chdir(dir) != 0) {
  4851. mg_cry_internal(
  4852. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4853. } else if (dup2(fdin[0], 0) == -1) {
  4854. mg_cry_internal(conn,
  4855. "%s: dup2(%d, 0): %s",
  4856. __func__,
  4857. fdin[0],
  4858. strerror(ERRNO));
  4859. } else if (dup2(fdout[1], 1) == -1) {
  4860. mg_cry_internal(conn,
  4861. "%s: dup2(%d, 1): %s",
  4862. __func__,
  4863. fdout[1],
  4864. strerror(ERRNO));
  4865. } else if (dup2(fderr[1], 2) == -1) {
  4866. mg_cry_internal(conn,
  4867. "%s: dup2(%d, 2): %s",
  4868. __func__,
  4869. fderr[1],
  4870. strerror(ERRNO));
  4871. } else {
  4872. struct sigaction sa;
  4873. /* Keep stderr and stdout in two different pipes.
  4874. * Stdout will be sent back to the client,
  4875. * stderr should go into a server error log. */
  4876. (void)close(fdin[0]);
  4877. (void)close(fdout[1]);
  4878. (void)close(fderr[1]);
  4879. /* Close write end fdin and read end fdout and fderr */
  4880. (void)close(fdin[1]);
  4881. (void)close(fdout[0]);
  4882. (void)close(fderr[0]);
  4883. /* After exec, all signal handlers are restored to their default
  4884. * values, with one exception of SIGCHLD. According to
  4885. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4886. * will leave unchanged after exec if it was set to be ignored.
  4887. * Restore it to default action. */
  4888. memset(&sa, 0, sizeof(sa));
  4889. sa.sa_handler = SIG_DFL;
  4890. sigaction(SIGCHLD, &sa, NULL);
  4891. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4892. if (interp == NULL) {
  4893. /* no interpreter configured, call the programm directly */
  4894. (void)execle(prog, prog, NULL, envp);
  4895. mg_cry_internal(conn,
  4896. "%s: execle(%s): %s",
  4897. __func__,
  4898. prog,
  4899. strerror(ERRNO));
  4900. } else {
  4901. /* call the configured interpreter */
  4902. const char *interp_args =
  4903. conn->dom_ctx
  4904. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4905. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4906. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4907. } else {
  4908. (void)execle(interp, interp, prog, NULL, envp);
  4909. }
  4910. mg_cry_internal(conn,
  4911. "%s: execle(%s %s): %s",
  4912. __func__,
  4913. interp,
  4914. prog,
  4915. strerror(ERRNO));
  4916. }
  4917. }
  4918. exit(EXIT_FAILURE);
  4919. }
  4920. return pid;
  4921. }
  4922. #endif /* !NO_CGI */
  4923. static int
  4924. set_non_blocking_mode(SOCKET sock)
  4925. {
  4926. int flags = fcntl(sock, F_GETFL, 0);
  4927. if (flags < 0) {
  4928. return -1;
  4929. }
  4930. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4931. return -1;
  4932. }
  4933. return 0;
  4934. }
  4935. static int
  4936. set_blocking_mode(SOCKET sock)
  4937. {
  4938. int flags = fcntl(sock, F_GETFL, 0);
  4939. if (flags < 0) {
  4940. return -1;
  4941. }
  4942. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4943. return -1;
  4944. }
  4945. return 0;
  4946. }
  4947. #endif /* _WIN32 / else */
  4948. /* End of initial operating system specific define block. */
  4949. /* Get a random number (independent of C rand function) */
  4950. static uint64_t
  4951. get_random(void)
  4952. {
  4953. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4954. static uint64_t lcg = 0; /* Linear congruential generator */
  4955. uint64_t now = mg_get_current_time_ns();
  4956. if (lfsr == 0) {
  4957. /* lfsr will be only 0 if has not been initialized,
  4958. * so this code is called only once. */
  4959. lfsr = mg_get_current_time_ns();
  4960. lcg = mg_get_current_time_ns();
  4961. } else {
  4962. /* Get the next step of both random number generators. */
  4963. lfsr = (lfsr >> 1)
  4964. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4965. << 63);
  4966. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4967. }
  4968. /* Combining two pseudo-random number generators and a high resolution
  4969. * part
  4970. * of the current server time will make it hard (impossible?) to guess
  4971. * the
  4972. * next number. */
  4973. return (lfsr ^ lcg ^ now);
  4974. }
  4975. static int
  4976. mg_poll(struct mg_pollfd *pfd,
  4977. unsigned int n,
  4978. int milliseconds,
  4979. const stop_flag_t *stop_flag)
  4980. {
  4981. /* Call poll, but only for a maximum time of a few seconds.
  4982. * This will allow to stop the server after some seconds, instead
  4983. * of having to wait for a long socket timeout. */
  4984. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4985. int check_pollerr = 0;
  4986. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  4987. /* If we wait for only one file descriptor, wait on error as well */
  4988. pfd[0].events |= POLLERR;
  4989. check_pollerr = 1;
  4990. }
  4991. do {
  4992. int result;
  4993. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  4994. /* Shut down signal */
  4995. return -2;
  4996. }
  4997. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4998. ms_now = milliseconds;
  4999. }
  5000. result = poll(pfd, n, ms_now);
  5001. if (result != 0) {
  5002. /* Poll returned either success (1) or error (-1).
  5003. * Forward both to the caller. */
  5004. if ((check_pollerr)
  5005. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5006. == POLLERR)) {
  5007. /* One and only file descriptor returned error */
  5008. return -1;
  5009. }
  5010. return result;
  5011. }
  5012. /* Poll returned timeout (0). */
  5013. if (milliseconds > 0) {
  5014. milliseconds -= ms_now;
  5015. }
  5016. } while (milliseconds > 0);
  5017. /* timeout: return 0 */
  5018. return 0;
  5019. }
  5020. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5021. * descriptor.
  5022. * Return value:
  5023. * >=0 .. number of bytes successfully written
  5024. * -1 .. timeout
  5025. * -2 .. error
  5026. */
  5027. static int
  5028. push_inner(struct mg_context *ctx,
  5029. FILE *fp,
  5030. SOCKET sock,
  5031. SSL *ssl,
  5032. const char *buf,
  5033. int len,
  5034. double timeout)
  5035. {
  5036. uint64_t start = 0, now = 0, timeout_ns = 0;
  5037. int n, err;
  5038. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5039. #if defined(_WIN32)
  5040. typedef int len_t;
  5041. #else
  5042. typedef size_t len_t;
  5043. #endif
  5044. if (timeout > 0) {
  5045. now = mg_get_current_time_ns();
  5046. start = now;
  5047. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5048. }
  5049. if (ctx == NULL) {
  5050. return -2;
  5051. }
  5052. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5053. if (ssl) {
  5054. return -2;
  5055. }
  5056. #endif
  5057. /* Try to read until it succeeds, fails, times out, or the server
  5058. * shuts down. */
  5059. for (;;) {
  5060. #if defined(USE_MBEDTLS)
  5061. if (ssl != NULL) {
  5062. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5063. if (n <= 0) {
  5064. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5065. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5066. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5067. n = 0;
  5068. } else {
  5069. fprintf(stderr, "SSL write failed, error %d\n", n);
  5070. return -2;
  5071. }
  5072. } else {
  5073. err = 0;
  5074. }
  5075. } else
  5076. #elif !defined(NO_SSL)
  5077. if (ssl != NULL) {
  5078. ERR_clear_error();
  5079. n = SSL_write(ssl, buf, len);
  5080. if (n <= 0) {
  5081. err = SSL_get_error(ssl, n);
  5082. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5083. err = ERRNO;
  5084. } else if ((err == SSL_ERROR_WANT_READ)
  5085. || (err == SSL_ERROR_WANT_WRITE)) {
  5086. n = 0;
  5087. } else {
  5088. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5089. ERR_clear_error();
  5090. return -2;
  5091. }
  5092. ERR_clear_error();
  5093. } else {
  5094. err = 0;
  5095. }
  5096. } else
  5097. #endif
  5098. if (fp != NULL) {
  5099. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5100. if (ferror(fp)) {
  5101. n = -1;
  5102. err = ERRNO;
  5103. } else {
  5104. err = 0;
  5105. }
  5106. } else {
  5107. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5108. err = (n < 0) ? ERRNO : 0;
  5109. #if defined(_WIN32)
  5110. if (err == WSAEWOULDBLOCK) {
  5111. err = 0;
  5112. n = 0;
  5113. }
  5114. #else
  5115. if (ERROR_TRY_AGAIN(err)) {
  5116. err = 0;
  5117. n = 0;
  5118. }
  5119. #endif
  5120. if (n < 0) {
  5121. /* shutdown of the socket at client side */
  5122. return -2;
  5123. }
  5124. }
  5125. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5126. return -2;
  5127. }
  5128. if ((n > 0) || ((n == 0) && (len == 0))) {
  5129. /* some data has been read, or no data was requested */
  5130. return n;
  5131. }
  5132. if (n < 0) {
  5133. /* socket error - check errno */
  5134. DEBUG_TRACE("send() failed, error %d", err);
  5135. /* TODO (mid): error handling depending on the error code.
  5136. * These codes are different between Windows and Linux.
  5137. * Currently there is no problem with failing send calls,
  5138. * if there is a reproducible situation, it should be
  5139. * investigated in detail.
  5140. */
  5141. return -2;
  5142. }
  5143. /* Only in case n=0 (timeout), repeat calling the write function */
  5144. /* If send failed, wait before retry */
  5145. if (fp != NULL) {
  5146. /* For files, just wait a fixed time.
  5147. * Maybe it helps, maybe not. */
  5148. mg_sleep(5);
  5149. } else {
  5150. /* For sockets, wait for the socket using poll */
  5151. struct mg_pollfd pfd[1];
  5152. int pollres;
  5153. pfd[0].fd = sock;
  5154. pfd[0].events = POLLOUT;
  5155. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5156. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5157. return -2;
  5158. }
  5159. if (pollres > 0) {
  5160. continue;
  5161. }
  5162. }
  5163. if (timeout > 0) {
  5164. now = mg_get_current_time_ns();
  5165. if ((now - start) > timeout_ns) {
  5166. /* Timeout */
  5167. break;
  5168. }
  5169. }
  5170. }
  5171. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5172. used */
  5173. return -1;
  5174. }
  5175. static int
  5176. push_all(struct mg_context *ctx,
  5177. FILE *fp,
  5178. SOCKET sock,
  5179. SSL *ssl,
  5180. const char *buf,
  5181. int len)
  5182. {
  5183. double timeout = -1.0;
  5184. int n, nwritten = 0;
  5185. if (ctx == NULL) {
  5186. return -1;
  5187. }
  5188. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5189. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5190. }
  5191. if (timeout <= 0.0) {
  5192. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5193. / 1000.0;
  5194. }
  5195. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5196. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5197. if (n < 0) {
  5198. if (nwritten == 0) {
  5199. nwritten = -1; /* Propagate the error */
  5200. }
  5201. break;
  5202. } else if (n == 0) {
  5203. break; /* No more data to write */
  5204. } else {
  5205. nwritten += n;
  5206. len -= n;
  5207. }
  5208. }
  5209. return nwritten;
  5210. }
  5211. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5212. * Return value:
  5213. * >=0 .. number of bytes successfully read
  5214. * -1 .. timeout
  5215. * -2 .. error
  5216. */
  5217. static int
  5218. pull_inner(FILE *fp,
  5219. struct mg_connection *conn,
  5220. char *buf,
  5221. int len,
  5222. double timeout)
  5223. {
  5224. int nread, err = 0;
  5225. #if defined(_WIN32)
  5226. typedef int len_t;
  5227. #else
  5228. typedef size_t len_t;
  5229. #endif
  5230. /* We need an additional wait loop around this, because in some cases
  5231. * with TLSwe may get data from the socket but not from SSL_read.
  5232. * In this case we need to repeat at least once.
  5233. */
  5234. if (fp != NULL) {
  5235. /* Use read() instead of fread(), because if we're reading from the
  5236. * CGI pipe, fread() may block until IO buffer is filled up. We
  5237. * cannot afford to block and must pass all read bytes immediately
  5238. * to the client. */
  5239. nread = (int)read(fileno(fp), buf, (size_t)len);
  5240. err = (nread < 0) ? ERRNO : 0;
  5241. if ((nread == 0) && (len > 0)) {
  5242. /* Should get data, but got EOL */
  5243. return -2;
  5244. }
  5245. #if defined(USE_MBEDTLS)
  5246. } else if (conn->ssl != NULL) {
  5247. struct mg_pollfd pfd[1];
  5248. int to_read;
  5249. int pollres;
  5250. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5251. if (to_read > 0) {
  5252. /* We already know there is no more data buffered in conn->buf
  5253. * but there is more available in the SSL layer. So don't poll
  5254. * conn->client.sock yet. */
  5255. pollres = 1;
  5256. if (to_read > len)
  5257. to_read = len;
  5258. } else {
  5259. pfd[0].fd = conn->client.sock;
  5260. pfd[0].events = POLLIN;
  5261. to_read = len;
  5262. pollres = mg_poll(pfd,
  5263. 1,
  5264. (int)(timeout * 1000.0),
  5265. &(conn->phys_ctx->stop_flag));
  5266. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5267. return -2;
  5268. }
  5269. }
  5270. if (pollres > 0) {
  5271. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5272. if (nread <= 0) {
  5273. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5274. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5275. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5276. nread = 0;
  5277. } else {
  5278. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5279. return -2;
  5280. }
  5281. } else {
  5282. err = 0;
  5283. }
  5284. } else if (pollres < 0) {
  5285. /* Error */
  5286. return -2;
  5287. } else {
  5288. /* pollres = 0 means timeout */
  5289. nread = 0;
  5290. }
  5291. #elif !defined(NO_SSL)
  5292. } else if (conn->ssl != NULL) {
  5293. int ssl_pending;
  5294. struct mg_pollfd pfd[1];
  5295. int pollres;
  5296. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5297. /* We already know there is no more data buffered in conn->buf
  5298. * but there is more available in the SSL layer. So don't poll
  5299. * conn->client.sock yet. */
  5300. if (ssl_pending > len) {
  5301. ssl_pending = len;
  5302. }
  5303. pollres = 1;
  5304. } else {
  5305. pfd[0].fd = conn->client.sock;
  5306. pfd[0].events = POLLIN;
  5307. pollres = mg_poll(pfd,
  5308. 1,
  5309. (int)(timeout * 1000.0),
  5310. &(conn->phys_ctx->stop_flag));
  5311. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5312. return -2;
  5313. }
  5314. }
  5315. if (pollres > 0) {
  5316. ERR_clear_error();
  5317. nread =
  5318. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5319. if (nread <= 0) {
  5320. err = SSL_get_error(conn->ssl, nread);
  5321. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5322. err = ERRNO;
  5323. } else if ((err == SSL_ERROR_WANT_READ)
  5324. || (err == SSL_ERROR_WANT_WRITE)) {
  5325. nread = 0;
  5326. } else {
  5327. /* All errors should return -2 */
  5328. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5329. ERR_clear_error();
  5330. return -2;
  5331. }
  5332. ERR_clear_error();
  5333. } else {
  5334. err = 0;
  5335. }
  5336. } else if (pollres < 0) {
  5337. /* Error */
  5338. return -2;
  5339. } else {
  5340. /* pollres = 0 means timeout */
  5341. nread = 0;
  5342. }
  5343. #endif
  5344. } else {
  5345. struct mg_pollfd pfd[1];
  5346. int pollres;
  5347. pfd[0].fd = conn->client.sock;
  5348. pfd[0].events = POLLIN;
  5349. pollres = mg_poll(pfd,
  5350. 1,
  5351. (int)(timeout * 1000.0),
  5352. &(conn->phys_ctx->stop_flag));
  5353. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5354. return -2;
  5355. }
  5356. if (pollres > 0) {
  5357. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5358. err = (nread < 0) ? ERRNO : 0;
  5359. if (nread <= 0) {
  5360. /* shutdown of the socket at client side */
  5361. return -2;
  5362. }
  5363. } else if (pollres < 0) {
  5364. /* error callint poll */
  5365. return -2;
  5366. } else {
  5367. /* pollres = 0 means timeout */
  5368. nread = 0;
  5369. }
  5370. }
  5371. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5372. return -2;
  5373. }
  5374. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5375. /* some data has been read, or no data was requested */
  5376. return nread;
  5377. }
  5378. if (nread < 0) {
  5379. /* socket error - check errno */
  5380. #if defined(_WIN32)
  5381. if (err == WSAEWOULDBLOCK) {
  5382. /* TODO (low): check if this is still required */
  5383. /* standard case if called from close_socket_gracefully */
  5384. return -2;
  5385. } else if (err == WSAETIMEDOUT) {
  5386. /* TODO (low): check if this is still required */
  5387. /* timeout is handled by the while loop */
  5388. return 0;
  5389. } else if (err == WSAECONNABORTED) {
  5390. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5391. return -2;
  5392. } else {
  5393. DEBUG_TRACE("recv() failed, error %d", err);
  5394. return -2;
  5395. }
  5396. #else
  5397. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5398. * if the timeout is reached and if the socket was set to non-
  5399. * blocking in close_socket_gracefully, so we can not distinguish
  5400. * here. We have to wait for the timeout in both cases for now.
  5401. */
  5402. if (ERROR_TRY_AGAIN(err)) {
  5403. /* TODO (low): check if this is still required */
  5404. /* EAGAIN/EWOULDBLOCK:
  5405. * standard case if called from close_socket_gracefully
  5406. * => should return -1 */
  5407. /* or timeout occurred
  5408. * => the code must stay in the while loop */
  5409. /* EINTR can be generated on a socket with a timeout set even
  5410. * when SA_RESTART is effective for all relevant signals
  5411. * (see signal(7)).
  5412. * => stay in the while loop */
  5413. } else {
  5414. DEBUG_TRACE("recv() failed, error %d", err);
  5415. return -2;
  5416. }
  5417. #endif
  5418. }
  5419. /* Timeout occurred, but no data available. */
  5420. return -1;
  5421. }
  5422. static int
  5423. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5424. {
  5425. int n, nread = 0;
  5426. double timeout = -1.0;
  5427. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5428. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5429. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5430. }
  5431. if (timeout <= 0.0) {
  5432. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5433. / 1000.0;
  5434. }
  5435. start_time = mg_get_current_time_ns();
  5436. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5437. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5438. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5439. if (n == -2) {
  5440. if (nread == 0) {
  5441. nread = -1; /* Propagate the error */
  5442. }
  5443. break;
  5444. } else if (n == -1) {
  5445. /* timeout */
  5446. if (timeout >= 0.0) {
  5447. now = mg_get_current_time_ns();
  5448. if ((now - start_time) <= timeout_ns) {
  5449. continue;
  5450. }
  5451. }
  5452. break;
  5453. } else if (n == 0) {
  5454. break; /* No more data to read */
  5455. } else {
  5456. nread += n;
  5457. len -= n;
  5458. }
  5459. }
  5460. return nread;
  5461. }
  5462. static void
  5463. discard_unread_request_data(struct mg_connection *conn)
  5464. {
  5465. char buf[MG_BUF_LEN];
  5466. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5467. ;
  5468. }
  5469. static int
  5470. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5471. {
  5472. int64_t content_len, n, buffered_len, nread;
  5473. int64_t len64 =
  5474. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5475. * int, we may not read more
  5476. * bytes */
  5477. const char *body;
  5478. if (conn == NULL) {
  5479. return 0;
  5480. }
  5481. /* If Content-Length is not set for a response with body data,
  5482. * we do not know in advance how much data should be read. */
  5483. content_len = conn->content_len;
  5484. if (content_len < 0) {
  5485. /* The body data is completed when the connection is closed. */
  5486. content_len = INT64_MAX;
  5487. }
  5488. nread = 0;
  5489. if (conn->consumed_content < content_len) {
  5490. /* Adjust number of bytes to read. */
  5491. int64_t left_to_read = content_len - conn->consumed_content;
  5492. if (left_to_read < len64) {
  5493. /* Do not read more than the total content length of the
  5494. * request.
  5495. */
  5496. len64 = left_to_read;
  5497. }
  5498. /* Return buffered data */
  5499. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5500. - conn->consumed_content;
  5501. if (buffered_len > 0) {
  5502. if (len64 < buffered_len) {
  5503. buffered_len = len64;
  5504. }
  5505. body = conn->buf + conn->request_len + conn->consumed_content;
  5506. memcpy(buf, body, (size_t)buffered_len);
  5507. len64 -= buffered_len;
  5508. conn->consumed_content += buffered_len;
  5509. nread += buffered_len;
  5510. buf = (char *)buf + buffered_len;
  5511. }
  5512. /* We have returned all buffered data. Read new data from the remote
  5513. * socket.
  5514. */
  5515. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5516. conn->consumed_content += n;
  5517. nread += n;
  5518. } else {
  5519. nread = ((nread > 0) ? nread : n);
  5520. }
  5521. }
  5522. return (int)nread;
  5523. }
  5524. /* Forward declarations */
  5525. static void handle_request(struct mg_connection *);
  5526. static void log_access(const struct mg_connection *);
  5527. /* Handle request, update statistics and call access log */
  5528. static void
  5529. handle_request_stat_log(struct mg_connection *conn)
  5530. {
  5531. #if defined(USE_SERVER_STATS)
  5532. struct timespec tnow;
  5533. conn->conn_state = 4; /* processing */
  5534. #endif
  5535. handle_request(conn);
  5536. #if defined(USE_SERVER_STATS)
  5537. conn->conn_state = 5; /* processed */
  5538. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5539. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5540. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5541. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5542. conn->num_bytes_sent);
  5543. #endif
  5544. DEBUG_TRACE("%s", "handle_request done");
  5545. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5546. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5547. DEBUG_TRACE("%s", "end_request callback done");
  5548. }
  5549. log_access(conn);
  5550. }
  5551. #if defined(USE_HTTP2)
  5552. #if defined(NO_SSL)
  5553. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5554. #endif
  5555. #define USE_ALPN
  5556. #include "mod_http2.inl"
  5557. /* Not supported with HTTP/2 */
  5558. #define HTTP1_only \
  5559. { \
  5560. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5561. http2_must_use_http1(conn); \
  5562. return; \
  5563. } \
  5564. }
  5565. #else
  5566. #define HTTP1_only
  5567. #endif
  5568. int
  5569. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5570. {
  5571. if (len > INT_MAX) {
  5572. len = INT_MAX;
  5573. }
  5574. if (conn == NULL) {
  5575. return 0;
  5576. }
  5577. if (conn->is_chunked) {
  5578. size_t all_read = 0;
  5579. while (len > 0) {
  5580. if (conn->is_chunked >= 3) {
  5581. /* No more data left to read */
  5582. return 0;
  5583. }
  5584. if (conn->is_chunked != 1) {
  5585. /* Has error */
  5586. return -1;
  5587. }
  5588. if (conn->consumed_content != conn->content_len) {
  5589. /* copy from the current chunk */
  5590. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5591. if (read_ret < 1) {
  5592. /* read error */
  5593. conn->is_chunked = 2;
  5594. return -1;
  5595. }
  5596. all_read += (size_t)read_ret;
  5597. len -= (size_t)read_ret;
  5598. if (conn->consumed_content == conn->content_len) {
  5599. /* Add data bytes in the current chunk have been read,
  5600. * so we are expecting \r\n now. */
  5601. char x[2];
  5602. conn->content_len += 2;
  5603. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5604. || (x[1] != '\n')) {
  5605. /* Protocol violation */
  5606. conn->is_chunked = 2;
  5607. return -1;
  5608. }
  5609. }
  5610. } else {
  5611. /* fetch a new chunk */
  5612. size_t i;
  5613. char lenbuf[64];
  5614. char *end = NULL;
  5615. unsigned long chunkSize = 0;
  5616. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5617. conn->content_len++;
  5618. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5619. lenbuf[i] = 0;
  5620. }
  5621. if ((i > 0) && (lenbuf[i] == '\r')
  5622. && (lenbuf[i - 1] != '\r')) {
  5623. continue;
  5624. }
  5625. if ((i > 1) && (lenbuf[i] == '\n')
  5626. && (lenbuf[i - 1] == '\r')) {
  5627. lenbuf[i + 1] = 0;
  5628. chunkSize = strtoul(lenbuf, &end, 16);
  5629. if (chunkSize == 0) {
  5630. /* regular end of content */
  5631. conn->is_chunked = 3;
  5632. }
  5633. break;
  5634. }
  5635. if (!isxdigit((unsigned char)lenbuf[i])) {
  5636. /* illegal character for chunk length */
  5637. conn->is_chunked = 2;
  5638. return -1;
  5639. }
  5640. }
  5641. if ((end == NULL) || (*end != '\r')) {
  5642. /* chunksize not set correctly */
  5643. conn->is_chunked = 2;
  5644. return -1;
  5645. }
  5646. if (chunkSize == 0) {
  5647. /* try discarding trailer for keep-alive */
  5648. conn->content_len += 2;
  5649. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5650. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5651. conn->is_chunked = 4;
  5652. }
  5653. break;
  5654. }
  5655. /* append a new chunk */
  5656. conn->content_len += (int64_t)chunkSize;
  5657. }
  5658. }
  5659. return (int)all_read;
  5660. }
  5661. return mg_read_inner(conn, buf, len);
  5662. }
  5663. int
  5664. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5665. {
  5666. time_t now;
  5667. int n, total, allowed;
  5668. if (conn == NULL) {
  5669. return 0;
  5670. }
  5671. if (len > INT_MAX) {
  5672. return -1;
  5673. }
  5674. /* Mark connection as "data sent" */
  5675. conn->request_state = 10;
  5676. #if defined(USE_HTTP2)
  5677. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5678. http2_data_frame_head(conn, len, 0);
  5679. }
  5680. #endif
  5681. if (conn->throttle > 0) {
  5682. if ((now = time(NULL)) != conn->last_throttle_time) {
  5683. conn->last_throttle_time = now;
  5684. conn->last_throttle_bytes = 0;
  5685. }
  5686. allowed = conn->throttle - conn->last_throttle_bytes;
  5687. if (allowed > (int)len) {
  5688. allowed = (int)len;
  5689. }
  5690. total = push_all(conn->phys_ctx,
  5691. NULL,
  5692. conn->client.sock,
  5693. conn->ssl,
  5694. (const char *)buf,
  5695. allowed);
  5696. if (total == allowed) {
  5697. buf = (const char *)buf + total;
  5698. conn->last_throttle_bytes += total;
  5699. while ((total < (int)len)
  5700. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5701. allowed = (conn->throttle > ((int)len - total))
  5702. ? (int)len - total
  5703. : conn->throttle;
  5704. n = push_all(conn->phys_ctx,
  5705. NULL,
  5706. conn->client.sock,
  5707. conn->ssl,
  5708. (const char *)buf,
  5709. allowed);
  5710. if (n != allowed) {
  5711. break;
  5712. }
  5713. sleep(1);
  5714. conn->last_throttle_bytes = allowed;
  5715. conn->last_throttle_time = time(NULL);
  5716. buf = (const char *)buf + n;
  5717. total += n;
  5718. }
  5719. }
  5720. } else {
  5721. total = push_all(conn->phys_ctx,
  5722. NULL,
  5723. conn->client.sock,
  5724. conn->ssl,
  5725. (const char *)buf,
  5726. (int)len);
  5727. }
  5728. if (total > 0) {
  5729. conn->num_bytes_sent += total;
  5730. }
  5731. return total;
  5732. }
  5733. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5734. int
  5735. mg_send_chunk(struct mg_connection *conn,
  5736. const char *chunk,
  5737. unsigned int chunk_len)
  5738. {
  5739. char lenbuf[16];
  5740. size_t lenbuf_len;
  5741. int ret;
  5742. int t;
  5743. /* First store the length information in a text buffer. */
  5744. sprintf(lenbuf, "%x\r\n", chunk_len);
  5745. lenbuf_len = strlen(lenbuf);
  5746. /* Then send length information, chunk and terminating \r\n. */
  5747. ret = mg_write(conn, lenbuf, lenbuf_len);
  5748. if (ret != (int)lenbuf_len) {
  5749. return -1;
  5750. }
  5751. t = ret;
  5752. ret = mg_write(conn, chunk, chunk_len);
  5753. if (ret != (int)chunk_len) {
  5754. return -1;
  5755. }
  5756. t += ret;
  5757. ret = mg_write(conn, "\r\n", 2);
  5758. if (ret != 2) {
  5759. return -1;
  5760. }
  5761. t += ret;
  5762. return t;
  5763. }
  5764. #if defined(GCC_DIAGNOSTIC)
  5765. /* This block forwards format strings to printf implementations,
  5766. * so we need to disable the format-nonliteral warning. */
  5767. #pragma GCC diagnostic push
  5768. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5769. #endif
  5770. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5771. static int
  5772. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5773. {
  5774. va_list ap_copy;
  5775. size_t size = MG_BUF_LEN / 4;
  5776. int len = -1;
  5777. *buf = NULL;
  5778. while (len < 0) {
  5779. if (*buf) {
  5780. mg_free(*buf);
  5781. }
  5782. size *= 4;
  5783. *buf = (char *)mg_malloc(size);
  5784. if (!*buf) {
  5785. break;
  5786. }
  5787. va_copy(ap_copy, ap);
  5788. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5789. va_end(ap_copy);
  5790. (*buf)[size - 1] = 0;
  5791. }
  5792. return len;
  5793. }
  5794. /* Print message to buffer. If buffer is large enough to hold the message,
  5795. * return buffer. If buffer is to small, allocate large enough buffer on
  5796. * heap,
  5797. * and return allocated buffer. */
  5798. static int
  5799. alloc_vprintf(char **out_buf,
  5800. char *prealloc_buf,
  5801. size_t prealloc_size,
  5802. const char *fmt,
  5803. va_list ap)
  5804. {
  5805. va_list ap_copy;
  5806. int len;
  5807. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5808. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5809. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5810. * Therefore, we make two passes: on first pass, get required message
  5811. * length.
  5812. * On second pass, actually print the message. */
  5813. va_copy(ap_copy, ap);
  5814. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5815. va_end(ap_copy);
  5816. if (len < 0) {
  5817. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5818. * Switch to alternative code path that uses incremental
  5819. * allocations.
  5820. */
  5821. va_copy(ap_copy, ap);
  5822. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5823. va_end(ap_copy);
  5824. } else if ((size_t)(len) >= prealloc_size) {
  5825. /* The pre-allocated buffer not large enough. */
  5826. /* Allocate a new buffer. */
  5827. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5828. if (!*out_buf) {
  5829. /* Allocation failed. Return -1 as "out of memory" error. */
  5830. return -1;
  5831. }
  5832. /* Buffer allocation successful. Store the string there. */
  5833. va_copy(ap_copy, ap);
  5834. IGNORE_UNUSED_RESULT(
  5835. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5836. va_end(ap_copy);
  5837. } else {
  5838. /* The pre-allocated buffer is large enough.
  5839. * Use it to store the string and return the address. */
  5840. va_copy(ap_copy, ap);
  5841. IGNORE_UNUSED_RESULT(
  5842. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5843. va_end(ap_copy);
  5844. *out_buf = prealloc_buf;
  5845. }
  5846. return len;
  5847. }
  5848. #if defined(GCC_DIAGNOSTIC)
  5849. /* Enable format-nonliteral warning again. */
  5850. #pragma GCC diagnostic pop
  5851. #endif
  5852. static int
  5853. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5854. {
  5855. char mem[MG_BUF_LEN];
  5856. char *buf = NULL;
  5857. int len;
  5858. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5859. len = mg_write(conn, buf, (size_t)len);
  5860. }
  5861. if (buf != mem) {
  5862. mg_free(buf);
  5863. }
  5864. return len;
  5865. }
  5866. int
  5867. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5868. {
  5869. va_list ap;
  5870. int result;
  5871. va_start(ap, fmt);
  5872. result = mg_vprintf(conn, fmt, ap);
  5873. va_end(ap);
  5874. return result;
  5875. }
  5876. int
  5877. mg_url_decode(const char *src,
  5878. int src_len,
  5879. char *dst,
  5880. int dst_len,
  5881. int is_form_url_encoded)
  5882. {
  5883. int i, j, a, b;
  5884. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5885. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5886. if ((i < src_len - 2) && (src[i] == '%')
  5887. && isxdigit((unsigned char)src[i + 1])
  5888. && isxdigit((unsigned char)src[i + 2])) {
  5889. a = tolower((unsigned char)src[i + 1]);
  5890. b = tolower((unsigned char)src[i + 2]);
  5891. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5892. i += 2;
  5893. } else if (is_form_url_encoded && (src[i] == '+')) {
  5894. dst[j] = ' ';
  5895. } else {
  5896. dst[j] = src[i];
  5897. }
  5898. }
  5899. dst[j] = '\0'; /* Null-terminate the destination */
  5900. return (i >= src_len) ? j : -1;
  5901. }
  5902. /* form url decoding of an entire string */
  5903. static void
  5904. url_decode_in_place(char *buf)
  5905. {
  5906. int len = (int)strlen(buf);
  5907. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5908. }
  5909. int
  5910. mg_get_var(const char *data,
  5911. size_t data_len,
  5912. const char *name,
  5913. char *dst,
  5914. size_t dst_len)
  5915. {
  5916. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5917. }
  5918. int
  5919. mg_get_var2(const char *data,
  5920. size_t data_len,
  5921. const char *name,
  5922. char *dst,
  5923. size_t dst_len,
  5924. size_t occurrence)
  5925. {
  5926. const char *p, *e, *s;
  5927. size_t name_len;
  5928. int len;
  5929. if ((dst == NULL) || (dst_len == 0)) {
  5930. len = -2;
  5931. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5932. len = -1;
  5933. dst[0] = '\0';
  5934. } else {
  5935. name_len = strlen(name);
  5936. e = data + data_len;
  5937. len = -1;
  5938. dst[0] = '\0';
  5939. /* data is "var1=val1&var2=val2...". Find variable first */
  5940. for (p = data; p + name_len < e; p++) {
  5941. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5942. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5943. /* Point p to variable value */
  5944. p += name_len + 1;
  5945. /* Point s to the end of the value */
  5946. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5947. if (s == NULL) {
  5948. s = e;
  5949. }
  5950. DEBUG_ASSERT(s >= p);
  5951. if (s < p) {
  5952. return -3;
  5953. }
  5954. /* Decode variable into destination buffer */
  5955. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5956. /* Redirect error code from -1 to -2 (destination buffer too
  5957. * small). */
  5958. if (len == -1) {
  5959. len = -2;
  5960. }
  5961. break;
  5962. }
  5963. }
  5964. }
  5965. return len;
  5966. }
  5967. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5968. int
  5969. mg_split_form_urlencoded(char *data,
  5970. struct mg_header *form_fields,
  5971. unsigned num_form_fields)
  5972. {
  5973. char *b;
  5974. int i;
  5975. int num = 0;
  5976. if (data == NULL) {
  5977. /* parameter error */
  5978. return -1;
  5979. }
  5980. if ((form_fields == NULL) && (num_form_fields == 0)) {
  5981. /* determine the number of expected fields */
  5982. if (data[0] == 0) {
  5983. return 0;
  5984. }
  5985. /* count number of & to return the number of key-value-pairs */
  5986. num = 1;
  5987. while (*data) {
  5988. if (*data == '&') {
  5989. num++;
  5990. }
  5991. data++;
  5992. }
  5993. return num;
  5994. }
  5995. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  5996. /* parameter error */
  5997. return -1;
  5998. }
  5999. for (i = 0; i < (int)num_form_fields; i++) {
  6000. /* extract key-value pairs from input data */
  6001. while ((*data == ' ') || (*data == '\t')) {
  6002. /* skip initial spaces */
  6003. data++;
  6004. }
  6005. if (*data == 0) {
  6006. /* end of string reached */
  6007. break;
  6008. }
  6009. form_fields[num].name = data;
  6010. /* find & or = */
  6011. b = data;
  6012. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6013. b++;
  6014. }
  6015. if (*b == 0) {
  6016. /* last key without value */
  6017. form_fields[num].value = NULL;
  6018. } else if (*b == '&') {
  6019. /* mid key without value */
  6020. form_fields[num].value = NULL;
  6021. } else {
  6022. /* terminate string */
  6023. *b = 0;
  6024. /* value starts after '=' */
  6025. data = b + 1;
  6026. form_fields[num].value = data;
  6027. }
  6028. /* new field is stored */
  6029. num++;
  6030. /* find a next key */
  6031. b = strchr(data, '&');
  6032. if (b == 0) {
  6033. /* no more data */
  6034. break;
  6035. } else {
  6036. /* terminate value of last field at '&' */
  6037. *b = 0;
  6038. /* next key-value-pairs starts after '&' */
  6039. data = b + 1;
  6040. }
  6041. }
  6042. /* Decode all values */
  6043. for (i = 0; i < num; i++) {
  6044. if (form_fields[i].name) {
  6045. url_decode_in_place((char *)form_fields[i].name);
  6046. }
  6047. if (form_fields[i].value) {
  6048. url_decode_in_place((char *)form_fields[i].value);
  6049. }
  6050. }
  6051. /* return number of fields found */
  6052. return num;
  6053. }
  6054. /* HCP24: some changes to compare whole var_name */
  6055. int
  6056. mg_get_cookie(const char *cookie_header,
  6057. const char *var_name,
  6058. char *dst,
  6059. size_t dst_size)
  6060. {
  6061. const char *s, *p, *end;
  6062. int name_len, len = -1;
  6063. if ((dst == NULL) || (dst_size == 0)) {
  6064. return -2;
  6065. }
  6066. dst[0] = '\0';
  6067. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6068. return -1;
  6069. }
  6070. name_len = (int)strlen(var_name);
  6071. end = s + strlen(s);
  6072. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6073. if (s[name_len] == '=') {
  6074. /* HCP24: now check is it a substring or a full cookie name */
  6075. if ((s == cookie_header) || (s[-1] == ' ')) {
  6076. s += name_len + 1;
  6077. if ((p = strchr(s, ' ')) == NULL) {
  6078. p = end;
  6079. }
  6080. if (p[-1] == ';') {
  6081. p--;
  6082. }
  6083. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6084. s++;
  6085. p--;
  6086. }
  6087. if ((size_t)(p - s) < dst_size) {
  6088. len = (int)(p - s);
  6089. mg_strlcpy(dst, s, (size_t)len + 1);
  6090. } else {
  6091. len = -3;
  6092. }
  6093. break;
  6094. }
  6095. }
  6096. }
  6097. return len;
  6098. }
  6099. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6100. static void
  6101. base64_encode(const unsigned char *src, int src_len, char *dst)
  6102. {
  6103. static const char *b64 =
  6104. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6105. int i, j, a, b, c;
  6106. for (i = j = 0; i < src_len; i += 3) {
  6107. a = src[i];
  6108. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6109. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6110. dst[j++] = b64[a >> 2];
  6111. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6112. if (i + 1 < src_len) {
  6113. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6114. }
  6115. if (i + 2 < src_len) {
  6116. dst[j++] = b64[c & 63];
  6117. }
  6118. }
  6119. while (j % 4 != 0) {
  6120. dst[j++] = '=';
  6121. }
  6122. dst[j++] = '\0';
  6123. }
  6124. #endif
  6125. #if defined(USE_LUA)
  6126. static unsigned char
  6127. b64reverse(char letter)
  6128. {
  6129. if ((letter >= 'A') && (letter <= 'Z')) {
  6130. return letter - 'A';
  6131. }
  6132. if ((letter >= 'a') && (letter <= 'z')) {
  6133. return letter - 'a' + 26;
  6134. }
  6135. if ((letter >= '0') && (letter <= '9')) {
  6136. return letter - '0' + 52;
  6137. }
  6138. if (letter == '+') {
  6139. return 62;
  6140. }
  6141. if (letter == '/') {
  6142. return 63;
  6143. }
  6144. if (letter == '=') {
  6145. return 255; /* normal end */
  6146. }
  6147. return 254; /* error */
  6148. }
  6149. static int
  6150. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6151. {
  6152. int i;
  6153. unsigned char a, b, c, d;
  6154. *dst_len = 0;
  6155. for (i = 0; i < src_len; i += 4) {
  6156. a = b64reverse(src[i]);
  6157. if (a >= 254) {
  6158. return i;
  6159. }
  6160. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6161. if (b >= 254) {
  6162. return i + 1;
  6163. }
  6164. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6165. if (c == 254) {
  6166. return i + 2;
  6167. }
  6168. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6169. if (d == 254) {
  6170. return i + 3;
  6171. }
  6172. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6173. if (c != 255) {
  6174. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6175. if (d != 255) {
  6176. dst[(*dst_len)++] = (c << 6) + d;
  6177. }
  6178. }
  6179. }
  6180. return -1;
  6181. }
  6182. #endif
  6183. static int
  6184. is_put_or_delete_method(const struct mg_connection *conn)
  6185. {
  6186. if (conn) {
  6187. const char *s = conn->request_info.request_method;
  6188. return (s != NULL)
  6189. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6190. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6191. }
  6192. return 0;
  6193. }
  6194. #if !defined(NO_FILES)
  6195. static int
  6196. extention_matches_script(
  6197. struct mg_connection *conn, /* in: request (must be valid) */
  6198. const char *filename /* in: filename (must be valid) */
  6199. )
  6200. {
  6201. #if !defined(NO_CGI)
  6202. unsigned char cgi_config_idx, inc, max;
  6203. #endif
  6204. #if defined(USE_LUA)
  6205. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6206. filename)
  6207. > 0) {
  6208. return 1;
  6209. }
  6210. #endif
  6211. #if defined(USE_DUKTAPE)
  6212. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6213. filename)
  6214. > 0) {
  6215. return 1;
  6216. }
  6217. #endif
  6218. #if !defined(NO_CGI)
  6219. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6220. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6221. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6222. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6223. && (match_prefix_strlen(
  6224. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6225. filename)
  6226. > 0)) {
  6227. return 1;
  6228. }
  6229. }
  6230. #endif
  6231. /* filename and conn could be unused, if all preocessor conditions
  6232. * are false (no script language supported). */
  6233. (void)filename;
  6234. (void)conn;
  6235. return 0;
  6236. }
  6237. static int
  6238. extention_matches_template_text(
  6239. struct mg_connection *conn, /* in: request (must be valid) */
  6240. const char *filename /* in: filename (must be valid) */
  6241. )
  6242. {
  6243. #if defined(USE_LUA)
  6244. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6245. filename)
  6246. > 0) {
  6247. return 1;
  6248. }
  6249. #endif
  6250. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6251. > 0) {
  6252. return 1;
  6253. }
  6254. return 0;
  6255. }
  6256. /* For given directory path, substitute it to valid index file.
  6257. * Return 1 if index file has been found, 0 if not found.
  6258. * If the file is found, it's stats is returned in stp. */
  6259. static int
  6260. substitute_index_file(struct mg_connection *conn,
  6261. char *path,
  6262. size_t path_len,
  6263. struct mg_file_stat *filestat)
  6264. {
  6265. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6266. struct vec filename_vec;
  6267. size_t n = strlen(path);
  6268. int found = 0;
  6269. /* The 'path' given to us points to the directory. Remove all trailing
  6270. * directory separator characters from the end of the path, and
  6271. * then append single directory separator character. */
  6272. while ((n > 0) && (path[n - 1] == '/')) {
  6273. n--;
  6274. }
  6275. path[n] = '/';
  6276. /* Traverse index files list. For each entry, append it to the given
  6277. * path and see if the file exists. If it exists, break the loop */
  6278. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6279. /* Ignore too long entries that may overflow path buffer */
  6280. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6281. continue;
  6282. }
  6283. /* Prepare full path to the index file */
  6284. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6285. /* Does it exist? */
  6286. if (mg_stat(conn, path, filestat)) {
  6287. /* Yes it does, break the loop */
  6288. found = 1;
  6289. break;
  6290. }
  6291. }
  6292. /* If no index file exists, restore directory path */
  6293. if (!found) {
  6294. path[n] = '\0';
  6295. }
  6296. return found;
  6297. }
  6298. #endif
  6299. static void
  6300. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6301. char *filename, /* out: filename */
  6302. size_t filename_buf_len, /* in: size of filename buffer */
  6303. struct mg_file_stat *filestat, /* out: file status structure */
  6304. int *is_found, /* out: file found (directly) */
  6305. int *is_script_resource, /* out: handled by a script? */
  6306. int *is_websocket_request, /* out: websocket connetion? */
  6307. int *is_put_or_delete_request, /* out: put/delete a file? */
  6308. int *is_template_text /* out: SSI file or LSP file? */
  6309. )
  6310. {
  6311. char const *accept_encoding;
  6312. #if !defined(NO_FILES)
  6313. const char *uri = conn->request_info.local_uri;
  6314. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6315. const char *rewrite;
  6316. struct vec a, b;
  6317. ptrdiff_t match_len;
  6318. char gz_path[UTF8_PATH_MAX];
  6319. int truncated;
  6320. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6321. char *tmp_str;
  6322. size_t tmp_str_len, sep_pos;
  6323. int allow_substitute_script_subresources;
  6324. #endif
  6325. #else
  6326. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6327. #endif
  6328. /* Step 1: Set all initially unknown outputs to zero */
  6329. memset(filestat, 0, sizeof(*filestat));
  6330. *filename = 0;
  6331. *is_found = 0;
  6332. *is_script_resource = 0;
  6333. *is_template_text = 0;
  6334. /* Step 2: Check if the request attempts to modify the file system */
  6335. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6336. /* Step 3: Check if it is a websocket request, and modify the document
  6337. * root if required */
  6338. #if defined(USE_WEBSOCKET)
  6339. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6340. #if !defined(NO_FILES)
  6341. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6342. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6343. }
  6344. #endif /* !NO_FILES */
  6345. #else /* USE_WEBSOCKET */
  6346. *is_websocket_request = 0;
  6347. #endif /* USE_WEBSOCKET */
  6348. /* Step 4: Check if gzip encoded response is allowed */
  6349. conn->accept_gzip = 0;
  6350. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6351. if (strstr(accept_encoding, "gzip") != NULL) {
  6352. conn->accept_gzip = 1;
  6353. }
  6354. }
  6355. #if !defined(NO_FILES)
  6356. /* Step 5: If there is no root directory, don't look for files. */
  6357. /* Note that root == NULL is a regular use case here. This occurs,
  6358. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6359. * config is not required. */
  6360. if (root == NULL) {
  6361. /* all file related outputs have already been set to 0, just return
  6362. */
  6363. return;
  6364. }
  6365. /* Step 6: Determine the local file path from the root path and the
  6366. * request uri. */
  6367. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6368. * part of the path one byte on the right. */
  6369. truncated = 0;
  6370. mg_snprintf(
  6371. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6372. if (truncated) {
  6373. goto interpret_cleanup;
  6374. }
  6375. /* Step 7: URI rewriting */
  6376. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6377. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6378. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6379. mg_snprintf(conn,
  6380. &truncated,
  6381. filename,
  6382. filename_buf_len - 1,
  6383. "%.*s%s",
  6384. (int)b.len,
  6385. b.ptr,
  6386. uri + match_len);
  6387. break;
  6388. }
  6389. }
  6390. if (truncated) {
  6391. goto interpret_cleanup;
  6392. }
  6393. /* Step 8: Check if the file exists at the server */
  6394. /* Local file path and name, corresponding to requested URI
  6395. * is now stored in "filename" variable. */
  6396. if (mg_stat(conn, filename, filestat)) {
  6397. int uri_len = (int)strlen(uri);
  6398. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6399. /* 8.1: File exists. */
  6400. *is_found = 1;
  6401. /* 8.2: Check if it is a script type. */
  6402. if (extention_matches_script(conn, filename)) {
  6403. /* The request addresses a CGI resource, Lua script or
  6404. * server-side javascript.
  6405. * The URI corresponds to the script itself (like
  6406. * /path/script.cgi), and there is no additional resource
  6407. * path (like /path/script.cgi/something).
  6408. * Requests that modify (replace or delete) a resource, like
  6409. * PUT and DELETE requests, should replace/delete the script
  6410. * file.
  6411. * Requests that read or write from/to a resource, like GET and
  6412. * POST requests, should call the script and return the
  6413. * generated response. */
  6414. *is_script_resource = (!*is_put_or_delete_request);
  6415. }
  6416. /* 8.3: Check for SSI and LSP files */
  6417. if (extention_matches_template_text(conn, filename)) {
  6418. /* Same as above, but for *.lsp and *.shtml files. */
  6419. /* A "template text" is a file delivered directly to the client,
  6420. * but with some text tags replaced by dynamic content.
  6421. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6422. * (LP, LSP) file. */
  6423. *is_template_text = (!*is_put_or_delete_request);
  6424. }
  6425. /* 8.4: If the request target is a directory, there could be
  6426. * a substitute file (index.html, index.cgi, ...). */
  6427. if (filestat->is_directory && is_uri_end_slash) {
  6428. /* Use a local copy here, since substitute_index_file will
  6429. * change the content of the file status */
  6430. struct mg_file_stat tmp_filestat;
  6431. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6432. if (substitute_index_file(
  6433. conn, filename, filename_buf_len, &tmp_filestat)) {
  6434. /* Substitute file found. Copy stat to the output, then
  6435. * check if the file is a script file */
  6436. *filestat = tmp_filestat;
  6437. if (extention_matches_script(conn, filename)) {
  6438. /* Substitute file is a script file */
  6439. *is_script_resource = 1;
  6440. } else if (extention_matches_template_text(conn, filename)) {
  6441. /* Substitute file is a LSP or SSI file */
  6442. *is_template_text = 1;
  6443. } else {
  6444. /* Substitute file is a regular file */
  6445. *is_script_resource = 0;
  6446. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6447. }
  6448. }
  6449. /* If there is no substitute file, the server could return
  6450. * a directory listing in a later step */
  6451. }
  6452. return;
  6453. }
  6454. /* Step 9: Check for zipped files: */
  6455. /* If we can't find the actual file, look for the file
  6456. * with the same name but a .gz extension. If we find it,
  6457. * use that and set the gzipped flag in the file struct
  6458. * to indicate that the response need to have the content-
  6459. * encoding: gzip header.
  6460. * We can only do this if the browser declares support. */
  6461. if (conn->accept_gzip) {
  6462. mg_snprintf(
  6463. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6464. if (truncated) {
  6465. goto interpret_cleanup;
  6466. }
  6467. if (mg_stat(conn, gz_path, filestat)) {
  6468. if (filestat) {
  6469. filestat->is_gzipped = 1;
  6470. *is_found = 1;
  6471. }
  6472. /* Currently gz files can not be scripts. */
  6473. return;
  6474. }
  6475. }
  6476. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6477. /* Step 10: Script resources may handle sub-resources */
  6478. /* Support PATH_INFO for CGI scripts. */
  6479. tmp_str_len = strlen(filename);
  6480. tmp_str =
  6481. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6482. if (!tmp_str) {
  6483. /* Out of memory */
  6484. goto interpret_cleanup;
  6485. }
  6486. memcpy(tmp_str, filename, tmp_str_len + 1);
  6487. /* Check config, if index scripts may have sub-resources */
  6488. allow_substitute_script_subresources =
  6489. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6490. "yes");
  6491. sep_pos = tmp_str_len;
  6492. while (sep_pos > 0) {
  6493. sep_pos--;
  6494. if (tmp_str[sep_pos] == '/') {
  6495. int is_script = 0, does_exist = 0;
  6496. tmp_str[sep_pos] = 0;
  6497. if (tmp_str[0]) {
  6498. is_script = extention_matches_script(conn, tmp_str);
  6499. does_exist = mg_stat(conn, tmp_str, filestat);
  6500. }
  6501. if (does_exist && is_script) {
  6502. filename[sep_pos] = 0;
  6503. memmove(filename + sep_pos + 2,
  6504. filename + sep_pos + 1,
  6505. strlen(filename + sep_pos + 1) + 1);
  6506. conn->path_info = filename + sep_pos + 1;
  6507. filename[sep_pos + 1] = '/';
  6508. *is_script_resource = 1;
  6509. *is_found = 1;
  6510. break;
  6511. }
  6512. if (allow_substitute_script_subresources) {
  6513. if (substitute_index_file(
  6514. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6515. /* some intermediate directory has an index file */
  6516. if (extention_matches_script(conn, tmp_str)) {
  6517. size_t script_name_len = strlen(tmp_str);
  6518. /* subres_name read before this memory locatio will be
  6519. overwritten */
  6520. char *subres_name = filename + sep_pos;
  6521. size_t subres_name_len = strlen(subres_name);
  6522. DEBUG_TRACE("Substitute script %s serving path %s",
  6523. tmp_str,
  6524. filename);
  6525. /* this index file is a script */
  6526. if ((script_name_len + subres_name_len + 2)
  6527. >= filename_buf_len) {
  6528. mg_free(tmp_str);
  6529. goto interpret_cleanup;
  6530. }
  6531. conn->path_info =
  6532. filename + script_name_len + 1; /* new target */
  6533. memmove(conn->path_info, subres_name, subres_name_len);
  6534. conn->path_info[subres_name_len] = 0;
  6535. memcpy(filename, tmp_str, script_name_len + 1);
  6536. *is_script_resource = 1;
  6537. *is_found = 1;
  6538. break;
  6539. } else {
  6540. DEBUG_TRACE("Substitute file %s serving path %s",
  6541. tmp_str,
  6542. filename);
  6543. /* non-script files will not have sub-resources */
  6544. filename[sep_pos] = 0;
  6545. conn->path_info = 0;
  6546. *is_script_resource = 0;
  6547. *is_found = 0;
  6548. break;
  6549. }
  6550. }
  6551. }
  6552. tmp_str[sep_pos] = '/';
  6553. }
  6554. }
  6555. mg_free(tmp_str);
  6556. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6557. #endif /* !defined(NO_FILES) */
  6558. return;
  6559. #if !defined(NO_FILES)
  6560. /* Reset all outputs */
  6561. interpret_cleanup:
  6562. memset(filestat, 0, sizeof(*filestat));
  6563. *filename = 0;
  6564. *is_found = 0;
  6565. *is_script_resource = 0;
  6566. *is_websocket_request = 0;
  6567. *is_put_or_delete_request = 0;
  6568. #endif /* !defined(NO_FILES) */
  6569. }
  6570. /* Check whether full request is buffered. Return:
  6571. * -1 if request or response is malformed
  6572. * 0 if request or response is not yet fully buffered
  6573. * >0 actual request length, including last \r\n\r\n */
  6574. static int
  6575. get_http_header_len(const char *buf, int buflen)
  6576. {
  6577. int i;
  6578. for (i = 0; i < buflen; i++) {
  6579. /* Do an unsigned comparison in some conditions below */
  6580. const unsigned char c = (unsigned char)buf[i];
  6581. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6582. && !isprint(c)) {
  6583. /* abort scan as soon as one malformed character is found */
  6584. return -1;
  6585. }
  6586. if (i < buflen - 1) {
  6587. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6588. /* Two newline, no carriage return - not standard compliant,
  6589. * but it should be accepted */
  6590. return i + 2;
  6591. }
  6592. }
  6593. if (i < buflen - 3) {
  6594. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6595. && (buf[i + 3] == '\n')) {
  6596. /* Two \r\n - standard compliant */
  6597. return i + 4;
  6598. }
  6599. }
  6600. }
  6601. return 0;
  6602. }
  6603. #if !defined(NO_CACHING)
  6604. /* Convert month to the month number. Return -1 on error, or month number */
  6605. static int
  6606. get_month_index(const char *s)
  6607. {
  6608. size_t i;
  6609. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6610. if (!strcmp(s, month_names[i])) {
  6611. return (int)i;
  6612. }
  6613. }
  6614. return -1;
  6615. }
  6616. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6617. static time_t
  6618. parse_date_string(const char *datetime)
  6619. {
  6620. char month_str[32] = {0};
  6621. int second, minute, hour, day, month, year;
  6622. time_t result = (time_t)0;
  6623. struct tm tm;
  6624. if ((sscanf(datetime,
  6625. "%d/%3s/%d %d:%d:%d",
  6626. &day,
  6627. month_str,
  6628. &year,
  6629. &hour,
  6630. &minute,
  6631. &second)
  6632. == 6)
  6633. || (sscanf(datetime,
  6634. "%d %3s %d %d:%d:%d",
  6635. &day,
  6636. month_str,
  6637. &year,
  6638. &hour,
  6639. &minute,
  6640. &second)
  6641. == 6)
  6642. || (sscanf(datetime,
  6643. "%*3s, %d %3s %d %d:%d:%d",
  6644. &day,
  6645. month_str,
  6646. &year,
  6647. &hour,
  6648. &minute,
  6649. &second)
  6650. == 6)
  6651. || (sscanf(datetime,
  6652. "%d-%3s-%d %d:%d:%d",
  6653. &day,
  6654. month_str,
  6655. &year,
  6656. &hour,
  6657. &minute,
  6658. &second)
  6659. == 6)) {
  6660. month = get_month_index(month_str);
  6661. if ((month >= 0) && (year >= 1970)) {
  6662. memset(&tm, 0, sizeof(tm));
  6663. tm.tm_year = year - 1900;
  6664. tm.tm_mon = month;
  6665. tm.tm_mday = day;
  6666. tm.tm_hour = hour;
  6667. tm.tm_min = minute;
  6668. tm.tm_sec = second;
  6669. result = timegm(&tm);
  6670. }
  6671. }
  6672. return result;
  6673. }
  6674. #endif /* !NO_CACHING */
  6675. /* Pre-process URIs according to RFC + protect against directory disclosure
  6676. * attacks by removing '..', excessive '/' and '\' characters */
  6677. static void
  6678. remove_dot_segments(char *inout)
  6679. {
  6680. /* Windows backend protection
  6681. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6682. * in URI by slash */
  6683. char *out_end = inout;
  6684. char *in = inout;
  6685. if (!in) {
  6686. /* Param error. */
  6687. return;
  6688. }
  6689. while (*in) {
  6690. if (*in == '\\') {
  6691. *in = '/';
  6692. }
  6693. in++;
  6694. }
  6695. /* Algorithm "remove_dot_segments" from
  6696. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6697. /* Step 1:
  6698. * The input buffer is initialized.
  6699. * The output buffer is initialized to the empty string.
  6700. */
  6701. in = inout;
  6702. /* Step 2:
  6703. * While the input buffer is not empty, loop as follows:
  6704. */
  6705. /* Less than out_end of the inout buffer is used as output, so keep
  6706. * condition: out_end <= in */
  6707. while (*in) {
  6708. /* Step 2a:
  6709. * If the input buffer begins with a prefix of "../" or "./",
  6710. * then remove that prefix from the input buffer;
  6711. */
  6712. if (!strncmp(in, "../", 3)) {
  6713. in += 3;
  6714. } else if (!strncmp(in, "./", 2)) {
  6715. in += 2;
  6716. }
  6717. /* otherwise */
  6718. /* Step 2b:
  6719. * if the input buffer begins with a prefix of "/./" or "/.",
  6720. * where "." is a complete path segment, then replace that
  6721. * prefix with "/" in the input buffer;
  6722. */
  6723. else if (!strncmp(in, "/./", 3)) {
  6724. in += 2;
  6725. } else if (!strcmp(in, "/.")) {
  6726. in[1] = 0;
  6727. }
  6728. /* otherwise */
  6729. /* Step 2c:
  6730. * if the input buffer begins with a prefix of "/../" or "/..",
  6731. * where ".." is a complete path segment, then replace that
  6732. * prefix with "/" in the input buffer and remove the last
  6733. * segment and its preceding "/" (if any) from the output
  6734. * buffer;
  6735. */
  6736. else if (!strncmp(in, "/../", 4)) {
  6737. in += 3;
  6738. if (inout != out_end) {
  6739. /* remove last segment */
  6740. do {
  6741. out_end--;
  6742. } while ((inout != out_end) && (*out_end != '/'));
  6743. }
  6744. } else if (!strcmp(in, "/..")) {
  6745. in[1] = 0;
  6746. if (inout != out_end) {
  6747. /* remove last segment */
  6748. do {
  6749. out_end--;
  6750. } while ((inout != out_end) && (*out_end != '/'));
  6751. }
  6752. }
  6753. /* otherwise */
  6754. /* Step 2d:
  6755. * if the input buffer consists only of "." or "..", then remove
  6756. * that from the input buffer;
  6757. */
  6758. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6759. *in = 0;
  6760. }
  6761. /* otherwise */
  6762. /* Step 2e:
  6763. * move the first path segment in the input buffer to the end of
  6764. * the output buffer, including the initial "/" character (if
  6765. * any) and any subsequent characters up to, but not including,
  6766. * the next "/" character or the end of the input buffer.
  6767. */
  6768. else {
  6769. do {
  6770. *out_end = *in;
  6771. out_end++;
  6772. in++;
  6773. } while ((*in != 0) && (*in != '/'));
  6774. }
  6775. }
  6776. /* Step 3:
  6777. * Finally, the output buffer is returned as the result of
  6778. * remove_dot_segments.
  6779. */
  6780. /* Terminate output */
  6781. *out_end = 0;
  6782. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6783. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6784. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6785. * or "//" anymore.
  6786. */
  6787. out_end = in = inout;
  6788. while (*in) {
  6789. if (*in == '.') {
  6790. /* remove . at the end or preceding of / */
  6791. char *in_ahead = in;
  6792. do {
  6793. in_ahead++;
  6794. } while (*in_ahead == '.');
  6795. if (*in_ahead == '/') {
  6796. in = in_ahead;
  6797. if ((out_end != inout) && (out_end[-1] == '/')) {
  6798. /* remove generated // */
  6799. out_end--;
  6800. }
  6801. } else if (*in_ahead == 0) {
  6802. in = in_ahead;
  6803. } else {
  6804. do {
  6805. *out_end++ = '.';
  6806. in++;
  6807. } while (in != in_ahead);
  6808. }
  6809. } else if (*in == '/') {
  6810. /* replace // by / */
  6811. *out_end++ = '/';
  6812. do {
  6813. in++;
  6814. } while (*in == '/');
  6815. } else {
  6816. *out_end++ = *in;
  6817. in++;
  6818. }
  6819. }
  6820. *out_end = 0;
  6821. }
  6822. static const struct {
  6823. const char *extension;
  6824. size_t ext_len;
  6825. const char *mime_type;
  6826. } builtin_mime_types[] = {
  6827. /* IANA registered MIME types
  6828. * (http://www.iana.org/assignments/media-types)
  6829. * application types */
  6830. {".bin", 4, "application/octet-stream"},
  6831. {".deb", 4, "application/octet-stream"},
  6832. {".dmg", 4, "application/octet-stream"},
  6833. {".dll", 4, "application/octet-stream"},
  6834. {".doc", 4, "application/msword"},
  6835. {".eps", 4, "application/postscript"},
  6836. {".exe", 4, "application/octet-stream"},
  6837. {".iso", 4, "application/octet-stream"},
  6838. {".js", 3, "application/javascript"},
  6839. {".json", 5, "application/json"},
  6840. {".msi", 4, "application/octet-stream"},
  6841. {".pdf", 4, "application/pdf"},
  6842. {".ps", 3, "application/postscript"},
  6843. {".rtf", 4, "application/rtf"},
  6844. {".xhtml", 6, "application/xhtml+xml"},
  6845. {".xsl", 4, "application/xml"},
  6846. {".xslt", 5, "application/xml"},
  6847. /* fonts */
  6848. {".ttf", 4, "application/font-sfnt"},
  6849. {".cff", 4, "application/font-sfnt"},
  6850. {".otf", 4, "application/font-sfnt"},
  6851. {".aat", 4, "application/font-sfnt"},
  6852. {".sil", 4, "application/font-sfnt"},
  6853. {".pfr", 4, "application/font-tdpfr"},
  6854. {".woff", 5, "application/font-woff"},
  6855. {".woff2", 6, "application/font-woff2"},
  6856. /* audio */
  6857. {".mp3", 4, "audio/mpeg"},
  6858. {".oga", 4, "audio/ogg"},
  6859. {".ogg", 4, "audio/ogg"},
  6860. /* image */
  6861. {".gif", 4, "image/gif"},
  6862. {".ief", 4, "image/ief"},
  6863. {".jpeg", 5, "image/jpeg"},
  6864. {".jpg", 4, "image/jpeg"},
  6865. {".jpm", 4, "image/jpm"},
  6866. {".jpx", 4, "image/jpx"},
  6867. {".png", 4, "image/png"},
  6868. {".svg", 4, "image/svg+xml"},
  6869. {".tif", 4, "image/tiff"},
  6870. {".tiff", 5, "image/tiff"},
  6871. /* model */
  6872. {".wrl", 4, "model/vrml"},
  6873. /* text */
  6874. {".css", 4, "text/css"},
  6875. {".csv", 4, "text/csv"},
  6876. {".htm", 4, "text/html"},
  6877. {".html", 5, "text/html"},
  6878. {".sgm", 4, "text/sgml"},
  6879. {".shtm", 5, "text/html"},
  6880. {".shtml", 6, "text/html"},
  6881. {".txt", 4, "text/plain"},
  6882. {".xml", 4, "text/xml"},
  6883. /* video */
  6884. {".mov", 4, "video/quicktime"},
  6885. {".mp4", 4, "video/mp4"},
  6886. {".mpeg", 5, "video/mpeg"},
  6887. {".mpg", 4, "video/mpeg"},
  6888. {".ogv", 4, "video/ogg"},
  6889. {".qt", 3, "video/quicktime"},
  6890. /* not registered types
  6891. * (http://reference.sitepoint.com/html/mime-types-full,
  6892. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6893. {".arj", 4, "application/x-arj-compressed"},
  6894. {".gz", 3, "application/x-gunzip"},
  6895. {".rar", 4, "application/x-arj-compressed"},
  6896. {".swf", 4, "application/x-shockwave-flash"},
  6897. {".tar", 4, "application/x-tar"},
  6898. {".tgz", 4, "application/x-tar-gz"},
  6899. {".torrent", 8, "application/x-bittorrent"},
  6900. {".ppt", 4, "application/x-mspowerpoint"},
  6901. {".xls", 4, "application/x-msexcel"},
  6902. {".zip", 4, "application/x-zip-compressed"},
  6903. {".aac",
  6904. 4,
  6905. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6906. {".flac", 5, "audio/flac"},
  6907. {".aif", 4, "audio/x-aif"},
  6908. {".m3u", 4, "audio/x-mpegurl"},
  6909. {".mid", 4, "audio/x-midi"},
  6910. {".ra", 3, "audio/x-pn-realaudio"},
  6911. {".ram", 4, "audio/x-pn-realaudio"},
  6912. {".wav", 4, "audio/x-wav"},
  6913. {".bmp", 4, "image/bmp"},
  6914. {".ico", 4, "image/x-icon"},
  6915. {".pct", 4, "image/x-pct"},
  6916. {".pict", 5, "image/pict"},
  6917. {".rgb", 4, "image/x-rgb"},
  6918. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6919. {".asf", 4, "video/x-ms-asf"},
  6920. {".avi", 4, "video/x-msvideo"},
  6921. {".m4v", 4, "video/x-m4v"},
  6922. {NULL, 0, NULL}};
  6923. const char *
  6924. mg_get_builtin_mime_type(const char *path)
  6925. {
  6926. const char *ext;
  6927. size_t i, path_len;
  6928. path_len = strlen(path);
  6929. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6930. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6931. if ((path_len > builtin_mime_types[i].ext_len)
  6932. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6933. return builtin_mime_types[i].mime_type;
  6934. }
  6935. }
  6936. return "text/plain";
  6937. }
  6938. /* Look at the "path" extension and figure what mime type it has.
  6939. * Store mime type in the vector. */
  6940. static void
  6941. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6942. {
  6943. struct vec ext_vec, mime_vec;
  6944. const char *list, *ext;
  6945. size_t path_len;
  6946. path_len = strlen(path);
  6947. if ((conn == NULL) || (vec == NULL)) {
  6948. if (vec != NULL) {
  6949. memset(vec, '\0', sizeof(struct vec));
  6950. }
  6951. return;
  6952. }
  6953. /* Scan user-defined mime types first, in case user wants to
  6954. * override default mime types. */
  6955. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6956. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6957. /* ext now points to the path suffix */
  6958. ext = path + path_len - ext_vec.len;
  6959. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6960. *vec = mime_vec;
  6961. return;
  6962. }
  6963. }
  6964. vec->ptr = mg_get_builtin_mime_type(path);
  6965. vec->len = strlen(vec->ptr);
  6966. }
  6967. /* Stringify binary data. Output buffer must be twice as big as input,
  6968. * because each byte takes 2 bytes in string representation */
  6969. static void
  6970. bin2str(char *to, const unsigned char *p, size_t len)
  6971. {
  6972. static const char *hex = "0123456789abcdef";
  6973. for (; len--; p++) {
  6974. *to++ = hex[p[0] >> 4];
  6975. *to++ = hex[p[0] & 0x0f];
  6976. }
  6977. *to = '\0';
  6978. }
  6979. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6980. */
  6981. char *
  6982. mg_md5(char buf[33], ...)
  6983. {
  6984. md5_byte_t hash[16];
  6985. const char *p;
  6986. va_list ap;
  6987. md5_state_t ctx;
  6988. md5_init(&ctx);
  6989. va_start(ap, buf);
  6990. while ((p = va_arg(ap, const char *)) != NULL) {
  6991. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6992. }
  6993. va_end(ap);
  6994. md5_finish(&ctx, hash);
  6995. bin2str(buf, hash, sizeof(hash));
  6996. return buf;
  6997. }
  6998. /* Check the user's password, return 1 if OK */
  6999. static int
  7000. check_password(const char *method,
  7001. const char *ha1,
  7002. const char *uri,
  7003. const char *nonce,
  7004. const char *nc,
  7005. const char *cnonce,
  7006. const char *qop,
  7007. const char *response)
  7008. {
  7009. char ha2[32 + 1], expected_response[32 + 1];
  7010. /* Some of the parameters may be NULL */
  7011. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7012. || (qop == NULL) || (response == NULL)) {
  7013. return 0;
  7014. }
  7015. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7016. if (strlen(response) != 32) {
  7017. return 0;
  7018. }
  7019. mg_md5(ha2, method, ":", uri, NULL);
  7020. mg_md5(expected_response,
  7021. ha1,
  7022. ":",
  7023. nonce,
  7024. ":",
  7025. nc,
  7026. ":",
  7027. cnonce,
  7028. ":",
  7029. qop,
  7030. ":",
  7031. ha2,
  7032. NULL);
  7033. return mg_strcasecmp(response, expected_response) == 0;
  7034. }
  7035. #if !defined(NO_FILESYSTEMS)
  7036. /* Use the global passwords file, if specified by auth_gpass option,
  7037. * or search for .htpasswd in the requested directory. */
  7038. static void
  7039. open_auth_file(struct mg_connection *conn,
  7040. const char *path,
  7041. struct mg_file *filep)
  7042. {
  7043. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7044. char name[UTF8_PATH_MAX];
  7045. const char *p, *e,
  7046. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7047. int truncated;
  7048. if (gpass != NULL) {
  7049. /* Use global passwords file */
  7050. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7051. #if defined(DEBUG)
  7052. /* Use mg_cry_internal here, since gpass has been
  7053. * configured. */
  7054. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7055. #endif
  7056. }
  7057. /* Important: using local struct mg_file to test path for
  7058. * is_directory flag. If filep is used, mg_stat() makes it
  7059. * appear as if auth file was opened.
  7060. * TODO(mid): Check if this is still required after rewriting
  7061. * mg_stat */
  7062. } else if (mg_stat(conn, path, &filep->stat)
  7063. && filep->stat.is_directory) {
  7064. mg_snprintf(conn,
  7065. &truncated,
  7066. name,
  7067. sizeof(name),
  7068. "%s/%s",
  7069. path,
  7070. PASSWORDS_FILE_NAME);
  7071. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7072. #if defined(DEBUG)
  7073. /* Don't use mg_cry_internal here, but only a trace, since
  7074. * this is a typical case. It will occur for every directory
  7075. * without a password file. */
  7076. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7077. #endif
  7078. }
  7079. } else {
  7080. /* Try to find .htpasswd in requested directory. */
  7081. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7082. if (e[0] == '/') {
  7083. break;
  7084. }
  7085. }
  7086. mg_snprintf(conn,
  7087. &truncated,
  7088. name,
  7089. sizeof(name),
  7090. "%.*s/%s",
  7091. (int)(e - p),
  7092. p,
  7093. PASSWORDS_FILE_NAME);
  7094. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7095. #if defined(DEBUG)
  7096. /* Don't use mg_cry_internal here, but only a trace, since
  7097. * this is a typical case. It will occur for every directory
  7098. * without a password file. */
  7099. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7100. #endif
  7101. }
  7102. }
  7103. }
  7104. }
  7105. #endif /* NO_FILESYSTEMS */
  7106. /* Parsed Authorization header */
  7107. struct ah {
  7108. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7109. };
  7110. /* Return 1 on success. Always initializes the ah structure. */
  7111. static int
  7112. parse_auth_header(struct mg_connection *conn,
  7113. char *buf,
  7114. size_t buf_size,
  7115. struct ah *ah)
  7116. {
  7117. char *name, *value, *s;
  7118. const char *auth_header;
  7119. uint64_t nonce;
  7120. if (!ah || !conn) {
  7121. return 0;
  7122. }
  7123. (void)memset(ah, 0, sizeof(*ah));
  7124. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7125. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7126. return 0;
  7127. }
  7128. /* Make modifiable copy of the auth header */
  7129. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7130. s = buf;
  7131. /* Parse authorization header */
  7132. for (;;) {
  7133. /* Gobble initial spaces */
  7134. while (isspace((unsigned char)*s)) {
  7135. s++;
  7136. }
  7137. name = skip_quoted(&s, "=", " ", 0);
  7138. /* Value is either quote-delimited, or ends at first comma or space.
  7139. */
  7140. if (s[0] == '\"') {
  7141. s++;
  7142. value = skip_quoted(&s, "\"", " ", '\\');
  7143. if (s[0] == ',') {
  7144. s++;
  7145. }
  7146. } else {
  7147. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7148. * uses spaces */
  7149. }
  7150. if (*name == '\0') {
  7151. break;
  7152. }
  7153. if (!strcmp(name, "username")) {
  7154. ah->user = value;
  7155. } else if (!strcmp(name, "cnonce")) {
  7156. ah->cnonce = value;
  7157. } else if (!strcmp(name, "response")) {
  7158. ah->response = value;
  7159. } else if (!strcmp(name, "uri")) {
  7160. ah->uri = value;
  7161. } else if (!strcmp(name, "qop")) {
  7162. ah->qop = value;
  7163. } else if (!strcmp(name, "nc")) {
  7164. ah->nc = value;
  7165. } else if (!strcmp(name, "nonce")) {
  7166. ah->nonce = value;
  7167. }
  7168. }
  7169. #if !defined(NO_NONCE_CHECK)
  7170. /* Read the nonce from the response. */
  7171. if (ah->nonce == NULL) {
  7172. return 0;
  7173. }
  7174. s = NULL;
  7175. nonce = strtoull(ah->nonce, &s, 10);
  7176. if ((s == NULL) || (*s != 0)) {
  7177. return 0;
  7178. }
  7179. /* Convert the nonce from the client to a number. */
  7180. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7181. /* The converted number corresponds to the time the nounce has been
  7182. * created. This should not be earlier than the server start. */
  7183. /* Server side nonce check is valuable in all situations but one:
  7184. * if the server restarts frequently, but the client should not see
  7185. * that, so the server should accept nonces from previous starts. */
  7186. /* However, the reasonable default is to not accept a nonce from a
  7187. * previous start, so if anyone changed the access rights between
  7188. * two restarts, a new login is required. */
  7189. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7190. /* nonce is from a previous start of the server and no longer valid
  7191. * (replay attack?) */
  7192. return 0;
  7193. }
  7194. /* Check if the nonce is too high, so it has not (yet) been used by the
  7195. * server. */
  7196. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7197. + conn->dom_ctx->nonce_count)) {
  7198. return 0;
  7199. }
  7200. #else
  7201. (void)nonce;
  7202. #endif
  7203. /* CGI needs it as REMOTE_USER */
  7204. if (ah->user != NULL) {
  7205. conn->request_info.remote_user =
  7206. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7207. } else {
  7208. return 0;
  7209. }
  7210. return 1;
  7211. }
  7212. static const char *
  7213. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7214. {
  7215. if (!filep) {
  7216. return NULL;
  7217. }
  7218. if (filep->access.fp != NULL) {
  7219. return fgets(buf, (int)size, filep->access.fp);
  7220. } else {
  7221. return NULL;
  7222. }
  7223. }
  7224. /* Define the initial recursion depth for procesesing htpasswd files that
  7225. * include other htpasswd
  7226. * (or even the same) files. It is not difficult to provide a file or files
  7227. * s.t. they force civetweb
  7228. * to infinitely recurse and then crash.
  7229. */
  7230. #define INITIAL_DEPTH 9
  7231. #if INITIAL_DEPTH <= 0
  7232. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7233. #endif
  7234. #if !defined(NO_FILESYSTEMS)
  7235. struct read_auth_file_struct {
  7236. struct mg_connection *conn;
  7237. struct ah ah;
  7238. const char *domain;
  7239. char buf[256 + 256 + 40];
  7240. const char *f_user;
  7241. const char *f_domain;
  7242. const char *f_ha1;
  7243. };
  7244. static int
  7245. read_auth_file(struct mg_file *filep,
  7246. struct read_auth_file_struct *workdata,
  7247. int depth)
  7248. {
  7249. int is_authorized = 0;
  7250. struct mg_file fp;
  7251. size_t l;
  7252. if (!filep || !workdata || (0 == depth)) {
  7253. return 0;
  7254. }
  7255. /* Loop over passwords file */
  7256. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7257. l = strlen(workdata->buf);
  7258. while (l > 0) {
  7259. if (isspace((unsigned char)workdata->buf[l - 1])
  7260. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7261. l--;
  7262. workdata->buf[l] = 0;
  7263. } else
  7264. break;
  7265. }
  7266. if (l < 1) {
  7267. continue;
  7268. }
  7269. workdata->f_user = workdata->buf;
  7270. if (workdata->f_user[0] == ':') {
  7271. /* user names may not contain a ':' and may not be empty,
  7272. * so lines starting with ':' may be used for a special purpose
  7273. */
  7274. if (workdata->f_user[1] == '#') {
  7275. /* :# is a comment */
  7276. continue;
  7277. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7278. if (mg_fopen(workdata->conn,
  7279. workdata->f_user + 9,
  7280. MG_FOPEN_MODE_READ,
  7281. &fp)) {
  7282. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7283. (void)mg_fclose(
  7284. &fp.access); /* ignore error on read only file */
  7285. /* No need to continue processing files once we have a
  7286. * match, since nothing will reset it back
  7287. * to 0.
  7288. */
  7289. if (is_authorized) {
  7290. return is_authorized;
  7291. }
  7292. } else {
  7293. mg_cry_internal(workdata->conn,
  7294. "%s: cannot open authorization file: %s",
  7295. __func__,
  7296. workdata->buf);
  7297. }
  7298. continue;
  7299. }
  7300. /* everything is invalid for the moment (might change in the
  7301. * future) */
  7302. mg_cry_internal(workdata->conn,
  7303. "%s: syntax error in authorization file: %s",
  7304. __func__,
  7305. workdata->buf);
  7306. continue;
  7307. }
  7308. workdata->f_domain = strchr(workdata->f_user, ':');
  7309. if (workdata->f_domain == NULL) {
  7310. mg_cry_internal(workdata->conn,
  7311. "%s: syntax error in authorization file: %s",
  7312. __func__,
  7313. workdata->buf);
  7314. continue;
  7315. }
  7316. *(char *)(workdata->f_domain) = 0;
  7317. (workdata->f_domain)++;
  7318. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7319. if (workdata->f_ha1 == NULL) {
  7320. mg_cry_internal(workdata->conn,
  7321. "%s: syntax error in authorization file: %s",
  7322. __func__,
  7323. workdata->buf);
  7324. continue;
  7325. }
  7326. *(char *)(workdata->f_ha1) = 0;
  7327. (workdata->f_ha1)++;
  7328. if (!strcmp(workdata->ah.user, workdata->f_user)
  7329. && !strcmp(workdata->domain, workdata->f_domain)) {
  7330. return check_password(workdata->conn->request_info.request_method,
  7331. workdata->f_ha1,
  7332. workdata->ah.uri,
  7333. workdata->ah.nonce,
  7334. workdata->ah.nc,
  7335. workdata->ah.cnonce,
  7336. workdata->ah.qop,
  7337. workdata->ah.response);
  7338. }
  7339. }
  7340. return is_authorized;
  7341. }
  7342. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7343. static int
  7344. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7345. {
  7346. struct read_auth_file_struct workdata;
  7347. char buf[MG_BUF_LEN];
  7348. if (!conn || !conn->dom_ctx) {
  7349. return 0;
  7350. }
  7351. memset(&workdata, 0, sizeof(workdata));
  7352. workdata.conn = conn;
  7353. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7354. return 0;
  7355. }
  7356. if (realm) {
  7357. workdata.domain = realm;
  7358. } else {
  7359. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7360. }
  7361. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7362. }
  7363. /* Public function to check http digest authentication header */
  7364. int
  7365. mg_check_digest_access_authentication(struct mg_connection *conn,
  7366. const char *realm,
  7367. const char *filename)
  7368. {
  7369. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7370. int auth;
  7371. if (!conn || !filename) {
  7372. return -1;
  7373. }
  7374. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7375. return -2;
  7376. }
  7377. auth = authorize(conn, &file, realm);
  7378. mg_fclose(&file.access);
  7379. return auth;
  7380. }
  7381. #endif /* NO_FILESYSTEMS */
  7382. /* Return 1 if request is authorised, 0 otherwise. */
  7383. static int
  7384. check_authorization(struct mg_connection *conn, const char *path)
  7385. {
  7386. #if !defined(NO_FILESYSTEMS)
  7387. char fname[UTF8_PATH_MAX];
  7388. struct vec uri_vec, filename_vec;
  7389. const char *list;
  7390. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7391. int authorized = 1, truncated;
  7392. if (!conn || !conn->dom_ctx) {
  7393. return 0;
  7394. }
  7395. list = conn->dom_ctx->config[PROTECT_URI];
  7396. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7397. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7398. mg_snprintf(conn,
  7399. &truncated,
  7400. fname,
  7401. sizeof(fname),
  7402. "%.*s",
  7403. (int)filename_vec.len,
  7404. filename_vec.ptr);
  7405. if (truncated
  7406. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7407. mg_cry_internal(conn,
  7408. "%s: cannot open %s: %s",
  7409. __func__,
  7410. fname,
  7411. strerror(errno));
  7412. }
  7413. break;
  7414. }
  7415. }
  7416. if (!is_file_opened(&file.access)) {
  7417. open_auth_file(conn, path, &file);
  7418. }
  7419. if (is_file_opened(&file.access)) {
  7420. authorized = authorize(conn, &file, NULL);
  7421. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7422. }
  7423. return authorized;
  7424. #else
  7425. (void)conn;
  7426. (void)path;
  7427. return 1;
  7428. #endif /* NO_FILESYSTEMS */
  7429. }
  7430. /* Internal function. Assumes conn is valid */
  7431. static void
  7432. send_authorization_request(struct mg_connection *conn, const char *realm)
  7433. {
  7434. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7435. int trunc = 0;
  7436. char buf[128];
  7437. if (!realm) {
  7438. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7439. }
  7440. mg_lock_context(conn->phys_ctx);
  7441. nonce += conn->dom_ctx->nonce_count;
  7442. ++conn->dom_ctx->nonce_count;
  7443. mg_unlock_context(conn->phys_ctx);
  7444. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7445. conn->must_close = 1;
  7446. /* Create 401 response */
  7447. mg_response_header_start(conn, 401);
  7448. send_no_cache_header(conn);
  7449. send_additional_header(conn);
  7450. mg_response_header_add(conn, "Content-Length", "0", -1);
  7451. /* Content for "WWW-Authenticate" header */
  7452. mg_snprintf(conn,
  7453. &trunc,
  7454. buf,
  7455. sizeof(buf),
  7456. "Digest qop=\"auth\", realm=\"%s\", "
  7457. "nonce=\"%" UINT64_FMT "\"",
  7458. realm,
  7459. nonce);
  7460. if (!trunc) {
  7461. /* !trunc should always be true */
  7462. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7463. }
  7464. /* Send all headers */
  7465. mg_response_header_send(conn);
  7466. }
  7467. /* Interface function. Parameters are provided by the user, so do
  7468. * at least some basic checks.
  7469. */
  7470. int
  7471. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7472. const char *realm)
  7473. {
  7474. if (conn && conn->dom_ctx) {
  7475. send_authorization_request(conn, realm);
  7476. return 0;
  7477. }
  7478. return -1;
  7479. }
  7480. #if !defined(NO_FILES)
  7481. static int
  7482. is_authorized_for_put(struct mg_connection *conn)
  7483. {
  7484. if (conn) {
  7485. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7486. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7487. int ret = 0;
  7488. if (passfile != NULL
  7489. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7490. ret = authorize(conn, &file, NULL);
  7491. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7492. }
  7493. return ret;
  7494. }
  7495. return 0;
  7496. }
  7497. #endif
  7498. static int
  7499. modify_passwords_file(const char *fname,
  7500. const char *domain,
  7501. const char *user,
  7502. const char *pass,
  7503. const char *ha1)
  7504. {
  7505. int found, i;
  7506. char line[512], u[512] = "", d[512] = "", ha1buf[33],
  7507. tmp[UTF8_PATH_MAX + 8];
  7508. FILE *fp, *fp2;
  7509. found = 0;
  7510. fp = fp2 = NULL;
  7511. /* Regard empty password as no password - remove user record. */
  7512. if ((pass != NULL) && (pass[0] == '\0')) {
  7513. pass = NULL;
  7514. }
  7515. /* Other arguments must not be empty */
  7516. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7517. return 0;
  7518. }
  7519. /* Using the given file format, user name and domain must not contain
  7520. * ':'
  7521. */
  7522. if (strchr(user, ':') != NULL) {
  7523. return 0;
  7524. }
  7525. if (strchr(domain, ':') != NULL) {
  7526. return 0;
  7527. }
  7528. /* Do not allow control characters like newline in user name and domain.
  7529. * Do not allow excessively long names either. */
  7530. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7531. if (iscntrl((unsigned char)user[i])) {
  7532. return 0;
  7533. }
  7534. }
  7535. if (user[i]) {
  7536. return 0;
  7537. }
  7538. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7539. if (iscntrl((unsigned char)domain[i])) {
  7540. return 0;
  7541. }
  7542. }
  7543. if (domain[i]) {
  7544. return 0;
  7545. }
  7546. /* The maximum length of the path to the password file is limited */
  7547. if ((strlen(fname) + strlen(MODIFY_PASSWORD_TEMP_EXT)) >= UTF8_PATH_MAX) {
  7548. return 0;
  7549. }
  7550. /* Create a temporary file name. Length has been checked before. */
  7551. strcpy(tmp, fname);
  7552. strcat(tmp, MODIFY_PASSWORD_TEMP_EXT);
  7553. /* Create the file if does not exist */
  7554. /* Use of fopen here is OK, since fname is only ASCII */
  7555. if ((fp = fopen(fname, "a+")) != NULL) {
  7556. (void)fclose(fp);
  7557. }
  7558. /* Open the given file and temporary file */
  7559. if ((fp = fopen(fname, "r")) == NULL) {
  7560. return 0;
  7561. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7562. fclose(fp);
  7563. return 0;
  7564. }
  7565. /* Copy the stuff to temporary file */
  7566. while (fgets(line, sizeof(line), fp) != NULL) {
  7567. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7568. continue;
  7569. }
  7570. u[255] = 0;
  7571. d[255] = 0;
  7572. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7573. found++;
  7574. if (pass != NULL) {
  7575. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7576. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
  7577. } else if (ha1 != NULL) {
  7578. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7579. }
  7580. } else {
  7581. fprintf(fp2, "%s", line);
  7582. }
  7583. }
  7584. /* If new user, just add it */
  7585. if (!found) {
  7586. if (pass != NULL) {
  7587. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7588. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1buf);
  7589. } else if (ha1 != NULL) {
  7590. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7591. }
  7592. }
  7593. /* Close files */
  7594. fclose(fp);
  7595. fclose(fp2);
  7596. /* Put the temp file in place of real file */
  7597. IGNORE_UNUSED_RESULT(remove(fname));
  7598. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7599. return 1;
  7600. }
  7601. int
  7602. mg_modify_passwords_file(const char *fname,
  7603. const char *domain,
  7604. const char *user,
  7605. const char *pass)
  7606. {
  7607. return modify_passwords_file(fname, domain, user, pass, NULL);
  7608. }
  7609. int
  7610. mg_modify_passwords_file_ha1(const char *fname,
  7611. const char *domain,
  7612. const char *user,
  7613. const char *ha1)
  7614. {
  7615. return modify_passwords_file(fname, domain, user, NULL, ha1);
  7616. }
  7617. static int
  7618. is_valid_port(unsigned long port)
  7619. {
  7620. return (port <= 0xffff);
  7621. }
  7622. static int
  7623. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7624. {
  7625. struct addrinfo hints, *res, *ressave;
  7626. int func_ret = 0;
  7627. int gai_ret;
  7628. memset(&hints, 0, sizeof(struct addrinfo));
  7629. hints.ai_family = af;
  7630. if (!resolve_src) {
  7631. hints.ai_flags = AI_NUMERICHOST;
  7632. }
  7633. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7634. if (gai_ret != 0) {
  7635. /* gai_strerror could be used to convert gai_ret to a string */
  7636. /* POSIX return values: see
  7637. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7638. */
  7639. /* Windows return values: see
  7640. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7641. */
  7642. return 0;
  7643. }
  7644. ressave = res;
  7645. while (res) {
  7646. if ((dstlen >= (size_t)res->ai_addrlen)
  7647. && (res->ai_addr->sa_family == af)) {
  7648. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7649. func_ret = 1;
  7650. }
  7651. res = res->ai_next;
  7652. }
  7653. freeaddrinfo(ressave);
  7654. return func_ret;
  7655. }
  7656. static int
  7657. connect_socket(
  7658. struct mg_context *ctx /* may be NULL */,
  7659. const char *host,
  7660. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7661. int use_ssl, /* 0 or 1 */
  7662. char *ebuf,
  7663. size_t ebuf_len,
  7664. SOCKET *sock /* output: socket, must not be NULL */,
  7665. union usa *sa /* output: socket address, must not be NULL */
  7666. )
  7667. {
  7668. int ip_ver = 0;
  7669. int conn_ret = -1;
  7670. int sockerr = 0;
  7671. *sock = INVALID_SOCKET;
  7672. memset(sa, 0, sizeof(*sa));
  7673. if (ebuf_len > 0) {
  7674. *ebuf = 0;
  7675. }
  7676. if (host == NULL) {
  7677. mg_snprintf(NULL,
  7678. NULL, /* No truncation check for ebuf */
  7679. ebuf,
  7680. ebuf_len,
  7681. "%s",
  7682. "NULL host");
  7683. return 0;
  7684. }
  7685. #if defined(USE_X_DOM_SOCKET)
  7686. if (port == -99) {
  7687. /* Unix domain socket */
  7688. size_t hostlen = strlen(host);
  7689. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7690. mg_snprintf(NULL,
  7691. NULL, /* No truncation check for ebuf */
  7692. ebuf,
  7693. ebuf_len,
  7694. "%s",
  7695. "host length exceeds limit");
  7696. return 0;
  7697. }
  7698. } else
  7699. #endif
  7700. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7701. mg_snprintf(NULL,
  7702. NULL, /* No truncation check for ebuf */
  7703. ebuf,
  7704. ebuf_len,
  7705. "%s",
  7706. "invalid port");
  7707. return 0;
  7708. }
  7709. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7710. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7711. if (use_ssl && (TLS_client_method == NULL)) {
  7712. mg_snprintf(NULL,
  7713. NULL, /* No truncation check for ebuf */
  7714. ebuf,
  7715. ebuf_len,
  7716. "%s",
  7717. "SSL is not initialized");
  7718. return 0;
  7719. }
  7720. #else
  7721. if (use_ssl && (SSLv23_client_method == NULL)) {
  7722. mg_snprintf(NULL,
  7723. NULL, /* No truncation check for ebuf */
  7724. ebuf,
  7725. ebuf_len,
  7726. "%s",
  7727. "SSL is not initialized");
  7728. return 0;
  7729. }
  7730. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7731. #else
  7732. (void)use_ssl;
  7733. #endif /* NO SSL */
  7734. #if defined(USE_X_DOM_SOCKET)
  7735. if (port == -99) {
  7736. size_t hostlen = strlen(host);
  7737. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7738. ip_ver = -99;
  7739. sa->sun.sun_family = AF_UNIX;
  7740. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7741. memcpy(sa->sun.sun_path, host, hostlen);
  7742. } else
  7743. #endif
  7744. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7745. sa->sin.sin_port = htons((uint16_t)port);
  7746. ip_ver = 4;
  7747. #if defined(USE_IPV6)
  7748. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7749. sa->sin6.sin6_port = htons((uint16_t)port);
  7750. ip_ver = 6;
  7751. } else if (host[0] == '[') {
  7752. /* While getaddrinfo on Windows will work with [::1],
  7753. * getaddrinfo on Linux only works with ::1 (without []). */
  7754. size_t l = strlen(host + 1);
  7755. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7756. if (h) {
  7757. h[l - 1] = 0;
  7758. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7759. sa->sin6.sin6_port = htons((uint16_t)port);
  7760. ip_ver = 6;
  7761. }
  7762. mg_free(h);
  7763. }
  7764. #endif
  7765. }
  7766. if (ip_ver == 0) {
  7767. mg_snprintf(NULL,
  7768. NULL, /* No truncation check for ebuf */
  7769. ebuf,
  7770. ebuf_len,
  7771. "%s",
  7772. "host not found");
  7773. return 0;
  7774. }
  7775. if (ip_ver == 4) {
  7776. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7777. }
  7778. #if defined(USE_IPV6)
  7779. else if (ip_ver == 6) {
  7780. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7781. }
  7782. #endif
  7783. #if defined(USE_X_DOM_SOCKET)
  7784. else if (ip_ver == -99) {
  7785. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7786. }
  7787. #endif
  7788. if (*sock == INVALID_SOCKET) {
  7789. mg_snprintf(NULL,
  7790. NULL, /* No truncation check for ebuf */
  7791. ebuf,
  7792. ebuf_len,
  7793. "socket(): %s",
  7794. strerror(ERRNO));
  7795. return 0;
  7796. }
  7797. if (0 != set_non_blocking_mode(*sock)) {
  7798. mg_snprintf(NULL,
  7799. NULL, /* No truncation check for ebuf */
  7800. ebuf,
  7801. ebuf_len,
  7802. "Cannot set socket to non-blocking: %s",
  7803. strerror(ERRNO));
  7804. closesocket(*sock);
  7805. *sock = INVALID_SOCKET;
  7806. return 0;
  7807. }
  7808. set_close_on_exec(*sock, NULL, ctx);
  7809. if (ip_ver == 4) {
  7810. /* connected with IPv4 */
  7811. conn_ret = connect(*sock,
  7812. (struct sockaddr *)((void *)&sa->sin),
  7813. sizeof(sa->sin));
  7814. }
  7815. #if defined(USE_IPV6)
  7816. else if (ip_ver == 6) {
  7817. /* connected with IPv6 */
  7818. conn_ret = connect(*sock,
  7819. (struct sockaddr *)((void *)&sa->sin6),
  7820. sizeof(sa->sin6));
  7821. }
  7822. #endif
  7823. #if defined(USE_X_DOM_SOCKET)
  7824. else if (ip_ver == -99) {
  7825. /* connected to domain socket */
  7826. conn_ret = connect(*sock,
  7827. (struct sockaddr *)((void *)&sa->sun),
  7828. sizeof(sa->sun));
  7829. }
  7830. #endif
  7831. if (conn_ret != 0) {
  7832. sockerr = ERRNO;
  7833. }
  7834. #if defined(_WIN32)
  7835. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7836. #else
  7837. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7838. #endif
  7839. /* Data for getsockopt */
  7840. void *psockerr = &sockerr;
  7841. int ret;
  7842. #if defined(_WIN32)
  7843. int len = (int)sizeof(sockerr);
  7844. #else
  7845. socklen_t len = (socklen_t)sizeof(sockerr);
  7846. #endif
  7847. /* Data for poll */
  7848. struct mg_pollfd pfd[1];
  7849. int pollres;
  7850. int ms_wait = 10000; /* 10 second timeout */
  7851. stop_flag_t nonstop;
  7852. STOP_FLAG_ASSIGN(&nonstop, 0);
  7853. /* For a non-blocking socket, the connect sequence is:
  7854. * 1) call connect (will not block)
  7855. * 2) wait until the socket is ready for writing (select or poll)
  7856. * 3) check connection state with getsockopt
  7857. */
  7858. pfd[0].fd = *sock;
  7859. pfd[0].events = POLLOUT;
  7860. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7861. if (pollres != 1) {
  7862. /* Not connected */
  7863. mg_snprintf(NULL,
  7864. NULL, /* No truncation check for ebuf */
  7865. ebuf,
  7866. ebuf_len,
  7867. "connect(%s:%d): timeout",
  7868. host,
  7869. port);
  7870. closesocket(*sock);
  7871. *sock = INVALID_SOCKET;
  7872. return 0;
  7873. }
  7874. #if defined(_WIN32)
  7875. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7876. #else
  7877. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7878. #endif
  7879. if ((ret == 0) && (sockerr == 0)) {
  7880. conn_ret = 0;
  7881. }
  7882. }
  7883. if (conn_ret != 0) {
  7884. /* Not connected */
  7885. mg_snprintf(NULL,
  7886. NULL, /* No truncation check for ebuf */
  7887. ebuf,
  7888. ebuf_len,
  7889. "connect(%s:%d): error %s",
  7890. host,
  7891. port,
  7892. strerror(sockerr));
  7893. closesocket(*sock);
  7894. *sock = INVALID_SOCKET;
  7895. return 0;
  7896. }
  7897. return 1;
  7898. }
  7899. int
  7900. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7901. {
  7902. static const char *dont_escape = "._-$,;~()";
  7903. static const char *hex = "0123456789abcdef";
  7904. char *pos = dst;
  7905. const char *end = dst + dst_len - 1;
  7906. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7907. if (isalnum((unsigned char)*src)
  7908. || (strchr(dont_escape, *src) != NULL)) {
  7909. *pos = *src;
  7910. } else if (pos + 2 < end) {
  7911. pos[0] = '%';
  7912. pos[1] = hex[(unsigned char)*src >> 4];
  7913. pos[2] = hex[(unsigned char)*src & 0xf];
  7914. pos += 2;
  7915. } else {
  7916. break;
  7917. }
  7918. }
  7919. *pos = '\0';
  7920. return (*src == '\0') ? (int)(pos - dst) : -1;
  7921. }
  7922. /* Return 0 on success, non-zero if an error occurs. */
  7923. static int
  7924. print_dir_entry(struct de *de)
  7925. {
  7926. size_t namesize, escsize, i;
  7927. char *href, *esc, *p;
  7928. char size[64], mod[64];
  7929. #if defined(REENTRANT_TIME)
  7930. struct tm _tm;
  7931. struct tm *tm = &_tm;
  7932. #else
  7933. struct tm *tm;
  7934. #endif
  7935. /* Estimate worst case size for encoding and escaping */
  7936. namesize = strlen(de->file_name) + 1;
  7937. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7938. href = (char *)mg_malloc(namesize * 3 + escsize);
  7939. if (href == NULL) {
  7940. return -1;
  7941. }
  7942. mg_url_encode(de->file_name, href, namesize * 3);
  7943. esc = NULL;
  7944. if (escsize > 0) {
  7945. /* HTML escaping needed */
  7946. esc = href + namesize * 3;
  7947. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7948. mg_strlcpy(p, de->file_name + i, 2);
  7949. if (*p == '&') {
  7950. strcpy(p, "&amp;");
  7951. } else if (*p == '<') {
  7952. strcpy(p, "&lt;");
  7953. } else if (*p == '>') {
  7954. strcpy(p, "&gt;");
  7955. }
  7956. }
  7957. }
  7958. if (de->file.is_directory) {
  7959. mg_snprintf(de->conn,
  7960. NULL, /* Buffer is big enough */
  7961. size,
  7962. sizeof(size),
  7963. "%s",
  7964. "[DIRECTORY]");
  7965. } else {
  7966. /* We use (signed) cast below because MSVC 6 compiler cannot
  7967. * convert unsigned __int64 to double. Sigh. */
  7968. if (de->file.size < 1024) {
  7969. mg_snprintf(de->conn,
  7970. NULL, /* Buffer is big enough */
  7971. size,
  7972. sizeof(size),
  7973. "%d",
  7974. (int)de->file.size);
  7975. } else if (de->file.size < 0x100000) {
  7976. mg_snprintf(de->conn,
  7977. NULL, /* Buffer is big enough */
  7978. size,
  7979. sizeof(size),
  7980. "%.1fk",
  7981. (double)de->file.size / 1024.0);
  7982. } else if (de->file.size < 0x40000000) {
  7983. mg_snprintf(de->conn,
  7984. NULL, /* Buffer is big enough */
  7985. size,
  7986. sizeof(size),
  7987. "%.1fM",
  7988. (double)de->file.size / 1048576);
  7989. } else {
  7990. mg_snprintf(de->conn,
  7991. NULL, /* Buffer is big enough */
  7992. size,
  7993. sizeof(size),
  7994. "%.1fG",
  7995. (double)de->file.size / 1073741824);
  7996. }
  7997. }
  7998. /* Note: mg_snprintf will not cause a buffer overflow above.
  7999. * So, string truncation checks are not required here. */
  8000. #if defined(REENTRANT_TIME)
  8001. localtime_r(&de->file.last_modified, tm);
  8002. #else
  8003. tm = localtime(&de->file.last_modified);
  8004. #endif
  8005. if (tm != NULL) {
  8006. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8007. } else {
  8008. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8009. mod[sizeof(mod) - 1] = '\0';
  8010. }
  8011. mg_printf(de->conn,
  8012. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8013. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8014. href,
  8015. de->file.is_directory ? "/" : "",
  8016. esc ? esc : de->file_name,
  8017. de->file.is_directory ? "/" : "",
  8018. mod,
  8019. size);
  8020. mg_free(href);
  8021. return 0;
  8022. }
  8023. /* This function is called from send_directory() and used for
  8024. * sorting directory entries by size, or name, or modification time.
  8025. * On windows, __cdecl specification is needed in case if project is built
  8026. * with __stdcall convention. qsort always requires __cdels callback. */
  8027. static int WINCDECL
  8028. compare_dir_entries(const void *p1, const void *p2)
  8029. {
  8030. if (p1 && p2) {
  8031. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8032. const char *query_string = a->conn->request_info.query_string;
  8033. int cmp_result = 0;
  8034. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8035. query_string = "n";
  8036. }
  8037. if (a->file.is_directory && !b->file.is_directory) {
  8038. return -1; /* Always put directories on top */
  8039. } else if (!a->file.is_directory && b->file.is_directory) {
  8040. return 1; /* Always put directories on top */
  8041. } else if (*query_string == 'n') {
  8042. cmp_result = strcmp(a->file_name, b->file_name);
  8043. } else if (*query_string == 's') {
  8044. cmp_result = (a->file.size == b->file.size)
  8045. ? 0
  8046. : ((a->file.size > b->file.size) ? 1 : -1);
  8047. } else if (*query_string == 'd') {
  8048. cmp_result =
  8049. (a->file.last_modified == b->file.last_modified)
  8050. ? 0
  8051. : ((a->file.last_modified > b->file.last_modified) ? 1
  8052. : -1);
  8053. }
  8054. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8055. }
  8056. return 0;
  8057. }
  8058. static int
  8059. must_hide_file(struct mg_connection *conn, const char *path)
  8060. {
  8061. if (conn && conn->dom_ctx) {
  8062. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8063. const char *pw_temp_pattern = "**" MODIFY_PASSWORD_TEMP_EXT "$";
  8064. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8065. return (match_prefix_strlen(pw_pattern, path) > 0)
  8066. || (match_prefix_strlen(pw_temp_pattern, path) > 0)
  8067. || (match_prefix_strlen(pattern, path) > 0);
  8068. }
  8069. return 0;
  8070. }
  8071. #if !defined(NO_FILESYSTEMS)
  8072. static int
  8073. scan_directory(struct mg_connection *conn,
  8074. const char *dir,
  8075. void *data,
  8076. int (*cb)(struct de *, void *))
  8077. {
  8078. char path[UTF8_PATH_MAX];
  8079. struct dirent *dp;
  8080. DIR *dirp;
  8081. struct de de;
  8082. int truncated;
  8083. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8084. return 0;
  8085. } else {
  8086. de.conn = conn;
  8087. while ((dp = mg_readdir(dirp)) != NULL) {
  8088. /* Do not show current dir and hidden files */
  8089. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8090. || must_hide_file(conn, dp->d_name)) {
  8091. continue;
  8092. }
  8093. mg_snprintf(
  8094. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8095. /* If we don't memset stat structure to zero, mtime will have
  8096. * garbage and strftime() will segfault later on in
  8097. * print_dir_entry(). memset is required only if mg_stat()
  8098. * fails. For more details, see
  8099. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8100. memset(&de.file, 0, sizeof(de.file));
  8101. if (truncated) {
  8102. /* If the path is not complete, skip processing. */
  8103. continue;
  8104. }
  8105. if (!mg_stat(conn, path, &de.file)) {
  8106. mg_cry_internal(conn,
  8107. "%s: mg_stat(%s) failed: %s",
  8108. __func__,
  8109. path,
  8110. strerror(ERRNO));
  8111. }
  8112. de.file_name = dp->d_name;
  8113. if (cb(&de, data)) {
  8114. /* stopped */
  8115. break;
  8116. }
  8117. }
  8118. (void)mg_closedir(dirp);
  8119. }
  8120. return 1;
  8121. }
  8122. #endif /* NO_FILESYSTEMS */
  8123. #if !defined(NO_FILES)
  8124. static int
  8125. remove_directory(struct mg_connection *conn, const char *dir)
  8126. {
  8127. char path[UTF8_PATH_MAX];
  8128. struct dirent *dp;
  8129. DIR *dirp;
  8130. struct de de;
  8131. int truncated;
  8132. int ok = 1;
  8133. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8134. return 0;
  8135. } else {
  8136. de.conn = conn;
  8137. while ((dp = mg_readdir(dirp)) != NULL) {
  8138. /* Do not show current dir (but show hidden files as they will
  8139. * also be removed) */
  8140. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8141. continue;
  8142. }
  8143. mg_snprintf(
  8144. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8145. /* If we don't memset stat structure to zero, mtime will have
  8146. * garbage and strftime() will segfault later on in
  8147. * print_dir_entry(). memset is required only if mg_stat()
  8148. * fails. For more details, see
  8149. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8150. memset(&de.file, 0, sizeof(de.file));
  8151. if (truncated) {
  8152. /* Do not delete anything shorter */
  8153. ok = 0;
  8154. continue;
  8155. }
  8156. if (!mg_stat(conn, path, &de.file)) {
  8157. mg_cry_internal(conn,
  8158. "%s: mg_stat(%s) failed: %s",
  8159. __func__,
  8160. path,
  8161. strerror(ERRNO));
  8162. ok = 0;
  8163. }
  8164. if (de.file.is_directory) {
  8165. if (remove_directory(conn, path) == 0) {
  8166. ok = 0;
  8167. }
  8168. } else {
  8169. /* This will fail file is the file is in memory */
  8170. if (mg_remove(conn, path) == 0) {
  8171. ok = 0;
  8172. }
  8173. }
  8174. }
  8175. (void)mg_closedir(dirp);
  8176. IGNORE_UNUSED_RESULT(rmdir(dir));
  8177. }
  8178. return ok;
  8179. }
  8180. #endif
  8181. struct dir_scan_data {
  8182. struct de *entries;
  8183. size_t num_entries;
  8184. size_t arr_size;
  8185. };
  8186. #if !defined(NO_FILESYSTEMS)
  8187. static int
  8188. dir_scan_callback(struct de *de, void *data)
  8189. {
  8190. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8191. struct de *entries = dsd->entries;
  8192. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8193. /* Here "entries" is a temporary pointer and can be replaced,
  8194. * "dsd->entries" is the original pointer */
  8195. entries =
  8196. (struct de *)mg_realloc(entries,
  8197. dsd->arr_size * 2 * sizeof(entries[0]));
  8198. if (entries == NULL) {
  8199. /* stop scan */
  8200. return 1;
  8201. }
  8202. dsd->entries = entries;
  8203. dsd->arr_size *= 2;
  8204. }
  8205. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8206. if (entries[dsd->num_entries].file_name == NULL) {
  8207. /* stop scan */
  8208. return 1;
  8209. }
  8210. entries[dsd->num_entries].file = de->file;
  8211. entries[dsd->num_entries].conn = de->conn;
  8212. dsd->num_entries++;
  8213. return 0;
  8214. }
  8215. static void
  8216. handle_directory_request(struct mg_connection *conn, const char *dir)
  8217. {
  8218. size_t i;
  8219. int sort_direction;
  8220. struct dir_scan_data data = {NULL, 0, 128};
  8221. char date[64], *esc, *p;
  8222. const char *title;
  8223. time_t curtime = time(NULL);
  8224. if (!conn) {
  8225. return;
  8226. }
  8227. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8228. mg_send_http_error(conn,
  8229. 500,
  8230. "Error: Cannot open directory\nopendir(%s): %s",
  8231. dir,
  8232. strerror(ERRNO));
  8233. return;
  8234. }
  8235. gmt_time_string(date, sizeof(date), &curtime);
  8236. esc = NULL;
  8237. title = conn->request_info.local_uri;
  8238. if (title[strcspn(title, "&<>")]) {
  8239. /* HTML escaping needed */
  8240. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8241. if (esc) {
  8242. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8243. mg_strlcpy(p, title + i, 2);
  8244. if (*p == '&') {
  8245. strcpy(p, "&amp;");
  8246. } else if (*p == '<') {
  8247. strcpy(p, "&lt;");
  8248. } else if (*p == '>') {
  8249. strcpy(p, "&gt;");
  8250. }
  8251. }
  8252. } else {
  8253. title = "";
  8254. }
  8255. }
  8256. sort_direction = ((conn->request_info.query_string != NULL)
  8257. && (conn->request_info.query_string[0] != '\0')
  8258. && (conn->request_info.query_string[1] == 'd'))
  8259. ? 'a'
  8260. : 'd';
  8261. conn->must_close = 1;
  8262. /* Create 200 OK response */
  8263. mg_response_header_start(conn, 200);
  8264. send_static_cache_header(conn);
  8265. send_additional_header(conn);
  8266. mg_response_header_add(conn,
  8267. "Content-Type",
  8268. "text/html; charset=utf-8",
  8269. -1);
  8270. /* Send all headers */
  8271. mg_response_header_send(conn);
  8272. /* Body */
  8273. mg_printf(conn,
  8274. "<html><head><title>Index of %s</title>"
  8275. "<style>th {text-align: left;}</style></head>"
  8276. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8277. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8278. "<th><a href=\"?d%c\">Modified</a></th>"
  8279. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8280. "<tr><td colspan=\"3\"><hr></td></tr>",
  8281. esc ? esc : title,
  8282. esc ? esc : title,
  8283. sort_direction,
  8284. sort_direction,
  8285. sort_direction);
  8286. mg_free(esc);
  8287. /* Print first entry - link to a parent directory */
  8288. mg_printf(conn,
  8289. "<tr><td><a href=\"%s\">%s</a></td>"
  8290. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8291. "..",
  8292. "Parent directory",
  8293. "-",
  8294. "-");
  8295. /* Sort and print directory entries */
  8296. if (data.entries != NULL) {
  8297. qsort(data.entries,
  8298. data.num_entries,
  8299. sizeof(data.entries[0]),
  8300. compare_dir_entries);
  8301. for (i = 0; i < data.num_entries; i++) {
  8302. print_dir_entry(&data.entries[i]);
  8303. mg_free(data.entries[i].file_name);
  8304. }
  8305. mg_free(data.entries);
  8306. }
  8307. mg_printf(conn, "%s", "</table></pre></body></html>");
  8308. conn->status_code = 200;
  8309. }
  8310. #endif /* NO_FILESYSTEMS */
  8311. /* Send len bytes from the opened file to the client. */
  8312. static void
  8313. send_file_data(struct mg_connection *conn,
  8314. struct mg_file *filep,
  8315. int64_t offset,
  8316. int64_t len)
  8317. {
  8318. char buf[MG_BUF_LEN];
  8319. int to_read, num_read, num_written;
  8320. int64_t size;
  8321. if (!filep || !conn) {
  8322. return;
  8323. }
  8324. /* Sanity check the offset */
  8325. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8326. : (int64_t)(filep->stat.size);
  8327. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8328. if (len > 0 && filep->access.fp != NULL) {
  8329. /* file stored on disk */
  8330. #if defined(__linux__)
  8331. /* sendfile is only available for Linux */
  8332. if ((conn->ssl == 0) && (conn->throttle == 0)
  8333. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8334. "yes"))) {
  8335. off_t sf_offs = (off_t)offset;
  8336. ssize_t sf_sent;
  8337. int sf_file = fileno(filep->access.fp);
  8338. int loop_cnt = 0;
  8339. do {
  8340. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8341. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8342. size_t sf_tosend =
  8343. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8344. sf_sent =
  8345. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8346. if (sf_sent > 0) {
  8347. len -= sf_sent;
  8348. offset += sf_sent;
  8349. } else if (loop_cnt == 0) {
  8350. /* This file can not be sent using sendfile.
  8351. * This might be the case for pseudo-files in the
  8352. * /sys/ and /proc/ file system.
  8353. * Use the regular user mode copy code instead. */
  8354. break;
  8355. } else if (sf_sent == 0) {
  8356. /* No error, but 0 bytes sent. May be EOF? */
  8357. return;
  8358. }
  8359. loop_cnt++;
  8360. } while ((len > 0) && (sf_sent >= 0));
  8361. if (sf_sent > 0) {
  8362. return; /* OK */
  8363. }
  8364. /* sf_sent<0 means error, thus fall back to the classic way */
  8365. /* This is always the case, if sf_file is not a "normal" file,
  8366. * e.g., for sending data from the output of a CGI process. */
  8367. offset = (int64_t)sf_offs;
  8368. }
  8369. #endif
  8370. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8371. mg_cry_internal(conn,
  8372. "%s: fseeko() failed: %s",
  8373. __func__,
  8374. strerror(ERRNO));
  8375. mg_send_http_error(
  8376. conn,
  8377. 500,
  8378. "%s",
  8379. "Error: Unable to access file at requested position.");
  8380. } else {
  8381. while (len > 0) {
  8382. /* Calculate how much to read from the file in the buffer */
  8383. to_read = sizeof(buf);
  8384. if ((int64_t)to_read > len) {
  8385. to_read = (int)len;
  8386. }
  8387. /* Read from file, exit the loop on error */
  8388. if ((num_read =
  8389. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8390. <= 0) {
  8391. break;
  8392. }
  8393. /* Send read bytes to the client, exit the loop on error */
  8394. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8395. != num_read) {
  8396. break;
  8397. }
  8398. /* Both read and were successful, adjust counters */
  8399. len -= num_written;
  8400. }
  8401. }
  8402. }
  8403. }
  8404. static int
  8405. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8406. {
  8407. return sscanf(header,
  8408. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8409. a,
  8410. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8411. // to an integer value, but function will not report
  8412. // conversion errors; consider using 'strtol' instead
  8413. }
  8414. static void
  8415. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8416. {
  8417. if ((filestat != NULL) && (buf != NULL)) {
  8418. mg_snprintf(NULL,
  8419. NULL, /* All calls to construct_etag use 64 byte buffer */
  8420. buf,
  8421. buf_len,
  8422. "\"%lx.%" INT64_FMT "\"",
  8423. (unsigned long)filestat->last_modified,
  8424. filestat->size);
  8425. }
  8426. }
  8427. static void
  8428. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8429. {
  8430. if (filep != NULL && filep->fp != NULL) {
  8431. #if defined(_WIN32)
  8432. (void)conn; /* Unused. */
  8433. #else
  8434. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8435. mg_cry_internal(conn,
  8436. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8437. __func__,
  8438. strerror(ERRNO));
  8439. }
  8440. #endif
  8441. }
  8442. }
  8443. #if defined(USE_ZLIB)
  8444. #include "mod_zlib.inl"
  8445. #endif
  8446. #if !defined(NO_FILESYSTEMS)
  8447. static void
  8448. handle_static_file_request(struct mg_connection *conn,
  8449. const char *path,
  8450. struct mg_file *filep,
  8451. const char *mime_type,
  8452. const char *additional_headers)
  8453. {
  8454. char lm[64], etag[64];
  8455. char range[128]; /* large enough, so there will be no overflow */
  8456. const char *range_hdr;
  8457. int64_t cl, r1, r2;
  8458. struct vec mime_vec;
  8459. int n, truncated;
  8460. char gz_path[UTF8_PATH_MAX];
  8461. const char *encoding = 0;
  8462. const char *origin_hdr;
  8463. const char *cors_orig_cfg;
  8464. const char *cors1, *cors2;
  8465. int is_head_request;
  8466. #if defined(USE_ZLIB)
  8467. /* Compression is allowed, unless there is a reason not to use
  8468. * compression. If the file is already compressed, too small or a
  8469. * "range" request was made, on the fly compression is not possible. */
  8470. int allow_on_the_fly_compression = 1;
  8471. #endif
  8472. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8473. return;
  8474. }
  8475. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8476. if (mime_type == NULL) {
  8477. get_mime_type(conn, path, &mime_vec);
  8478. } else {
  8479. mime_vec.ptr = mime_type;
  8480. mime_vec.len = strlen(mime_type);
  8481. }
  8482. if (filep->stat.size > INT64_MAX) {
  8483. mg_send_http_error(conn,
  8484. 500,
  8485. "Error: File size is too large to send\n%" INT64_FMT,
  8486. filep->stat.size);
  8487. return;
  8488. }
  8489. cl = (int64_t)filep->stat.size;
  8490. conn->status_code = 200;
  8491. range[0] = '\0';
  8492. #if defined(USE_ZLIB)
  8493. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8494. * it's important to rewrite the filename after resolving
  8495. * the mime type from it, to preserve the actual file's type */
  8496. if (!conn->accept_gzip) {
  8497. allow_on_the_fly_compression = 0;
  8498. }
  8499. #endif
  8500. /* Check if there is a range header */
  8501. range_hdr = mg_get_header(conn, "Range");
  8502. /* For gzipped files, add *.gz */
  8503. if (filep->stat.is_gzipped) {
  8504. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8505. if (truncated) {
  8506. mg_send_http_error(conn,
  8507. 500,
  8508. "Error: Path of zipped file too long (%s)",
  8509. path);
  8510. return;
  8511. }
  8512. path = gz_path;
  8513. encoding = "gzip";
  8514. #if defined(USE_ZLIB)
  8515. /* File is already compressed. No "on the fly" compression. */
  8516. allow_on_the_fly_compression = 0;
  8517. #endif
  8518. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8519. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8520. struct mg_file_stat file_stat;
  8521. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8522. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8523. && !file_stat.is_directory) {
  8524. file_stat.is_gzipped = 1;
  8525. filep->stat = file_stat;
  8526. cl = (int64_t)filep->stat.size;
  8527. path = gz_path;
  8528. encoding = "gzip";
  8529. #if defined(USE_ZLIB)
  8530. /* File is already compressed. No "on the fly" compression. */
  8531. allow_on_the_fly_compression = 0;
  8532. #endif
  8533. }
  8534. }
  8535. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8536. mg_send_http_error(conn,
  8537. 500,
  8538. "Error: Cannot open file\nfopen(%s): %s",
  8539. path,
  8540. strerror(ERRNO));
  8541. return;
  8542. }
  8543. fclose_on_exec(&filep->access, conn);
  8544. /* If "Range" request was made: parse header, send only selected part
  8545. * of the file. */
  8546. r1 = r2 = 0;
  8547. if ((range_hdr != NULL)
  8548. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8549. && (r2 >= 0)) {
  8550. /* actually, range requests don't play well with a pre-gzipped
  8551. * file (since the range is specified in the uncompressed space) */
  8552. if (filep->stat.is_gzipped) {
  8553. mg_send_http_error(
  8554. conn,
  8555. 416, /* 416 = Range Not Satisfiable */
  8556. "%s",
  8557. "Error: Range requests in gzipped files are not supported");
  8558. (void)mg_fclose(
  8559. &filep->access); /* ignore error on read only file */
  8560. return;
  8561. }
  8562. conn->status_code = 206;
  8563. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8564. mg_snprintf(conn,
  8565. NULL, /* range buffer is big enough */
  8566. range,
  8567. sizeof(range),
  8568. "bytes "
  8569. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8570. r1,
  8571. r1 + cl - 1,
  8572. filep->stat.size);
  8573. #if defined(USE_ZLIB)
  8574. /* Do not compress ranges. */
  8575. allow_on_the_fly_compression = 0;
  8576. #endif
  8577. }
  8578. /* Do not compress small files. Small files do not benefit from file
  8579. * compression, but there is still some overhead. */
  8580. #if defined(USE_ZLIB)
  8581. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8582. /* File is below the size limit. */
  8583. allow_on_the_fly_compression = 0;
  8584. }
  8585. #endif
  8586. /* Standard CORS header */
  8587. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8588. origin_hdr = mg_get_header(conn, "Origin");
  8589. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8590. /* Cross-origin resource sharing (CORS), see
  8591. * http://www.html5rocks.com/en/tutorials/cors/,
  8592. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8593. * -
  8594. * preflight is not supported for files. */
  8595. cors1 = "Access-Control-Allow-Origin";
  8596. cors2 = cors_orig_cfg;
  8597. } else {
  8598. cors1 = cors2 = "";
  8599. }
  8600. /* Prepare Etag, and Last-Modified headers. */
  8601. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8602. construct_etag(etag, sizeof(etag), &filep->stat);
  8603. /* Create 2xx (200, 206) response */
  8604. mg_response_header_start(conn, conn->status_code);
  8605. send_static_cache_header(conn);
  8606. send_additional_header(conn);
  8607. mg_response_header_add(conn,
  8608. "Content-Type",
  8609. mime_vec.ptr,
  8610. (int)mime_vec.len);
  8611. if (cors1[0] != 0) {
  8612. mg_response_header_add(conn, cors1, cors2, -1);
  8613. }
  8614. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8615. mg_response_header_add(conn, "Etag", etag, -1);
  8616. #if defined(USE_ZLIB)
  8617. /* On the fly compression allowed */
  8618. if (allow_on_the_fly_compression) {
  8619. /* For on the fly compression, we don't know the content size in
  8620. * advance, so we have to use chunked encoding */
  8621. encoding = "gzip";
  8622. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8623. /* HTTP/2 is always using "chunks" (frames) */
  8624. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8625. }
  8626. } else
  8627. #endif
  8628. {
  8629. /* Without on-the-fly compression, we know the content-length
  8630. * and we can use ranges (with on-the-fly compression we cannot).
  8631. * So we send these response headers only in this case. */
  8632. char len[32];
  8633. int trunc = 0;
  8634. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8635. if (!trunc) {
  8636. mg_response_header_add(conn, "Content-Length", len, -1);
  8637. }
  8638. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8639. }
  8640. if (encoding) {
  8641. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8642. }
  8643. if (range[0] != 0) {
  8644. mg_response_header_add(conn, "Content-Range", range, -1);
  8645. }
  8646. /* The code above does not add any header starting with X- to make
  8647. * sure no one of the additional_headers is included twice */
  8648. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8649. mg_response_header_add_lines(conn, additional_headers);
  8650. }
  8651. /* Send all headers */
  8652. mg_response_header_send(conn);
  8653. if (!is_head_request) {
  8654. #if defined(USE_ZLIB)
  8655. if (allow_on_the_fly_compression) {
  8656. /* Compress and send */
  8657. send_compressed_data(conn, filep);
  8658. } else
  8659. #endif
  8660. {
  8661. /* Send file directly */
  8662. send_file_data(conn, filep, r1, cl);
  8663. }
  8664. }
  8665. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8666. }
  8667. int
  8668. mg_send_file_body(struct mg_connection *conn, const char *path)
  8669. {
  8670. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8671. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8672. return -1;
  8673. }
  8674. fclose_on_exec(&file.access, conn);
  8675. send_file_data(conn, &file, 0, INT64_MAX);
  8676. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8677. return 0; /* >= 0 for OK */
  8678. }
  8679. #endif /* NO_FILESYSTEMS */
  8680. #if !defined(NO_CACHING)
  8681. /* Return True if we should reply 304 Not Modified. */
  8682. static int
  8683. is_not_modified(const struct mg_connection *conn,
  8684. const struct mg_file_stat *filestat)
  8685. {
  8686. char etag[64];
  8687. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8688. const char *inm = mg_get_header(conn, "If-None-Match");
  8689. construct_etag(etag, sizeof(etag), filestat);
  8690. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8691. || ((ims != NULL)
  8692. && (filestat->last_modified <= parse_date_string(ims)));
  8693. }
  8694. static void
  8695. handle_not_modified_static_file_request(struct mg_connection *conn,
  8696. struct mg_file *filep)
  8697. {
  8698. char lm[64], etag[64];
  8699. if ((conn == NULL) || (filep == NULL)) {
  8700. return;
  8701. }
  8702. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8703. construct_etag(etag, sizeof(etag), &filep->stat);
  8704. /* Create 304 "not modified" response */
  8705. mg_response_header_start(conn, 304);
  8706. send_static_cache_header(conn);
  8707. send_additional_header(conn);
  8708. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8709. mg_response_header_add(conn, "Etag", etag, -1);
  8710. /* Send all headers */
  8711. mg_response_header_send(conn);
  8712. }
  8713. #endif
  8714. #if !defined(NO_FILESYSTEMS)
  8715. void
  8716. mg_send_file(struct mg_connection *conn, const char *path)
  8717. {
  8718. mg_send_mime_file2(conn, path, NULL, NULL);
  8719. }
  8720. void
  8721. mg_send_mime_file(struct mg_connection *conn,
  8722. const char *path,
  8723. const char *mime_type)
  8724. {
  8725. mg_send_mime_file2(conn, path, mime_type, NULL);
  8726. }
  8727. void
  8728. mg_send_mime_file2(struct mg_connection *conn,
  8729. const char *path,
  8730. const char *mime_type,
  8731. const char *additional_headers)
  8732. {
  8733. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8734. if (!conn) {
  8735. /* No conn */
  8736. return;
  8737. }
  8738. if (mg_stat(conn, path, &file.stat)) {
  8739. #if !defined(NO_CACHING)
  8740. if (is_not_modified(conn, &file.stat)) {
  8741. /* Send 304 "Not Modified" - this must not send any body data */
  8742. handle_not_modified_static_file_request(conn, &file);
  8743. } else
  8744. #endif /* NO_CACHING */
  8745. if (file.stat.is_directory) {
  8746. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8747. "yes")) {
  8748. handle_directory_request(conn, path);
  8749. } else {
  8750. mg_send_http_error(conn,
  8751. 403,
  8752. "%s",
  8753. "Error: Directory listing denied");
  8754. }
  8755. } else {
  8756. handle_static_file_request(
  8757. conn, path, &file, mime_type, additional_headers);
  8758. }
  8759. } else {
  8760. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8761. }
  8762. }
  8763. /* For a given PUT path, create all intermediate subdirectories.
  8764. * Return 0 if the path itself is a directory.
  8765. * Return 1 if the path leads to a file.
  8766. * Return -1 for if the path is too long.
  8767. * Return -2 if path can not be created.
  8768. */
  8769. static int
  8770. put_dir(struct mg_connection *conn, const char *path)
  8771. {
  8772. char buf[UTF8_PATH_MAX];
  8773. const char *s, *p;
  8774. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8775. size_t len;
  8776. int res = 1;
  8777. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8778. len = (size_t)(p - path);
  8779. if (len >= sizeof(buf)) {
  8780. /* path too long */
  8781. res = -1;
  8782. break;
  8783. }
  8784. memcpy(buf, path, len);
  8785. buf[len] = '\0';
  8786. /* Try to create intermediate directory */
  8787. DEBUG_TRACE("mkdir(%s)", buf);
  8788. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8789. /* path does not exixt and can not be created */
  8790. res = -2;
  8791. break;
  8792. }
  8793. /* Is path itself a directory? */
  8794. if (p[1] == '\0') {
  8795. res = 0;
  8796. }
  8797. }
  8798. return res;
  8799. }
  8800. static void
  8801. remove_bad_file(const struct mg_connection *conn, const char *path)
  8802. {
  8803. int r = mg_remove(conn, path);
  8804. if (r != 0) {
  8805. mg_cry_internal(conn,
  8806. "%s: Cannot remove invalid file %s",
  8807. __func__,
  8808. path);
  8809. }
  8810. }
  8811. long long
  8812. mg_store_body(struct mg_connection *conn, const char *path)
  8813. {
  8814. char buf[MG_BUF_LEN];
  8815. long long len = 0;
  8816. int ret, n;
  8817. struct mg_file fi;
  8818. if (conn->consumed_content != 0) {
  8819. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8820. return -11;
  8821. }
  8822. ret = put_dir(conn, path);
  8823. if (ret < 0) {
  8824. /* -1 for path too long,
  8825. * -2 for path can not be created. */
  8826. return ret;
  8827. }
  8828. if (ret != 1) {
  8829. /* Return 0 means, path itself is a directory. */
  8830. return 0;
  8831. }
  8832. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8833. return -12;
  8834. }
  8835. ret = mg_read(conn, buf, sizeof(buf));
  8836. while (ret > 0) {
  8837. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8838. if (n != ret) {
  8839. (void)mg_fclose(
  8840. &fi.access); /* File is bad and will be removed anyway. */
  8841. remove_bad_file(conn, path);
  8842. return -13;
  8843. }
  8844. len += ret;
  8845. ret = mg_read(conn, buf, sizeof(buf));
  8846. }
  8847. /* File is open for writing. If fclose fails, there was probably an
  8848. * error flushing the buffer to disk, so the file on disk might be
  8849. * broken. Delete it and return an error to the caller. */
  8850. if (mg_fclose(&fi.access) != 0) {
  8851. remove_bad_file(conn, path);
  8852. return -14;
  8853. }
  8854. return len;
  8855. }
  8856. #endif /* NO_FILESYSTEMS */
  8857. /* Parse a buffer:
  8858. * Forward the string pointer till the end of a word, then
  8859. * terminate it and forward till the begin of the next word.
  8860. */
  8861. static int
  8862. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8863. {
  8864. /* Forward until a space is found - use isgraph here */
  8865. /* See http://www.cplusplus.com/reference/cctype/ */
  8866. while (isgraph((unsigned char)**ppw)) {
  8867. (*ppw)++;
  8868. }
  8869. /* Check end of word */
  8870. if (eol) {
  8871. /* must be a end of line */
  8872. if ((**ppw != '\r') && (**ppw != '\n')) {
  8873. return -1;
  8874. }
  8875. } else {
  8876. /* must be a end of a word, but not a line */
  8877. if (**ppw != ' ') {
  8878. return -1;
  8879. }
  8880. }
  8881. /* Terminate and forward to the next word */
  8882. do {
  8883. **ppw = 0;
  8884. (*ppw)++;
  8885. } while (isspace((unsigned char)**ppw));
  8886. /* Check after term */
  8887. if (!eol) {
  8888. /* if it's not the end of line, there must be a next word */
  8889. if (!isgraph((unsigned char)**ppw)) {
  8890. return -1;
  8891. }
  8892. }
  8893. /* ok */
  8894. return 1;
  8895. }
  8896. /* Parse HTTP headers from the given buffer, advance buf pointer
  8897. * to the point where parsing stopped.
  8898. * All parameters must be valid pointers (not NULL).
  8899. * Return <0 on error. */
  8900. static int
  8901. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8902. {
  8903. int i;
  8904. int num_headers = 0;
  8905. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8906. char *dp = *buf;
  8907. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8908. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8909. dp++;
  8910. }
  8911. if (dp == *buf) {
  8912. /* End of headers reached. */
  8913. break;
  8914. }
  8915. /* Drop all spaces after header name before : */
  8916. while (*dp == ' ') {
  8917. *dp = 0;
  8918. dp++;
  8919. }
  8920. if (*dp != ':') {
  8921. /* This is not a valid field. */
  8922. return -1;
  8923. }
  8924. /* End of header key (*dp == ':') */
  8925. /* Truncate here and set the key name */
  8926. *dp = 0;
  8927. hdr[i].name = *buf;
  8928. /* Skip all spaces */
  8929. do {
  8930. dp++;
  8931. } while ((*dp == ' ') || (*dp == '\t'));
  8932. /* The rest of the line is the value */
  8933. hdr[i].value = dp;
  8934. /* Find end of line */
  8935. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8936. dp++;
  8937. };
  8938. /* eliminate \r */
  8939. if (*dp == '\r') {
  8940. *dp = 0;
  8941. dp++;
  8942. if (*dp != '\n') {
  8943. /* This is not a valid line. */
  8944. return -1;
  8945. }
  8946. }
  8947. /* here *dp is either 0 or '\n' */
  8948. /* in any case, we have a new header */
  8949. num_headers = i + 1;
  8950. if (*dp) {
  8951. *dp = 0;
  8952. dp++;
  8953. *buf = dp;
  8954. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8955. /* This is the end of the header */
  8956. break;
  8957. }
  8958. } else {
  8959. *buf = dp;
  8960. break;
  8961. }
  8962. }
  8963. return num_headers;
  8964. }
  8965. struct mg_http_method_info {
  8966. const char *name;
  8967. int request_has_body;
  8968. int response_has_body;
  8969. int is_safe;
  8970. int is_idempotent;
  8971. int is_cacheable;
  8972. };
  8973. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8974. static const struct mg_http_method_info http_methods[] = {
  8975. /* HTTP (RFC 2616) */
  8976. {"GET", 0, 1, 1, 1, 1},
  8977. {"POST", 1, 1, 0, 0, 0},
  8978. {"PUT", 1, 0, 0, 1, 0},
  8979. {"DELETE", 0, 0, 0, 1, 0},
  8980. {"HEAD", 0, 0, 1, 1, 1},
  8981. {"OPTIONS", 0, 0, 1, 1, 0},
  8982. {"CONNECT", 1, 1, 0, 0, 0},
  8983. /* TRACE method (RFC 2616) is not supported for security reasons */
  8984. /* PATCH method (RFC 5789) */
  8985. {"PATCH", 1, 0, 0, 0, 0},
  8986. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8987. /* WEBDAV (RFC 2518) */
  8988. {"PROPFIND", 0, 1, 1, 1, 0},
  8989. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8990. * Some PROPFIND results MAY be cached, with care,
  8991. * as there is no cache validation mechanism for
  8992. * most properties. This method is both safe and
  8993. * idempotent (see Section 9.1 of [RFC2616]). */
  8994. {"MKCOL", 0, 0, 0, 1, 0},
  8995. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8996. * When MKCOL is invoked without a request body,
  8997. * the newly created collection SHOULD have no
  8998. * members. A MKCOL request message may contain
  8999. * a message body. The precise behavior of a MKCOL
  9000. * request when the body is present is undefined,
  9001. * ... ==> We do not support MKCOL with body data.
  9002. * This method is idempotent, but not safe (see
  9003. * Section 9.1 of [RFC2616]). Responses to this
  9004. * method MUST NOT be cached. */
  9005. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9006. {"LOCK", 1, 1, 0, 0, 0},
  9007. {"UNLOCK", 1, 0, 0, 0, 0},
  9008. {"PROPPATCH", 1, 1, 0, 0, 0},
  9009. /* Unsupported WEBDAV Methods: */
  9010. /* COPY, MOVE (RFC 2518) */
  9011. /* + 11 methods from RFC 3253 */
  9012. /* ORDERPATCH (RFC 3648) */
  9013. /* ACL (RFC 3744) */
  9014. /* SEARCH (RFC 5323) */
  9015. /* + MicroSoft extensions
  9016. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9017. /* REPORT method (RFC 3253) */
  9018. {"REPORT", 1, 1, 1, 1, 1},
  9019. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9020. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9021. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9022. * to be useful for REST in case a "GET request with body" is
  9023. * required. */
  9024. {NULL, 0, 0, 0, 0, 0}
  9025. /* end of list */
  9026. };
  9027. static const struct mg_http_method_info *
  9028. get_http_method_info(const char *method)
  9029. {
  9030. /* Check if the method is known to the server. The list of all known
  9031. * HTTP methods can be found here at
  9032. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9033. */
  9034. const struct mg_http_method_info *m = http_methods;
  9035. while (m->name) {
  9036. if (!strcmp(m->name, method)) {
  9037. return m;
  9038. }
  9039. m++;
  9040. }
  9041. return NULL;
  9042. }
  9043. static int
  9044. is_valid_http_method(const char *method)
  9045. {
  9046. return (get_http_method_info(method) != NULL);
  9047. }
  9048. /* Parse HTTP request, fill in mg_request_info structure.
  9049. * This function modifies the buffer by NUL-terminating
  9050. * HTTP request components, header names and header values.
  9051. * Parameters:
  9052. * buf (in/out): pointer to the HTTP header to parse and split
  9053. * len (in): length of HTTP header buffer
  9054. * re (out): parsed header as mg_request_info
  9055. * buf and ri must be valid pointers (not NULL), len>0.
  9056. * Returns <0 on error. */
  9057. static int
  9058. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9059. {
  9060. int request_length;
  9061. int init_skip = 0;
  9062. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9063. * remote_port */
  9064. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9065. NULL;
  9066. ri->num_headers = 0;
  9067. /* RFC says that all initial whitespaces should be ignored */
  9068. /* This included all leading \r and \n (isspace) */
  9069. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9070. while ((len > 0) && isspace((unsigned char)*buf)) {
  9071. buf++;
  9072. len--;
  9073. init_skip++;
  9074. }
  9075. if (len == 0) {
  9076. /* Incomplete request */
  9077. return 0;
  9078. }
  9079. /* Control characters are not allowed, including zero */
  9080. if (iscntrl((unsigned char)*buf)) {
  9081. return -1;
  9082. }
  9083. /* Find end of HTTP header */
  9084. request_length = get_http_header_len(buf, len);
  9085. if (request_length <= 0) {
  9086. return request_length;
  9087. }
  9088. buf[request_length - 1] = '\0';
  9089. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9090. return -1;
  9091. }
  9092. /* The first word has to be the HTTP method */
  9093. ri->request_method = buf;
  9094. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9095. return -1;
  9096. }
  9097. /* The second word is the URI */
  9098. ri->request_uri = buf;
  9099. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9100. return -1;
  9101. }
  9102. /* Next would be the HTTP version */
  9103. ri->http_version = buf;
  9104. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9105. return -1;
  9106. }
  9107. /* Check for a valid HTTP version key */
  9108. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9109. /* Invalid request */
  9110. return -1;
  9111. }
  9112. ri->http_version += 5;
  9113. /* Check for a valid http method */
  9114. if (!is_valid_http_method(ri->request_method)) {
  9115. return -1;
  9116. }
  9117. /* Parse all HTTP headers */
  9118. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9119. if (ri->num_headers < 0) {
  9120. /* Error while parsing headers */
  9121. return -1;
  9122. }
  9123. return request_length + init_skip;
  9124. }
  9125. static int
  9126. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9127. {
  9128. int response_length;
  9129. int init_skip = 0;
  9130. char *tmp, *tmp2;
  9131. long l;
  9132. /* Initialize elements. */
  9133. ri->http_version = ri->status_text = NULL;
  9134. ri->num_headers = ri->status_code = 0;
  9135. /* RFC says that all initial whitespaces should be ingored */
  9136. /* This included all leading \r and \n (isspace) */
  9137. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9138. while ((len > 0) && isspace((unsigned char)*buf)) {
  9139. buf++;
  9140. len--;
  9141. init_skip++;
  9142. }
  9143. if (len == 0) {
  9144. /* Incomplete request */
  9145. return 0;
  9146. }
  9147. /* Control characters are not allowed, including zero */
  9148. if (iscntrl((unsigned char)*buf)) {
  9149. return -1;
  9150. }
  9151. /* Find end of HTTP header */
  9152. response_length = get_http_header_len(buf, len);
  9153. if (response_length <= 0) {
  9154. return response_length;
  9155. }
  9156. buf[response_length - 1] = '\0';
  9157. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9158. return -1;
  9159. }
  9160. /* The first word is the HTTP version */
  9161. /* Check for a valid HTTP version key */
  9162. if (strncmp(buf, "HTTP/", 5) != 0) {
  9163. /* Invalid request */
  9164. return -1;
  9165. }
  9166. buf += 5;
  9167. if (!isgraph((unsigned char)buf[0])) {
  9168. /* Invalid request */
  9169. return -1;
  9170. }
  9171. ri->http_version = buf;
  9172. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9173. return -1;
  9174. }
  9175. /* The second word is the status as a number */
  9176. tmp = buf;
  9177. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9178. return -1;
  9179. }
  9180. l = strtol(tmp, &tmp2, 10);
  9181. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9182. /* Everything else but a 3 digit code is invalid */
  9183. return -1;
  9184. }
  9185. ri->status_code = (int)l;
  9186. /* The rest of the line is the status text */
  9187. ri->status_text = buf;
  9188. /* Find end of status text */
  9189. /* isgraph or isspace = isprint */
  9190. while (isprint((unsigned char)*buf)) {
  9191. buf++;
  9192. }
  9193. if ((*buf != '\r') && (*buf != '\n')) {
  9194. return -1;
  9195. }
  9196. /* Terminate string and forward buf to next line */
  9197. do {
  9198. *buf = 0;
  9199. buf++;
  9200. } while (isspace((unsigned char)*buf));
  9201. /* Parse all HTTP headers */
  9202. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9203. if (ri->num_headers < 0) {
  9204. /* Error while parsing headers */
  9205. return -1;
  9206. }
  9207. return response_length + init_skip;
  9208. }
  9209. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9210. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9211. * buffer (which marks the end of HTTP request). Buffer buf may already
  9212. * have some data. The length of the data is stored in nread.
  9213. * Upon every read operation, increase nread by the number of bytes read. */
  9214. static int
  9215. read_message(FILE *fp,
  9216. struct mg_connection *conn,
  9217. char *buf,
  9218. int bufsiz,
  9219. int *nread)
  9220. {
  9221. int request_len, n = 0;
  9222. struct timespec last_action_time;
  9223. double request_timeout;
  9224. if (!conn) {
  9225. return 0;
  9226. }
  9227. memset(&last_action_time, 0, sizeof(last_action_time));
  9228. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9229. /* value of request_timeout is in seconds, config in milliseconds */
  9230. request_timeout =
  9231. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9232. } else {
  9233. request_timeout =
  9234. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9235. / 1000.0;
  9236. }
  9237. if (conn->handled_requests > 0) {
  9238. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9239. request_timeout =
  9240. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9241. / 1000.0;
  9242. }
  9243. }
  9244. request_len = get_http_header_len(buf, *nread);
  9245. while (request_len == 0) {
  9246. /* Full request not yet received */
  9247. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9248. /* Server is to be stopped. */
  9249. return -1;
  9250. }
  9251. if (*nread >= bufsiz) {
  9252. /* Request too long */
  9253. return -2;
  9254. }
  9255. n = pull_inner(
  9256. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9257. if (n == -2) {
  9258. /* Receive error */
  9259. return -1;
  9260. }
  9261. /* update clock after every read request */
  9262. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9263. if (n > 0) {
  9264. *nread += n;
  9265. request_len = get_http_header_len(buf, *nread);
  9266. }
  9267. if ((request_len == 0) && (request_timeout >= 0)) {
  9268. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9269. > request_timeout) {
  9270. /* Timeout */
  9271. return -1;
  9272. }
  9273. }
  9274. }
  9275. return request_len;
  9276. }
  9277. #if !defined(NO_CGI) || !defined(NO_FILES)
  9278. static int
  9279. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9280. {
  9281. const char *expect;
  9282. char buf[MG_BUF_LEN];
  9283. int success = 0;
  9284. if (!conn) {
  9285. return 0;
  9286. }
  9287. expect = mg_get_header(conn, "Expect");
  9288. DEBUG_ASSERT(fp != NULL);
  9289. if (!fp) {
  9290. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9291. return 0;
  9292. }
  9293. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9294. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9295. */
  9296. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9297. } else {
  9298. if (expect != NULL) {
  9299. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9300. conn->status_code = 100;
  9301. } else {
  9302. conn->status_code = 200;
  9303. }
  9304. DEBUG_ASSERT(conn->consumed_content == 0);
  9305. if (conn->consumed_content != 0) {
  9306. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9307. return 0;
  9308. }
  9309. for (;;) {
  9310. int nread = mg_read(conn, buf, sizeof(buf));
  9311. if (nread <= 0) {
  9312. success = (nread == 0);
  9313. break;
  9314. }
  9315. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9316. break;
  9317. }
  9318. }
  9319. /* Each error code path in this function must send an error */
  9320. if (!success) {
  9321. /* NOTE: Maybe some data has already been sent. */
  9322. /* TODO (low): If some data has been sent, a correct error
  9323. * reply can no longer be sent, so just close the connection */
  9324. mg_send_http_error(conn, 500, "%s", "");
  9325. }
  9326. }
  9327. return success;
  9328. }
  9329. #endif
  9330. #if defined(USE_TIMERS)
  9331. #define TIMER_API static
  9332. #include "timer.inl"
  9333. #endif /* USE_TIMERS */
  9334. #if !defined(NO_CGI)
  9335. /* This structure helps to create an environment for the spawned CGI
  9336. * program.
  9337. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9338. * last element must be NULL.
  9339. * However, on Windows there is a requirement that all these
  9340. * VARIABLE=VALUE\0
  9341. * strings must reside in a contiguous buffer. The end of the buffer is
  9342. * marked by two '\0' characters.
  9343. * We satisfy both worlds: we create an envp array (which is vars), all
  9344. * entries are actually pointers inside buf. */
  9345. struct cgi_environment {
  9346. struct mg_connection *conn;
  9347. /* Data block */
  9348. char *buf; /* Environment buffer */
  9349. size_t buflen; /* Space available in buf */
  9350. size_t bufused; /* Space taken in buf */
  9351. /* Index block */
  9352. char **var; /* char **envp */
  9353. size_t varlen; /* Number of variables available in var */
  9354. size_t varused; /* Number of variables stored in var */
  9355. };
  9356. static void addenv(struct cgi_environment *env,
  9357. PRINTF_FORMAT_STRING(const char *fmt),
  9358. ...) PRINTF_ARGS(2, 3);
  9359. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9360. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9361. static void
  9362. addenv(struct cgi_environment *env, const char *fmt, ...)
  9363. {
  9364. size_t i, n, space;
  9365. int truncated = 0;
  9366. char *added;
  9367. va_list ap;
  9368. if ((env->varlen - env->varused) < 2) {
  9369. mg_cry_internal(env->conn,
  9370. "%s: Cannot register CGI variable [%s]",
  9371. __func__,
  9372. fmt);
  9373. return;
  9374. }
  9375. /* Calculate how much space is left in the buffer */
  9376. space = (env->buflen - env->bufused);
  9377. do {
  9378. /* Space for "\0\0" is always needed. */
  9379. if (space <= 2) {
  9380. /* Allocate new buffer */
  9381. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9382. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9383. if (!added) {
  9384. /* Out of memory */
  9385. mg_cry_internal(
  9386. env->conn,
  9387. "%s: Cannot allocate memory for CGI variable [%s]",
  9388. __func__,
  9389. fmt);
  9390. return;
  9391. }
  9392. /* Retarget pointers */
  9393. env->buf = added;
  9394. env->buflen = n;
  9395. for (i = 0, n = 0; i < env->varused; i++) {
  9396. env->var[i] = added + n;
  9397. n += strlen(added + n) + 1;
  9398. }
  9399. space = (env->buflen - env->bufused);
  9400. }
  9401. /* Make a pointer to the free space int the buffer */
  9402. added = env->buf + env->bufused;
  9403. /* Copy VARIABLE=VALUE\0 string into the free space */
  9404. va_start(ap, fmt);
  9405. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9406. va_end(ap);
  9407. /* Do not add truncated strings to the environment */
  9408. if (truncated) {
  9409. /* Reallocate the buffer */
  9410. space = 0;
  9411. }
  9412. } while (truncated);
  9413. /* Calculate number of bytes added to the environment */
  9414. n = strlen(added) + 1;
  9415. env->bufused += n;
  9416. /* Append a pointer to the added string into the envp array */
  9417. env->var[env->varused] = added;
  9418. env->varused++;
  9419. }
  9420. /* Return 0 on success, non-zero if an error occurs. */
  9421. static int
  9422. prepare_cgi_environment(struct mg_connection *conn,
  9423. const char *prog,
  9424. struct cgi_environment *env,
  9425. unsigned char cgi_config_idx)
  9426. {
  9427. const char *s;
  9428. struct vec var_vec;
  9429. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9430. int i, truncated, uri_len;
  9431. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9432. return -1;
  9433. }
  9434. env->conn = conn;
  9435. env->buflen = CGI_ENVIRONMENT_SIZE;
  9436. env->bufused = 0;
  9437. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9438. if (env->buf == NULL) {
  9439. mg_cry_internal(conn,
  9440. "%s: Not enough memory for environmental buffer",
  9441. __func__);
  9442. return -1;
  9443. }
  9444. env->varlen = MAX_CGI_ENVIR_VARS;
  9445. env->varused = 0;
  9446. env->var =
  9447. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9448. if (env->var == NULL) {
  9449. mg_cry_internal(conn,
  9450. "%s: Not enough memory for environmental variables",
  9451. __func__);
  9452. mg_free(env->buf);
  9453. return -1;
  9454. }
  9455. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9456. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9457. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9458. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9459. /* Prepare the environment block */
  9460. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9461. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9462. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9463. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9464. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9465. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9466. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9467. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9468. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9469. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9470. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9471. /* SCRIPT_NAME */
  9472. uri_len = (int)strlen(conn->request_info.local_uri);
  9473. if (conn->path_info == NULL) {
  9474. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9475. /* URI: /path_to_script/script.cgi */
  9476. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9477. } else {
  9478. /* URI: /path_to_script/ ... using index.cgi */
  9479. const char *index_file = strrchr(prog, '/');
  9480. if (index_file) {
  9481. addenv(env,
  9482. "SCRIPT_NAME=%s%s",
  9483. conn->request_info.local_uri,
  9484. index_file + 1);
  9485. }
  9486. }
  9487. } else {
  9488. /* URI: /path_to_script/script.cgi/path_info */
  9489. addenv(env,
  9490. "SCRIPT_NAME=%.*s",
  9491. uri_len - (int)strlen(conn->path_info),
  9492. conn->request_info.local_uri);
  9493. }
  9494. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9495. if (conn->path_info == NULL) {
  9496. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9497. } else {
  9498. addenv(env,
  9499. "PATH_TRANSLATED=%s%s",
  9500. conn->dom_ctx->config[DOCUMENT_ROOT],
  9501. conn->path_info);
  9502. }
  9503. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9504. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9505. addenv(env, "CONTENT_TYPE=%s", s);
  9506. }
  9507. if (conn->request_info.query_string != NULL) {
  9508. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9509. }
  9510. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9511. addenv(env, "CONTENT_LENGTH=%s", s);
  9512. }
  9513. if ((s = getenv("PATH")) != NULL) {
  9514. addenv(env, "PATH=%s", s);
  9515. }
  9516. if (conn->path_info != NULL) {
  9517. addenv(env, "PATH_INFO=%s", conn->path_info);
  9518. }
  9519. if (conn->status_code > 0) {
  9520. /* CGI error handler should show the status code */
  9521. addenv(env, "STATUS=%d", conn->status_code);
  9522. }
  9523. #if defined(_WIN32)
  9524. if ((s = getenv("COMSPEC")) != NULL) {
  9525. addenv(env, "COMSPEC=%s", s);
  9526. }
  9527. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9528. addenv(env, "SYSTEMROOT=%s", s);
  9529. }
  9530. if ((s = getenv("SystemDrive")) != NULL) {
  9531. addenv(env, "SystemDrive=%s", s);
  9532. }
  9533. if ((s = getenv("ProgramFiles")) != NULL) {
  9534. addenv(env, "ProgramFiles=%s", s);
  9535. }
  9536. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9537. addenv(env, "ProgramFiles(x86)=%s", s);
  9538. }
  9539. #else
  9540. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9541. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9542. }
  9543. #endif /* _WIN32 */
  9544. if ((s = getenv("PERLLIB")) != NULL) {
  9545. addenv(env, "PERLLIB=%s", s);
  9546. }
  9547. if (conn->request_info.remote_user != NULL) {
  9548. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9549. addenv(env, "%s", "AUTH_TYPE=Digest");
  9550. }
  9551. /* Add all headers as HTTP_* variables */
  9552. for (i = 0; i < conn->request_info.num_headers; i++) {
  9553. (void)mg_snprintf(conn,
  9554. &truncated,
  9555. http_var_name,
  9556. sizeof(http_var_name),
  9557. "HTTP_%s",
  9558. conn->request_info.http_headers[i].name);
  9559. if (truncated) {
  9560. mg_cry_internal(conn,
  9561. "%s: HTTP header variable too long [%s]",
  9562. __func__,
  9563. conn->request_info.http_headers[i].name);
  9564. continue;
  9565. }
  9566. /* Convert variable name into uppercase, and change - to _ */
  9567. for (p = http_var_name; *p != '\0'; p++) {
  9568. if (*p == '-') {
  9569. *p = '_';
  9570. }
  9571. *p = (char)toupper((unsigned char)*p);
  9572. }
  9573. addenv(env,
  9574. "%s=%s",
  9575. http_var_name,
  9576. conn->request_info.http_headers[i].value);
  9577. }
  9578. /* Add user-specified variables */
  9579. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9580. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9581. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9582. }
  9583. env->var[env->varused] = NULL;
  9584. env->buf[env->bufused] = '\0';
  9585. return 0;
  9586. }
  9587. /* Data for CGI process control: PID and number of references */
  9588. struct process_control_data {
  9589. pid_t pid;
  9590. ptrdiff_t references;
  9591. };
  9592. static int
  9593. abort_cgi_process(void *data)
  9594. {
  9595. /* Waitpid checks for child status and won't work for a pid that does
  9596. * not identify a child of the current process. Thus, if the pid is
  9597. * reused, we will not affect a different process. */
  9598. struct process_control_data *proc = (struct process_control_data *)data;
  9599. int status = 0;
  9600. ptrdiff_t refs;
  9601. pid_t ret_pid;
  9602. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9603. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9604. /* Stop child process */
  9605. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9606. kill(proc->pid, SIGABRT);
  9607. /* Wait until process is terminated (don't leave zombies) */
  9608. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9609. ;
  9610. } else {
  9611. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9612. }
  9613. /* Dec reference counter */
  9614. refs = mg_atomic_dec(&proc->references);
  9615. if (refs == 0) {
  9616. /* no more references - free data */
  9617. mg_free(data);
  9618. }
  9619. return 0;
  9620. }
  9621. /* Local (static) function assumes all arguments are valid. */
  9622. static void
  9623. handle_cgi_request(struct mg_connection *conn,
  9624. const char *prog,
  9625. unsigned char cgi_config_idx)
  9626. {
  9627. char *buf;
  9628. size_t buflen;
  9629. int headers_len, data_len, i, truncated;
  9630. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9631. const char *status, *status_text, *connection_state;
  9632. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9633. struct mg_request_info ri;
  9634. struct cgi_environment blk;
  9635. FILE *in = NULL, *out = NULL, *err = NULL;
  9636. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9637. pid_t pid = (pid_t)-1;
  9638. struct process_control_data *proc = NULL;
  9639. #if defined(USE_TIMERS)
  9640. double cgi_timeout;
  9641. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9642. /* Get timeout in seconds */
  9643. cgi_timeout =
  9644. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9645. } else {
  9646. cgi_timeout =
  9647. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9648. }
  9649. #endif
  9650. buf = NULL;
  9651. buflen = conn->phys_ctx->max_request_size;
  9652. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9653. if (i != 0) {
  9654. blk.buf = NULL;
  9655. blk.var = NULL;
  9656. goto done;
  9657. }
  9658. /* CGI must be executed in its own directory. 'dir' must point to the
  9659. * directory containing executable program, 'p' must point to the
  9660. * executable program name relative to 'dir'. */
  9661. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9662. if (truncated) {
  9663. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9664. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9665. goto done;
  9666. }
  9667. if ((p = strrchr(dir, '/')) != NULL) {
  9668. *p++ = '\0';
  9669. } else {
  9670. dir[0] = '.';
  9671. dir[1] = '\0';
  9672. p = (char *)prog;
  9673. }
  9674. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9675. status = strerror(ERRNO);
  9676. mg_cry_internal(
  9677. conn,
  9678. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9679. prog,
  9680. status);
  9681. mg_send_http_error(conn,
  9682. 500,
  9683. "Error: Cannot create CGI pipe: %s",
  9684. status);
  9685. goto done;
  9686. }
  9687. proc = (struct process_control_data *)
  9688. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9689. if (proc == NULL) {
  9690. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9691. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9692. goto done;
  9693. }
  9694. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9695. pid = spawn_process(
  9696. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9697. if (pid == (pid_t)-1) {
  9698. status = strerror(ERRNO);
  9699. mg_cry_internal(
  9700. conn,
  9701. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9702. prog,
  9703. status);
  9704. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9705. mg_free(proc);
  9706. proc = NULL;
  9707. goto done;
  9708. }
  9709. /* Store data in shared process_control_data */
  9710. proc->pid = pid;
  9711. proc->references = 1;
  9712. #if defined(USE_TIMERS)
  9713. if (cgi_timeout > 0.0) {
  9714. proc->references = 2;
  9715. // Start a timer for CGI
  9716. timer_add(conn->phys_ctx,
  9717. cgi_timeout /* in seconds */,
  9718. 0.0,
  9719. 1,
  9720. abort_cgi_process,
  9721. (void *)proc,
  9722. NULL);
  9723. }
  9724. #endif
  9725. /* Parent closes only one side of the pipes.
  9726. * If we don't mark them as closed, close() attempt before
  9727. * return from this function throws an exception on Windows.
  9728. * Windows does not like when closed descriptor is closed again. */
  9729. (void)close(fdin[0]);
  9730. (void)close(fdout[1]);
  9731. (void)close(fderr[1]);
  9732. fdin[0] = fdout[1] = fderr[1] = -1;
  9733. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9734. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9735. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9736. status = strerror(ERRNO);
  9737. mg_cry_internal(conn,
  9738. "Error: CGI program \"%s\": Can not open fd: %s",
  9739. prog,
  9740. status);
  9741. mg_send_http_error(conn,
  9742. 500,
  9743. "Error: CGI can not open fd\nfdopen: %s",
  9744. status);
  9745. goto done;
  9746. }
  9747. setbuf(in, NULL);
  9748. setbuf(out, NULL);
  9749. setbuf(err, NULL);
  9750. fout.access.fp = out;
  9751. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9752. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9753. conn->content_len);
  9754. /* This is a POST/PUT request, or another request with body data. */
  9755. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9756. /* Error sending the body data */
  9757. mg_cry_internal(
  9758. conn,
  9759. "Error: CGI program \"%s\": Forward body data failed",
  9760. prog);
  9761. goto done;
  9762. }
  9763. }
  9764. /* Close so child gets an EOF. */
  9765. fclose(in);
  9766. in = NULL;
  9767. fdin[1] = -1;
  9768. /* Now read CGI reply into a buffer. We need to set correct
  9769. * status code, thus we need to see all HTTP headers first.
  9770. * Do not send anything back to client, until we buffer in all
  9771. * HTTP headers. */
  9772. data_len = 0;
  9773. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9774. if (buf == NULL) {
  9775. mg_send_http_error(conn,
  9776. 500,
  9777. "Error: Not enough memory for CGI buffer (%u bytes)",
  9778. (unsigned int)buflen);
  9779. mg_cry_internal(
  9780. conn,
  9781. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9782. "bytes)",
  9783. prog,
  9784. (unsigned int)buflen);
  9785. goto done;
  9786. }
  9787. DEBUG_TRACE("CGI: %s", "wait for response");
  9788. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9789. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9790. if (headers_len <= 0) {
  9791. /* Could not parse the CGI response. Check if some error message on
  9792. * stderr. */
  9793. i = pull_all(err, conn, buf, (int)buflen);
  9794. if (i > 0) {
  9795. /* CGI program explicitly sent an error */
  9796. /* Write the error message to the internal log */
  9797. mg_cry_internal(conn,
  9798. "Error: CGI program \"%s\" sent error "
  9799. "message: [%.*s]",
  9800. prog,
  9801. i,
  9802. buf);
  9803. /* Don't send the error message back to the client */
  9804. mg_send_http_error(conn,
  9805. 500,
  9806. "Error: CGI program \"%s\" failed.",
  9807. prog);
  9808. } else {
  9809. /* CGI program did not explicitly send an error, but a broken
  9810. * respon header */
  9811. mg_cry_internal(conn,
  9812. "Error: CGI program sent malformed or too big "
  9813. "(>%u bytes) HTTP headers: [%.*s]",
  9814. (unsigned)buflen,
  9815. data_len,
  9816. buf);
  9817. mg_send_http_error(conn,
  9818. 500,
  9819. "Error: CGI program sent malformed or too big "
  9820. "(>%u bytes) HTTP headers: [%.*s]",
  9821. (unsigned)buflen,
  9822. data_len,
  9823. buf);
  9824. }
  9825. /* in both cases, abort processing CGI */
  9826. goto done;
  9827. }
  9828. pbuf = buf;
  9829. buf[headers_len - 1] = '\0';
  9830. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9831. /* Make up and send the status line */
  9832. status_text = "OK";
  9833. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9834. != NULL) {
  9835. conn->status_code = atoi(status);
  9836. status_text = status;
  9837. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9838. status_text++;
  9839. }
  9840. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9841. != NULL) {
  9842. conn->status_code = 307;
  9843. } else {
  9844. conn->status_code = 200;
  9845. }
  9846. connection_state =
  9847. get_header(ri.http_headers, ri.num_headers, "Connection");
  9848. if (!header_has_option(connection_state, "keep-alive")) {
  9849. conn->must_close = 1;
  9850. }
  9851. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9852. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9853. /* Send headers */
  9854. for (i = 0; i < ri.num_headers; i++) {
  9855. DEBUG_TRACE("CGI header: %s: %s",
  9856. ri.http_headers[i].name,
  9857. ri.http_headers[i].value);
  9858. mg_printf(conn,
  9859. "%s: %s\r\n",
  9860. ri.http_headers[i].name,
  9861. ri.http_headers[i].value);
  9862. }
  9863. mg_write(conn, "\r\n", 2);
  9864. /* Send chunk of data that may have been read after the headers */
  9865. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9866. /* Read the rest of CGI output and send to the client */
  9867. DEBUG_TRACE("CGI: %s", "forward all data");
  9868. send_file_data(conn, &fout, 0, INT64_MAX);
  9869. DEBUG_TRACE("CGI: %s", "all data sent");
  9870. done:
  9871. mg_free(blk.var);
  9872. mg_free(blk.buf);
  9873. if (pid != (pid_t)-1) {
  9874. abort_cgi_process((void *)proc);
  9875. }
  9876. if (fdin[0] != -1) {
  9877. close(fdin[0]);
  9878. }
  9879. if (fdout[1] != -1) {
  9880. close(fdout[1]);
  9881. }
  9882. if (fderr[1] != -1) {
  9883. close(fderr[1]);
  9884. }
  9885. if (in != NULL) {
  9886. fclose(in);
  9887. } else if (fdin[1] != -1) {
  9888. close(fdin[1]);
  9889. }
  9890. if (out != NULL) {
  9891. fclose(out);
  9892. } else if (fdout[0] != -1) {
  9893. close(fdout[0]);
  9894. }
  9895. if (err != NULL) {
  9896. fclose(err);
  9897. } else if (fderr[0] != -1) {
  9898. close(fderr[0]);
  9899. }
  9900. mg_free(buf);
  9901. }
  9902. #endif /* !NO_CGI */
  9903. #if !defined(NO_FILES)
  9904. static void
  9905. mkcol(struct mg_connection *conn, const char *path)
  9906. {
  9907. int rc, body_len;
  9908. struct de de;
  9909. if (conn == NULL) {
  9910. return;
  9911. }
  9912. /* TODO (mid): Check the mg_send_http_error situations in this function
  9913. */
  9914. memset(&de.file, 0, sizeof(de.file));
  9915. if (!mg_stat(conn, path, &de.file)) {
  9916. mg_cry_internal(conn,
  9917. "%s: mg_stat(%s) failed: %s",
  9918. __func__,
  9919. path,
  9920. strerror(ERRNO));
  9921. }
  9922. if (de.file.last_modified) {
  9923. /* TODO (mid): This check does not seem to make any sense ! */
  9924. /* TODO (mid): Add a webdav unit test first, before changing
  9925. * anything here. */
  9926. mg_send_http_error(
  9927. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9928. return;
  9929. }
  9930. body_len = conn->data_len - conn->request_len;
  9931. if (body_len > 0) {
  9932. mg_send_http_error(
  9933. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9934. return;
  9935. }
  9936. rc = mg_mkdir(conn, path, 0755);
  9937. if (rc == 0) {
  9938. /* Create 201 "Created" response */
  9939. mg_response_header_start(conn, 201);
  9940. send_static_cache_header(conn);
  9941. send_additional_header(conn);
  9942. mg_response_header_add(conn, "Content-Length", "0", -1);
  9943. /* Send all headers - there is no body */
  9944. mg_response_header_send(conn);
  9945. } else {
  9946. if (errno == EEXIST) {
  9947. mg_send_http_error(
  9948. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9949. } else if (errno == EACCES) {
  9950. mg_send_http_error(
  9951. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9952. } else if (errno == ENOENT) {
  9953. mg_send_http_error(
  9954. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9955. } else {
  9956. mg_send_http_error(
  9957. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9958. }
  9959. }
  9960. }
  9961. static void
  9962. put_file(struct mg_connection *conn, const char *path)
  9963. {
  9964. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9965. const char *range;
  9966. int64_t r1, r2;
  9967. int rc;
  9968. if (conn == NULL) {
  9969. return;
  9970. }
  9971. if (mg_stat(conn, path, &file.stat)) {
  9972. /* File already exists */
  9973. conn->status_code = 200;
  9974. if (file.stat.is_directory) {
  9975. /* This is an already existing directory,
  9976. * so there is nothing to do for the server. */
  9977. rc = 0;
  9978. } else {
  9979. /* File exists and is not a directory. */
  9980. /* Can it be replaced? */
  9981. /* Check if the server may write this file */
  9982. if (access(path, W_OK) == 0) {
  9983. /* Access granted */
  9984. rc = 1;
  9985. } else {
  9986. mg_send_http_error(
  9987. conn,
  9988. 403,
  9989. "Error: Put not possible\nReplacing %s is not allowed",
  9990. path);
  9991. return;
  9992. }
  9993. }
  9994. } else {
  9995. /* File should be created */
  9996. conn->status_code = 201;
  9997. rc = put_dir(conn, path);
  9998. }
  9999. if (rc == 0) {
  10000. /* put_dir returns 0 if path is a directory */
  10001. /* Create response */
  10002. mg_response_header_start(conn, conn->status_code);
  10003. send_no_cache_header(conn);
  10004. send_additional_header(conn);
  10005. mg_response_header_add(conn, "Content-Length", "0", -1);
  10006. /* Send all headers - there is no body */
  10007. mg_response_header_send(conn);
  10008. /* Request to create a directory has been fulfilled successfully.
  10009. * No need to put a file. */
  10010. return;
  10011. }
  10012. if (rc == -1) {
  10013. /* put_dir returns -1 if the path is too long */
  10014. mg_send_http_error(conn,
  10015. 414,
  10016. "Error: Path too long\nput_dir(%s): %s",
  10017. path,
  10018. strerror(ERRNO));
  10019. return;
  10020. }
  10021. if (rc == -2) {
  10022. /* put_dir returns -2 if the directory can not be created */
  10023. mg_send_http_error(conn,
  10024. 500,
  10025. "Error: Can not create directory\nput_dir(%s): %s",
  10026. path,
  10027. strerror(ERRNO));
  10028. return;
  10029. }
  10030. /* A file should be created or overwritten. */
  10031. /* Currently CivetWeb does not nead read+write access. */
  10032. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10033. || file.access.fp == NULL) {
  10034. (void)mg_fclose(&file.access);
  10035. mg_send_http_error(conn,
  10036. 500,
  10037. "Error: Can not create file\nfopen(%s): %s",
  10038. path,
  10039. strerror(ERRNO));
  10040. return;
  10041. }
  10042. fclose_on_exec(&file.access, conn);
  10043. range = mg_get_header(conn, "Content-Range");
  10044. r1 = r2 = 0;
  10045. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10046. conn->status_code = 206; /* Partial content */
  10047. fseeko(file.access.fp, r1, SEEK_SET);
  10048. }
  10049. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10050. /* forward_body_data failed.
  10051. * The error code has already been sent to the client,
  10052. * and conn->status_code is already set. */
  10053. (void)mg_fclose(&file.access);
  10054. return;
  10055. }
  10056. if (mg_fclose(&file.access) != 0) {
  10057. /* fclose failed. This might have different reasons, but a likely
  10058. * one is "no space on disk", http 507. */
  10059. conn->status_code = 507;
  10060. }
  10061. /* Create response (status_code has been set before) */
  10062. mg_response_header_start(conn, conn->status_code);
  10063. send_no_cache_header(conn);
  10064. send_additional_header(conn);
  10065. mg_response_header_add(conn, "Content-Length", "0", -1);
  10066. /* Send all headers - there is no body */
  10067. mg_response_header_send(conn);
  10068. }
  10069. static void
  10070. delete_file(struct mg_connection *conn, const char *path)
  10071. {
  10072. struct de de;
  10073. memset(&de.file, 0, sizeof(de.file));
  10074. if (!mg_stat(conn, path, &de.file)) {
  10075. /* mg_stat returns 0 if the file does not exist */
  10076. mg_send_http_error(conn,
  10077. 404,
  10078. "Error: Cannot delete file\nFile %s not found",
  10079. path);
  10080. return;
  10081. }
  10082. if (de.file.is_directory) {
  10083. if (remove_directory(conn, path)) {
  10084. /* Delete is successful: Return 204 without content. */
  10085. mg_send_http_error(conn, 204, "%s", "");
  10086. } else {
  10087. /* Delete is not successful: Return 500 (Server error). */
  10088. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10089. }
  10090. return;
  10091. }
  10092. /* This is an existing file (not a directory).
  10093. * Check if write permission is granted. */
  10094. if (access(path, W_OK) != 0) {
  10095. /* File is read only */
  10096. mg_send_http_error(
  10097. conn,
  10098. 403,
  10099. "Error: Delete not possible\nDeleting %s is not allowed",
  10100. path);
  10101. return;
  10102. }
  10103. /* Try to delete it. */
  10104. if (mg_remove(conn, path) == 0) {
  10105. /* Delete was successful: Return 204 without content. */
  10106. mg_response_header_start(conn, 204);
  10107. send_no_cache_header(conn);
  10108. send_additional_header(conn);
  10109. mg_response_header_add(conn, "Content-Length", "0", -1);
  10110. mg_response_header_send(conn);
  10111. } else {
  10112. /* Delete not successful (file locked). */
  10113. mg_send_http_error(conn,
  10114. 423,
  10115. "Error: Cannot delete file\nremove(%s): %s",
  10116. path,
  10117. strerror(ERRNO));
  10118. }
  10119. }
  10120. #endif /* !NO_FILES */
  10121. #if !defined(NO_FILESYSTEMS)
  10122. static void
  10123. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10124. static void
  10125. do_ssi_include(struct mg_connection *conn,
  10126. const char *ssi,
  10127. char *tag,
  10128. int include_level)
  10129. {
  10130. char file_name[MG_BUF_LEN], path[512], *p;
  10131. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10132. size_t len;
  10133. int truncated = 0;
  10134. if (conn == NULL) {
  10135. return;
  10136. }
  10137. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10138. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10139. * always < MG_BUF_LEN. */
  10140. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10141. /* File name is relative to the webserver root */
  10142. file_name[511] = 0;
  10143. (void)mg_snprintf(conn,
  10144. &truncated,
  10145. path,
  10146. sizeof(path),
  10147. "%s/%s",
  10148. conn->dom_ctx->config[DOCUMENT_ROOT],
  10149. file_name);
  10150. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10151. /* File name is relative to the webserver working directory
  10152. * or it is absolute system path */
  10153. file_name[511] = 0;
  10154. (void)
  10155. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10156. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10157. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10158. /* File name is relative to the currect document */
  10159. file_name[511] = 0;
  10160. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10161. if (!truncated) {
  10162. if ((p = strrchr(path, '/')) != NULL) {
  10163. p[1] = '\0';
  10164. }
  10165. len = strlen(path);
  10166. (void)mg_snprintf(conn,
  10167. &truncated,
  10168. path + len,
  10169. sizeof(path) - len,
  10170. "%s",
  10171. file_name);
  10172. }
  10173. } else {
  10174. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10175. return;
  10176. }
  10177. if (truncated) {
  10178. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10179. return;
  10180. }
  10181. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10182. mg_cry_internal(conn,
  10183. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10184. tag,
  10185. path,
  10186. strerror(ERRNO));
  10187. } else {
  10188. fclose_on_exec(&file.access, conn);
  10189. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10190. > 0) {
  10191. send_ssi_file(conn, path, &file, include_level + 1);
  10192. } else {
  10193. send_file_data(conn, &file, 0, INT64_MAX);
  10194. }
  10195. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10196. }
  10197. }
  10198. #if !defined(NO_POPEN)
  10199. static void
  10200. do_ssi_exec(struct mg_connection *conn, char *tag)
  10201. {
  10202. char cmd[1024] = "";
  10203. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10204. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10205. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10206. } else {
  10207. cmd[1023] = 0;
  10208. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10209. mg_cry_internal(conn,
  10210. "Cannot SSI #exec: [%s]: %s",
  10211. cmd,
  10212. strerror(ERRNO));
  10213. } else {
  10214. send_file_data(conn, &file, 0, INT64_MAX);
  10215. pclose(file.access.fp);
  10216. }
  10217. }
  10218. }
  10219. #endif /* !NO_POPEN */
  10220. static int
  10221. mg_fgetc(struct mg_file *filep)
  10222. {
  10223. if (filep == NULL) {
  10224. return EOF;
  10225. }
  10226. if (filep->access.fp != NULL) {
  10227. return fgetc(filep->access.fp);
  10228. } else {
  10229. return EOF;
  10230. }
  10231. }
  10232. static void
  10233. send_ssi_file(struct mg_connection *conn,
  10234. const char *path,
  10235. struct mg_file *filep,
  10236. int include_level)
  10237. {
  10238. char buf[MG_BUF_LEN];
  10239. int ch, len, in_tag, in_ssi_tag;
  10240. if (include_level > 10) {
  10241. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10242. return;
  10243. }
  10244. in_tag = in_ssi_tag = len = 0;
  10245. /* Read file, byte by byte, and look for SSI include tags */
  10246. while ((ch = mg_fgetc(filep)) != EOF) {
  10247. if (in_tag) {
  10248. /* We are in a tag, either SSI tag or html tag */
  10249. if (ch == '>') {
  10250. /* Tag is closing */
  10251. buf[len++] = '>';
  10252. if (in_ssi_tag) {
  10253. /* Handle SSI tag */
  10254. buf[len] = 0;
  10255. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10256. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10257. #if !defined(NO_POPEN)
  10258. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10259. do_ssi_exec(conn, buf + 9);
  10260. #endif /* !NO_POPEN */
  10261. } else {
  10262. mg_cry_internal(conn,
  10263. "%s: unknown SSI "
  10264. "command: \"%s\"",
  10265. path,
  10266. buf);
  10267. }
  10268. len = 0;
  10269. in_ssi_tag = in_tag = 0;
  10270. } else {
  10271. /* Not an SSI tag */
  10272. /* Flush buffer */
  10273. (void)mg_write(conn, buf, (size_t)len);
  10274. len = 0;
  10275. in_tag = 0;
  10276. }
  10277. } else {
  10278. /* Tag is still open */
  10279. buf[len++] = (char)(ch & 0xff);
  10280. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10281. /* All SSI tags start with <!--# */
  10282. in_ssi_tag = 1;
  10283. }
  10284. if ((len + 2) > (int)sizeof(buf)) {
  10285. /* Tag to long for buffer */
  10286. mg_cry_internal(conn, "%s: tag is too large", path);
  10287. return;
  10288. }
  10289. }
  10290. } else {
  10291. /* We are not in a tag yet. */
  10292. if (ch == '<') {
  10293. /* Tag is opening */
  10294. in_tag = 1;
  10295. if (len > 0) {
  10296. /* Flush current buffer.
  10297. * Buffer is filled with "len" bytes. */
  10298. (void)mg_write(conn, buf, (size_t)len);
  10299. }
  10300. /* Store the < */
  10301. len = 1;
  10302. buf[0] = '<';
  10303. } else {
  10304. /* No Tag */
  10305. /* Add data to buffer */
  10306. buf[len++] = (char)(ch & 0xff);
  10307. /* Flush if buffer is full */
  10308. if (len == (int)sizeof(buf)) {
  10309. mg_write(conn, buf, (size_t)len);
  10310. len = 0;
  10311. }
  10312. }
  10313. }
  10314. }
  10315. /* Send the rest of buffered data */
  10316. if (len > 0) {
  10317. mg_write(conn, buf, (size_t)len);
  10318. }
  10319. }
  10320. static void
  10321. handle_ssi_file_request(struct mg_connection *conn,
  10322. const char *path,
  10323. struct mg_file *filep)
  10324. {
  10325. char date[64];
  10326. time_t curtime = time(NULL);
  10327. const char *cors_orig_cfg;
  10328. const char *cors1, *cors2;
  10329. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10330. return;
  10331. }
  10332. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10333. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10334. /* Cross-origin resource sharing (CORS). */
  10335. cors1 = "Access-Control-Allow-Origin";
  10336. cors2 = cors_orig_cfg;
  10337. } else {
  10338. cors1 = cors2 = "";
  10339. }
  10340. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10341. /* File exists (precondition for calling this function),
  10342. * but can not be opened by the server. */
  10343. mg_send_http_error(conn,
  10344. 500,
  10345. "Error: Cannot read file\nfopen(%s): %s",
  10346. path,
  10347. strerror(ERRNO));
  10348. } else {
  10349. /* Set "must_close" for HTTP/1.x, since we do not know the
  10350. * content length */
  10351. conn->must_close = 1;
  10352. gmt_time_string(date, sizeof(date), &curtime);
  10353. fclose_on_exec(&filep->access, conn);
  10354. /* 200 OK response */
  10355. mg_response_header_start(conn, 200);
  10356. send_no_cache_header(conn);
  10357. send_additional_header(conn);
  10358. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10359. if (cors1[0]) {
  10360. mg_response_header_add(conn, cors1, cors2, -1);
  10361. }
  10362. mg_response_header_send(conn);
  10363. /* Header sent, now send body */
  10364. send_ssi_file(conn, path, filep, 0);
  10365. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10366. }
  10367. }
  10368. #endif /* NO_FILESYSTEMS */
  10369. #if !defined(NO_FILES)
  10370. static void
  10371. send_options(struct mg_connection *conn)
  10372. {
  10373. if (!conn) {
  10374. return;
  10375. }
  10376. /* We do not set a "Cache-Control" header here, but leave the default.
  10377. * Since browsers do not send an OPTIONS request, we can not test the
  10378. * effect anyway. */
  10379. mg_response_header_start(conn, 200);
  10380. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10381. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10382. /* Use the same as before */
  10383. mg_response_header_add(
  10384. conn,
  10385. "Allow",
  10386. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10387. -1);
  10388. mg_response_header_add(conn, "DAV", "1", -1);
  10389. } else {
  10390. /* TODO: Check this later for HTTP/2 */
  10391. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10392. }
  10393. send_additional_header(conn);
  10394. mg_response_header_send(conn);
  10395. }
  10396. /* Writes PROPFIND properties for a collection element */
  10397. static int
  10398. print_props(struct mg_connection *conn,
  10399. const char *uri,
  10400. const char *name,
  10401. struct mg_file_stat *filep)
  10402. {
  10403. size_t href_size, i, j;
  10404. int len;
  10405. char *href, mtime[64];
  10406. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10407. return 0;
  10408. }
  10409. /* Estimate worst case size for encoding */
  10410. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10411. href = (char *)mg_malloc(href_size);
  10412. if (href == NULL) {
  10413. return 0;
  10414. }
  10415. len = mg_url_encode(uri, href, href_size);
  10416. if (len >= 0) {
  10417. /* Append an extra string */
  10418. mg_url_encode(name, href + len, href_size - (size_t)len);
  10419. }
  10420. /* Directory separator should be preserved. */
  10421. for (i = j = 0; href[i]; j++) {
  10422. if (!strncmp(href + i, "%2f", 3)) {
  10423. href[j] = '/';
  10424. i += 3;
  10425. } else {
  10426. href[j] = href[i++];
  10427. }
  10428. }
  10429. href[j] = '\0';
  10430. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10431. mg_printf(conn,
  10432. "<d:response>"
  10433. "<d:href>%s</d:href>"
  10434. "<d:propstat>"
  10435. "<d:prop>"
  10436. "<d:resourcetype>%s</d:resourcetype>"
  10437. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10438. "<d:getlastmodified>%s</d:getlastmodified>"
  10439. "</d:prop>"
  10440. "<d:status>HTTP/1.1 200 OK</d:status>"
  10441. "</d:propstat>"
  10442. "</d:response>\n",
  10443. href,
  10444. filep->is_directory ? "<d:collection/>" : "",
  10445. filep->size,
  10446. mtime);
  10447. mg_free(href);
  10448. return 1;
  10449. }
  10450. static int
  10451. print_dav_dir_entry(struct de *de, void *data)
  10452. {
  10453. struct mg_connection *conn = (struct mg_connection *)data;
  10454. if (!de || !conn
  10455. || !print_props(
  10456. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10457. /* stop scan */
  10458. return 1;
  10459. }
  10460. return 0;
  10461. }
  10462. static void
  10463. handle_propfind(struct mg_connection *conn,
  10464. const char *path,
  10465. struct mg_file_stat *filep)
  10466. {
  10467. const char *depth = mg_get_header(conn, "Depth");
  10468. char date[64];
  10469. time_t curtime = time(NULL);
  10470. gmt_time_string(date, sizeof(date), &curtime);
  10471. if (!conn || !path || !filep || !conn->dom_ctx) {
  10472. return;
  10473. }
  10474. conn->must_close = 1;
  10475. /* return 207 "Multi-Status" */
  10476. mg_response_header_start(conn, 207);
  10477. send_static_cache_header(conn);
  10478. send_additional_header(conn);
  10479. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10480. mg_response_header_send(conn);
  10481. /* Content */
  10482. mg_printf(conn,
  10483. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10484. "<d:multistatus xmlns:d='DAV:'>\n");
  10485. /* Print properties for the requested resource itself */
  10486. print_props(conn, conn->request_info.local_uri, "", filep);
  10487. /* If it is a directory, print directory entries too if Depth is not 0
  10488. */
  10489. if (filep->is_directory
  10490. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10491. "yes")
  10492. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10493. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10494. }
  10495. mg_printf(conn, "%s\n", "</d:multistatus>");
  10496. }
  10497. #endif
  10498. void
  10499. mg_lock_connection(struct mg_connection *conn)
  10500. {
  10501. if (conn) {
  10502. (void)pthread_mutex_lock(&conn->mutex);
  10503. }
  10504. }
  10505. void
  10506. mg_unlock_connection(struct mg_connection *conn)
  10507. {
  10508. if (conn) {
  10509. (void)pthread_mutex_unlock(&conn->mutex);
  10510. }
  10511. }
  10512. void
  10513. mg_lock_context(struct mg_context *ctx)
  10514. {
  10515. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10516. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10517. }
  10518. }
  10519. void
  10520. mg_unlock_context(struct mg_context *ctx)
  10521. {
  10522. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10523. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10524. }
  10525. }
  10526. #if defined(USE_LUA)
  10527. #include "mod_lua.inl"
  10528. #endif /* USE_LUA */
  10529. #if defined(USE_DUKTAPE)
  10530. #include "mod_duktape.inl"
  10531. #endif /* USE_DUKTAPE */
  10532. #if defined(USE_WEBSOCKET)
  10533. #if !defined(NO_SSL_DL)
  10534. #define SHA_API static
  10535. #include "sha1.inl"
  10536. #endif
  10537. static int
  10538. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10539. {
  10540. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10541. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10542. SHA_CTX sha_ctx;
  10543. int truncated;
  10544. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10545. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10546. if (truncated) {
  10547. conn->must_close = 1;
  10548. return 0;
  10549. }
  10550. DEBUG_TRACE("%s", "Send websocket handshake");
  10551. SHA1_Init(&sha_ctx);
  10552. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10553. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10554. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10555. mg_printf(conn,
  10556. "HTTP/1.1 101 Switching Protocols\r\n"
  10557. "Upgrade: websocket\r\n"
  10558. "Connection: Upgrade\r\n"
  10559. "Sec-WebSocket-Accept: %s\r\n",
  10560. b64_sha);
  10561. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10562. // Send negotiated compression extension parameters
  10563. websocket_deflate_response(conn);
  10564. #endif
  10565. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10566. mg_printf(conn,
  10567. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10568. conn->request_info.acceptedWebSocketSubprotocol);
  10569. } else {
  10570. mg_printf(conn, "%s", "\r\n");
  10571. }
  10572. return 1;
  10573. }
  10574. #if !defined(MG_MAX_UNANSWERED_PING)
  10575. /* Configuration of the maximum number of websocket PINGs that might
  10576. * stay unanswered before the connection is considered broken.
  10577. * Note: The name of this define may still change (until it is
  10578. * defined as a compile parameter in a documentation).
  10579. */
  10580. #define MG_MAX_UNANSWERED_PING (5)
  10581. #endif
  10582. static void
  10583. read_websocket(struct mg_connection *conn,
  10584. mg_websocket_data_handler ws_data_handler,
  10585. void *callback_data)
  10586. {
  10587. /* Pointer to the beginning of the portion of the incoming websocket
  10588. * message queue.
  10589. * The original websocket upgrade request is never removed, so the queue
  10590. * begins after it. */
  10591. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10592. int n, error, exit_by_callback;
  10593. int ret;
  10594. /* body_len is the length of the entire queue in bytes
  10595. * len is the length of the current message
  10596. * data_len is the length of the current message's data payload
  10597. * header_len is the length of the current message's header */
  10598. size_t i, len, mask_len = 0, header_len, body_len;
  10599. uint64_t data_len = 0;
  10600. /* "The masking key is a 32-bit value chosen at random by the client."
  10601. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10602. */
  10603. unsigned char mask[4];
  10604. /* data points to the place where the message is stored when passed to
  10605. * the websocket_data callback. This is either mem on the stack, or a
  10606. * dynamically allocated buffer if it is too large. */
  10607. unsigned char mem[4096];
  10608. unsigned char mop; /* mask flag and opcode */
  10609. /* Variables used for connection monitoring */
  10610. double timeout = -1.0;
  10611. int enable_ping_pong = 0;
  10612. int ping_count = 0;
  10613. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10614. enable_ping_pong =
  10615. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10616. "yes");
  10617. }
  10618. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10619. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10620. }
  10621. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10622. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10623. }
  10624. if (timeout <= 0.0) {
  10625. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10626. }
  10627. /* Enter data processing loop */
  10628. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10629. conn->request_info.remote_addr,
  10630. conn->request_info.remote_port);
  10631. conn->in_websocket_handling = 1;
  10632. mg_set_thread_name("wsock");
  10633. /* Loop continuously, reading messages from the socket, invoking the
  10634. * callback, and waiting repeatedly until an error occurs. */
  10635. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10636. && (!conn->must_close)) {
  10637. header_len = 0;
  10638. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10639. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10640. len = buf[1] & 127;
  10641. mask_len = (buf[1] & 128) ? 4 : 0;
  10642. if ((len < 126) && (body_len >= mask_len)) {
  10643. /* inline 7-bit length field */
  10644. data_len = len;
  10645. header_len = 2 + mask_len;
  10646. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10647. /* 16-bit length field */
  10648. header_len = 4 + mask_len;
  10649. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10650. } else if (body_len >= (10 + mask_len)) {
  10651. /* 64-bit length field */
  10652. uint32_t l1, l2;
  10653. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10654. memcpy(&l2, &buf[6], 4);
  10655. header_len = 10 + mask_len;
  10656. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10657. if (data_len > (uint64_t)0x7FFF0000ul) {
  10658. /* no can do */
  10659. mg_cry_internal(
  10660. conn,
  10661. "%s",
  10662. "websocket out of memory; closing connection");
  10663. break;
  10664. }
  10665. }
  10666. }
  10667. if ((header_len > 0) && (body_len >= header_len)) {
  10668. /* Allocate space to hold websocket payload */
  10669. unsigned char *data = mem;
  10670. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10671. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10672. conn->phys_ctx);
  10673. if (data == NULL) {
  10674. /* Allocation failed, exit the loop and then close the
  10675. * connection */
  10676. mg_cry_internal(
  10677. conn,
  10678. "%s",
  10679. "websocket out of memory; closing connection");
  10680. break;
  10681. }
  10682. }
  10683. /* Copy the mask before we shift the queue and destroy it */
  10684. if (mask_len > 0) {
  10685. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10686. } else {
  10687. memset(mask, 0, sizeof(mask));
  10688. }
  10689. /* Read frame payload from the first message in the queue into
  10690. * data and advance the queue by moving the memory in place. */
  10691. DEBUG_ASSERT(body_len >= header_len);
  10692. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10693. mop = buf[0]; /* current mask and opcode */
  10694. /* Overflow case */
  10695. len = body_len - header_len;
  10696. memcpy(data, buf + header_len, len);
  10697. error = 0;
  10698. while ((uint64_t)len < data_len) {
  10699. n = pull_inner(NULL,
  10700. conn,
  10701. (char *)(data + len),
  10702. (int)(data_len - len),
  10703. timeout);
  10704. if (n <= -2) {
  10705. error = 1;
  10706. break;
  10707. } else if (n > 0) {
  10708. len += (size_t)n;
  10709. } else {
  10710. /* Timeout: should retry */
  10711. /* TODO: retry condition */
  10712. }
  10713. }
  10714. if (error) {
  10715. mg_cry_internal(
  10716. conn,
  10717. "%s",
  10718. "Websocket pull failed; closing connection");
  10719. if (data != mem) {
  10720. mg_free(data);
  10721. }
  10722. break;
  10723. }
  10724. conn->data_len = conn->request_len;
  10725. } else {
  10726. mop = buf[0]; /* current mask and opcode, overwritten by
  10727. * memmove() */
  10728. /* Length of the message being read at the front of the
  10729. * queue. Cast to 31 bit is OK, since we limited
  10730. * data_len before. */
  10731. len = (size_t)data_len + header_len;
  10732. /* Copy the data payload into the data pointer for the
  10733. * callback. Cast to 31 bit is OK, since we
  10734. * limited data_len */
  10735. memcpy(data, buf + header_len, (size_t)data_len);
  10736. /* Move the queue forward len bytes */
  10737. memmove(buf, buf + len, body_len - len);
  10738. /* Mark the queue as advanced */
  10739. conn->data_len -= (int)len;
  10740. }
  10741. /* Apply mask if necessary */
  10742. if (mask_len > 0) {
  10743. for (i = 0; i < (size_t)data_len; i++) {
  10744. data[i] ^= mask[i & 3];
  10745. }
  10746. }
  10747. exit_by_callback = 0;
  10748. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10749. /* filter PONG messages */
  10750. DEBUG_TRACE("PONG from %s:%u",
  10751. conn->request_info.remote_addr,
  10752. conn->request_info.remote_port);
  10753. /* No unanwered PINGs left */
  10754. ping_count = 0;
  10755. } else if (enable_ping_pong
  10756. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10757. /* reply PING messages */
  10758. DEBUG_TRACE("Reply PING from %s:%u",
  10759. conn->request_info.remote_addr,
  10760. conn->request_info.remote_port);
  10761. ret = mg_websocket_write(conn,
  10762. MG_WEBSOCKET_OPCODE_PONG,
  10763. (char *)data,
  10764. (size_t)data_len);
  10765. if (ret <= 0) {
  10766. /* Error: send failed */
  10767. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10768. break;
  10769. }
  10770. } else {
  10771. /* Exit the loop if callback signals to exit (server side),
  10772. * or "connection close" opcode received (client side). */
  10773. if (ws_data_handler != NULL) {
  10774. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10775. if (mop & 0x40) {
  10776. /* Inflate the data received if bit RSV1 is set. */
  10777. if (!conn->websocket_deflate_initialized) {
  10778. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10779. exit_by_callback = 1;
  10780. }
  10781. if (!exit_by_callback) {
  10782. size_t inflate_buf_size_old = 0;
  10783. size_t inflate_buf_size =
  10784. data_len
  10785. * 4; // Initial guess of the inflated message
  10786. // size. We double the memory when needed.
  10787. Bytef *inflated = NULL;
  10788. Bytef *new_mem = NULL;
  10789. conn->websocket_inflate_state.avail_in =
  10790. (uInt)(data_len + 4);
  10791. conn->websocket_inflate_state.next_in = data;
  10792. // Add trailing 0x00 0x00 0xff 0xff bytes
  10793. data[data_len] = '\x00';
  10794. data[data_len + 1] = '\x00';
  10795. data[data_len + 2] = '\xff';
  10796. data[data_len + 3] = '\xff';
  10797. do {
  10798. if (inflate_buf_size_old == 0) {
  10799. new_mem =
  10800. (Bytef *)mg_calloc(inflate_buf_size,
  10801. sizeof(Bytef));
  10802. } else {
  10803. inflate_buf_size *= 2;
  10804. new_mem =
  10805. (Bytef *)mg_realloc(inflated,
  10806. inflate_buf_size);
  10807. }
  10808. if (new_mem == NULL) {
  10809. mg_cry_internal(
  10810. conn,
  10811. "Out of memory: Cannot allocate "
  10812. "inflate buffer of %lu bytes",
  10813. (unsigned long)inflate_buf_size);
  10814. exit_by_callback = 1;
  10815. break;
  10816. }
  10817. inflated = new_mem;
  10818. conn->websocket_inflate_state.avail_out =
  10819. (uInt)(inflate_buf_size
  10820. - inflate_buf_size_old);
  10821. conn->websocket_inflate_state.next_out =
  10822. inflated + inflate_buf_size_old;
  10823. ret = inflate(&conn->websocket_inflate_state,
  10824. Z_SYNC_FLUSH);
  10825. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  10826. || ret == Z_MEM_ERROR) {
  10827. mg_cry_internal(
  10828. conn,
  10829. "ZLIB inflate error: %i %s",
  10830. ret,
  10831. (conn->websocket_inflate_state.msg
  10832. ? conn->websocket_inflate_state.msg
  10833. : "<no error message>"));
  10834. exit_by_callback = 1;
  10835. break;
  10836. }
  10837. inflate_buf_size_old = inflate_buf_size;
  10838. } while (conn->websocket_inflate_state.avail_out
  10839. == 0);
  10840. inflate_buf_size -=
  10841. conn->websocket_inflate_state.avail_out;
  10842. if (!ws_data_handler(conn,
  10843. mop,
  10844. (char *)inflated,
  10845. inflate_buf_size,
  10846. callback_data)) {
  10847. exit_by_callback = 1;
  10848. }
  10849. mg_free(inflated);
  10850. }
  10851. } else
  10852. #endif
  10853. if (!ws_data_handler(conn,
  10854. mop,
  10855. (char *)data,
  10856. (size_t)data_len,
  10857. callback_data)) {
  10858. exit_by_callback = 1;
  10859. }
  10860. }
  10861. }
  10862. /* It a buffer has been allocated, free it again */
  10863. if (data != mem) {
  10864. mg_free(data);
  10865. }
  10866. if (exit_by_callback) {
  10867. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10868. conn->request_info.remote_addr,
  10869. conn->request_info.remote_port);
  10870. break;
  10871. }
  10872. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10873. /* Opcode == 8, connection close */
  10874. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10875. conn->request_info.remote_addr,
  10876. conn->request_info.remote_port);
  10877. break;
  10878. }
  10879. /* Not breaking the loop, process next websocket frame. */
  10880. } else {
  10881. /* Read from the socket into the next available location in the
  10882. * message queue. */
  10883. n = pull_inner(NULL,
  10884. conn,
  10885. conn->buf + conn->data_len,
  10886. conn->buf_size - conn->data_len,
  10887. timeout);
  10888. if (n <= -2) {
  10889. /* Error, no bytes read */
  10890. DEBUG_TRACE("PULL from %s:%u failed",
  10891. conn->request_info.remote_addr,
  10892. conn->request_info.remote_port);
  10893. break;
  10894. }
  10895. if (n > 0) {
  10896. conn->data_len += n;
  10897. /* Reset open PING count */
  10898. ping_count = 0;
  10899. } else {
  10900. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10901. && (!conn->must_close)) {
  10902. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10903. /* Stop sending PING */
  10904. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10905. "- closing connection",
  10906. ping_count,
  10907. conn->request_info.remote_addr,
  10908. conn->request_info.remote_port);
  10909. break;
  10910. }
  10911. if (enable_ping_pong) {
  10912. /* Send Websocket PING message */
  10913. DEBUG_TRACE("PING to %s:%u",
  10914. conn->request_info.remote_addr,
  10915. conn->request_info.remote_port);
  10916. ret = mg_websocket_write(conn,
  10917. MG_WEBSOCKET_OPCODE_PING,
  10918. NULL,
  10919. 0);
  10920. if (ret <= 0) {
  10921. /* Error: send failed */
  10922. DEBUG_TRACE("Send PING failed (%i)", ret);
  10923. break;
  10924. }
  10925. ping_count++;
  10926. }
  10927. }
  10928. /* Timeout: should retry */
  10929. /* TODO: get timeout def */
  10930. }
  10931. }
  10932. }
  10933. /* Leave data processing loop */
  10934. mg_set_thread_name("worker");
  10935. conn->in_websocket_handling = 0;
  10936. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10937. conn->request_info.remote_addr,
  10938. conn->request_info.remote_port);
  10939. }
  10940. static int
  10941. mg_websocket_write_exec(struct mg_connection *conn,
  10942. int opcode,
  10943. const char *data,
  10944. size_t dataLen,
  10945. uint32_t masking_key)
  10946. {
  10947. unsigned char header[14];
  10948. size_t headerLen;
  10949. int retval;
  10950. #if defined(GCC_DIAGNOSTIC)
  10951. /* Disable spurious conversion warning for GCC */
  10952. #pragma GCC diagnostic push
  10953. #pragma GCC diagnostic ignored "-Wconversion"
  10954. #endif
  10955. /* Note that POSIX/Winsock's send() is threadsafe
  10956. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10957. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10958. * push(), although that is only a problem if the packet is large or
  10959. * outgoing buffer is full). */
  10960. /* TODO: Check if this lock should be moved to user land.
  10961. * Currently the server sets this lock for websockets, but
  10962. * not for any other connection. It must be set for every
  10963. * conn read/written by more than one thread, no matter if
  10964. * it is a websocket or regular connection. */
  10965. (void)mg_lock_connection(conn);
  10966. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10967. size_t deflated_size = 0;
  10968. Bytef *deflated = 0;
  10969. // Deflate websocket messages over 100kb
  10970. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  10971. if (use_deflate) {
  10972. if (!conn->websocket_deflate_initialized) {
  10973. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10974. return 0;
  10975. }
  10976. // Deflating the message
  10977. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  10978. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  10979. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  10980. deflated_size = (Bytef *)compressBound((uLong)dataLen);
  10981. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  10982. if (deflated == NULL) {
  10983. mg_cry_internal(
  10984. conn,
  10985. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  10986. (unsigned long)deflated_size);
  10987. mg_unlock_connection(conn);
  10988. return -1;
  10989. }
  10990. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  10991. conn->websocket_deflate_state.next_out = deflated;
  10992. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  10993. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  10994. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  10995. } else
  10996. #endif
  10997. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10998. #if defined(GCC_DIAGNOSTIC)
  10999. #pragma GCC diagnostic pop
  11000. #endif
  11001. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11002. if (dataLen < 126) {
  11003. /* inline 7-bit length field */
  11004. header[1] = (unsigned char)dataLen;
  11005. headerLen = 2;
  11006. } else if (dataLen <= 0xFFFF) {
  11007. /* 16-bit length field */
  11008. uint16_t len = htons((uint16_t)dataLen);
  11009. header[1] = 126;
  11010. memcpy(header + 2, &len, 2);
  11011. headerLen = 4;
  11012. } else {
  11013. /* 64-bit length field */
  11014. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11015. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11016. header[1] = 127;
  11017. memcpy(header + 2, &len1, 4);
  11018. memcpy(header + 6, &len2, 4);
  11019. headerLen = 10;
  11020. }
  11021. if (masking_key) {
  11022. /* add mask */
  11023. header[1] |= 0x80;
  11024. memcpy(header + headerLen, &masking_key, 4);
  11025. headerLen += 4;
  11026. }
  11027. retval = mg_write(conn, header, headerLen);
  11028. if (retval != (int)headerLen) {
  11029. /* Did not send complete header */
  11030. retval = -1;
  11031. } else {
  11032. if (dataLen > 0) {
  11033. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11034. if (use_deflate) {
  11035. retval = mg_write(conn, deflated, dataLen);
  11036. mg_free(deflated);
  11037. } else
  11038. #endif
  11039. retval = mg_write(conn, data, dataLen);
  11040. }
  11041. /* if dataLen == 0, the header length (2) is returned */
  11042. }
  11043. /* TODO: Remove this unlock as well, when lock is removed. */
  11044. mg_unlock_connection(conn);
  11045. return retval;
  11046. }
  11047. int
  11048. mg_websocket_write(struct mg_connection *conn,
  11049. int opcode,
  11050. const char *data,
  11051. size_t dataLen)
  11052. {
  11053. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11054. }
  11055. static void
  11056. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11057. {
  11058. size_t i = 0;
  11059. i = 0;
  11060. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11061. /* Convert in 32 bit words, if data is 4 byte aligned */
  11062. while (i < (in_len - 3)) {
  11063. *(uint32_t *)(void *)(out + i) =
  11064. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11065. i += 4;
  11066. }
  11067. }
  11068. if (i != in_len) {
  11069. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11070. while (i < in_len) {
  11071. *(uint8_t *)(void *)(out + i) =
  11072. *(uint8_t *)(void *)(in + i)
  11073. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11074. i++;
  11075. }
  11076. }
  11077. }
  11078. int
  11079. mg_websocket_client_write(struct mg_connection *conn,
  11080. int opcode,
  11081. const char *data,
  11082. size_t dataLen)
  11083. {
  11084. int retval = -1;
  11085. char *masked_data =
  11086. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11087. uint32_t masking_key = 0;
  11088. if (masked_data == NULL) {
  11089. /* Return -1 in an error case */
  11090. mg_cry_internal(conn,
  11091. "%s",
  11092. "Cannot allocate buffer for masked websocket response: "
  11093. "Out of memory");
  11094. return -1;
  11095. }
  11096. do {
  11097. /* Get a masking key - but not 0 */
  11098. masking_key = (uint32_t)get_random();
  11099. } while (masking_key == 0);
  11100. mask_data(data, dataLen, masking_key, masked_data);
  11101. retval = mg_websocket_write_exec(
  11102. conn, opcode, masked_data, dataLen, masking_key);
  11103. mg_free(masked_data);
  11104. return retval;
  11105. }
  11106. static void
  11107. handle_websocket_request(struct mg_connection *conn,
  11108. const char *path,
  11109. int is_callback_resource,
  11110. struct mg_websocket_subprotocols *subprotocols,
  11111. mg_websocket_connect_handler ws_connect_handler,
  11112. mg_websocket_ready_handler ws_ready_handler,
  11113. mg_websocket_data_handler ws_data_handler,
  11114. mg_websocket_close_handler ws_close_handler,
  11115. void *cbData)
  11116. {
  11117. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11118. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11119. ptrdiff_t lua_websock = 0;
  11120. #if !defined(USE_LUA)
  11121. (void)path;
  11122. #endif
  11123. /* Step 1: Check websocket protocol version. */
  11124. /* Step 1.1: Check Sec-WebSocket-Key. */
  11125. if (!websock_key) {
  11126. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11127. * requires a Sec-WebSocket-Key header.
  11128. */
  11129. /* It could be the hixie draft version
  11130. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11131. */
  11132. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11133. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11134. char key3[8];
  11135. if ((key1 != NULL) && (key2 != NULL)) {
  11136. /* This version uses 8 byte body data in a GET request */
  11137. conn->content_len = 8;
  11138. if (8 == mg_read(conn, key3, 8)) {
  11139. /* This is the hixie version */
  11140. mg_send_http_error(conn,
  11141. 426,
  11142. "%s",
  11143. "Protocol upgrade to RFC 6455 required");
  11144. return;
  11145. }
  11146. }
  11147. /* This is an unknown version */
  11148. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11149. return;
  11150. }
  11151. /* Step 1.2: Check websocket protocol version. */
  11152. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11153. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11154. /* Reject wrong versions */
  11155. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11156. return;
  11157. }
  11158. /* Step 1.3: Could check for "Host", but we do not really nead this
  11159. * value for anything, so just ignore it. */
  11160. /* Step 2: If a callback is responsible, call it. */
  11161. if (is_callback_resource) {
  11162. /* Step 2.1 check and select subprotocol */
  11163. const char *protocols[64]; // max 64 headers
  11164. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11165. "Sec-WebSocket-Protocol",
  11166. protocols,
  11167. 64);
  11168. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11169. int cnt = 0;
  11170. int idx;
  11171. unsigned long len;
  11172. const char *sep, *curSubProtocol,
  11173. *acceptedWebSocketSubprotocol = NULL;
  11174. /* look for matching subprotocol */
  11175. do {
  11176. const char *protocol = protocols[cnt];
  11177. do {
  11178. sep = strchr(protocol, ',');
  11179. curSubProtocol = protocol;
  11180. len = sep ? (unsigned long)(sep - protocol)
  11181. : (unsigned long)strlen(protocol);
  11182. while (sep && isspace((unsigned char)*++sep))
  11183. ; // ignore leading whitespaces
  11184. protocol = sep;
  11185. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11186. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11187. && (strncmp(curSubProtocol,
  11188. subprotocols->subprotocols[idx],
  11189. len)
  11190. == 0)) {
  11191. acceptedWebSocketSubprotocol =
  11192. subprotocols->subprotocols[idx];
  11193. break;
  11194. }
  11195. }
  11196. } while (sep && !acceptedWebSocketSubprotocol);
  11197. } while (++cnt < nbSubprotocolHeader
  11198. && !acceptedWebSocketSubprotocol);
  11199. conn->request_info.acceptedWebSocketSubprotocol =
  11200. acceptedWebSocketSubprotocol;
  11201. } else if (nbSubprotocolHeader > 0) {
  11202. /* keep legacy behavior */
  11203. const char *protocol = protocols[0];
  11204. /* The protocol is a comma separated list of names. */
  11205. /* The server must only return one value from this list. */
  11206. /* First check if it is a list or just a single value. */
  11207. const char *sep = strrchr(protocol, ',');
  11208. if (sep == NULL) {
  11209. /* Just a single protocol -> accept it. */
  11210. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11211. } else {
  11212. /* Multiple protocols -> accept the last one. */
  11213. /* This is just a quick fix if the client offers multiple
  11214. * protocols. The handler should have a list of accepted
  11215. * protocols on his own
  11216. * and use it to select one protocol among those the client
  11217. * has
  11218. * offered.
  11219. */
  11220. while (isspace((unsigned char)*++sep)) {
  11221. ; /* ignore leading whitespaces */
  11222. }
  11223. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11224. }
  11225. }
  11226. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11227. websocket_deflate_negotiate(conn);
  11228. #endif
  11229. if ((ws_connect_handler != NULL)
  11230. && (ws_connect_handler(conn, cbData) != 0)) {
  11231. /* C callback has returned non-zero, do not proceed with
  11232. * handshake.
  11233. */
  11234. /* Note that C callbacks are no longer called when Lua is
  11235. * responsible, so C can no longer filter callbacks for Lua. */
  11236. return;
  11237. }
  11238. }
  11239. #if defined(USE_LUA)
  11240. /* Step 3: No callback. Check if Lua is responsible. */
  11241. else {
  11242. /* Step 3.1: Check if Lua is responsible. */
  11243. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11244. lua_websock = match_prefix_strlen(
  11245. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11246. }
  11247. if (lua_websock) {
  11248. /* Step 3.2: Lua is responsible: call it. */
  11249. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11250. if (!conn->lua_websocket_state) {
  11251. /* Lua rejected the new client */
  11252. return;
  11253. }
  11254. }
  11255. }
  11256. #endif
  11257. /* Step 4: Check if there is a responsible websocket handler. */
  11258. if (!is_callback_resource && !lua_websock) {
  11259. /* There is no callback, and Lua is not responsible either. */
  11260. /* Reply with a 404 Not Found. We are still at a standard
  11261. * HTTP request here, before the websocket handshake, so
  11262. * we can still send standard HTTP error replies. */
  11263. mg_send_http_error(conn, 404, "%s", "Not found");
  11264. return;
  11265. }
  11266. /* Step 5: The websocket connection has been accepted */
  11267. if (!send_websocket_handshake(conn, websock_key)) {
  11268. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11269. return;
  11270. }
  11271. /* Step 6: Call the ready handler */
  11272. if (is_callback_resource) {
  11273. if (ws_ready_handler != NULL) {
  11274. ws_ready_handler(conn, cbData);
  11275. }
  11276. #if defined(USE_LUA)
  11277. } else if (lua_websock) {
  11278. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11279. /* the ready handler returned false */
  11280. return;
  11281. }
  11282. #endif
  11283. }
  11284. /* Step 7: Enter the read loop */
  11285. if (is_callback_resource) {
  11286. read_websocket(conn, ws_data_handler, cbData);
  11287. #if defined(USE_LUA)
  11288. } else if (lua_websock) {
  11289. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11290. #endif
  11291. }
  11292. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11293. /* Step 8: Close the deflate & inflate buffers */
  11294. if (conn->websocket_deflate_initialized) {
  11295. deflateEnd(&conn->websocket_deflate_state);
  11296. inflateEnd(&conn->websocket_inflate_state);
  11297. }
  11298. #endif
  11299. /* Step 9: Call the close handler */
  11300. if (ws_close_handler) {
  11301. ws_close_handler(conn, cbData);
  11302. }
  11303. }
  11304. #endif /* !USE_WEBSOCKET */
  11305. /* Is upgrade request:
  11306. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11307. * 1 = upgrade to websocket
  11308. * 2 = upgrade to HTTP/2
  11309. * -1 = upgrade to unknown protocol
  11310. */
  11311. static int
  11312. should_switch_to_protocol(const struct mg_connection *conn)
  11313. {
  11314. const char *upgrade, *connection;
  11315. /* A websocket protocoll has the following HTTP headers:
  11316. *
  11317. * Connection: Upgrade
  11318. * Upgrade: Websocket
  11319. */
  11320. connection = mg_get_header(conn, "Connection");
  11321. if (connection == NULL) {
  11322. return PROTOCOL_TYPE_HTTP1;
  11323. }
  11324. if (!mg_strcasestr(connection, "upgrade")) {
  11325. return PROTOCOL_TYPE_HTTP1;
  11326. }
  11327. upgrade = mg_get_header(conn, "Upgrade");
  11328. if (upgrade == NULL) {
  11329. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11330. return -1;
  11331. }
  11332. /* Upgrade to ... */
  11333. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11334. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11335. * "Sec-WebSocket-Version" are also required.
  11336. * Don't check them here, since even an unsupported websocket protocol
  11337. * request still IS a websocket request (in contrast to a standard HTTP
  11338. * request). It will fail later in handle_websocket_request.
  11339. */
  11340. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11341. }
  11342. if (0 != mg_strcasestr(upgrade, "h2")) {
  11343. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11344. }
  11345. /* Upgrade to another protocol */
  11346. return -1;
  11347. }
  11348. static int
  11349. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11350. {
  11351. int n;
  11352. unsigned int a, b, c, d, slash;
  11353. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11354. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11355. // integer value, but function will not report conversion
  11356. // errors; consider using 'strtol' instead
  11357. slash = 32;
  11358. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11359. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11360. // an integer value, but function will not report conversion
  11361. // errors; consider using 'strtol' instead
  11362. n = 0;
  11363. }
  11364. }
  11365. if ((n > 0) && ((size_t)n == vec->len)) {
  11366. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11367. /* IPv4 format */
  11368. if (sa->sa.sa_family == AF_INET) {
  11369. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11370. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11371. | ((uint32_t)c << 8) | (uint32_t)d;
  11372. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11373. return (ip & mask) == net;
  11374. }
  11375. return 0;
  11376. }
  11377. }
  11378. #if defined(USE_IPV6)
  11379. else {
  11380. char ad[50];
  11381. const char *p;
  11382. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11383. slash = 128;
  11384. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11385. n = 0;
  11386. }
  11387. }
  11388. if ((n <= 0) && no_strict) {
  11389. /* no square brackets? */
  11390. p = strchr(vec->ptr, '/');
  11391. if (p && (p < (vec->ptr + vec->len))) {
  11392. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11393. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11394. n += (int)(p - vec->ptr);
  11395. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11396. } else {
  11397. n = 0;
  11398. }
  11399. } else if (vec->len < sizeof(ad)) {
  11400. n = (int)vec->len;
  11401. slash = 128;
  11402. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11403. }
  11404. }
  11405. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11406. p = ad;
  11407. c = 0;
  11408. /* zone indexes are unsupported, at least two colons are needed */
  11409. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11410. if (*(p++) == ':') {
  11411. c++;
  11412. }
  11413. }
  11414. if ((*p == '\0') && (c >= 2)) {
  11415. struct sockaddr_in6 sin6;
  11416. unsigned int i;
  11417. /* for strict validation, an actual IPv6 argument is needed */
  11418. if (sa->sa.sa_family != AF_INET6) {
  11419. return 0;
  11420. }
  11421. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11422. /* IPv6 format */
  11423. for (i = 0; i < 16; i++) {
  11424. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11425. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11426. uint8_t mask = 0;
  11427. if (8 * i + 8 < slash) {
  11428. mask = 0xFFu;
  11429. } else if (8 * i < slash) {
  11430. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11431. }
  11432. if ((ip & mask) != net) {
  11433. return 0;
  11434. }
  11435. }
  11436. return 1;
  11437. }
  11438. }
  11439. }
  11440. }
  11441. #else
  11442. (void)no_strict;
  11443. #endif
  11444. /* malformed */
  11445. return -1;
  11446. }
  11447. static int
  11448. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11449. {
  11450. int throttle = 0;
  11451. struct vec vec, val;
  11452. char mult;
  11453. double v;
  11454. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11455. mult = ',';
  11456. if ((val.ptr == NULL)
  11457. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11458. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11459. // to an integer value, but function will not report
  11460. // conversion errors; consider using 'strtol' instead
  11461. || (v < 0)
  11462. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11463. && (mult != ','))) {
  11464. continue;
  11465. }
  11466. v *= (lowercase(&mult) == 'k')
  11467. ? 1024
  11468. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11469. if (vec.len == 1 && vec.ptr[0] == '*') {
  11470. throttle = (int)v;
  11471. } else {
  11472. int matched = parse_match_net(&vec, rsa, 0);
  11473. if (matched >= 0) {
  11474. /* a valid IP subnet */
  11475. if (matched) {
  11476. throttle = (int)v;
  11477. }
  11478. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11479. throttle = (int)v;
  11480. }
  11481. }
  11482. }
  11483. return throttle;
  11484. }
  11485. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11486. #include "handle_form.inl"
  11487. static int
  11488. get_first_ssl_listener_index(const struct mg_context *ctx)
  11489. {
  11490. unsigned int i;
  11491. int idx = -1;
  11492. if (ctx) {
  11493. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11494. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11495. }
  11496. }
  11497. return idx;
  11498. }
  11499. /* Return host (without port) */
  11500. static void
  11501. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11502. {
  11503. const char *host_header =
  11504. get_header(ri->http_headers, ri->num_headers, "Host");
  11505. host->ptr = NULL;
  11506. host->len = 0;
  11507. if (host_header != NULL) {
  11508. const char *pos;
  11509. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11510. * is found. */
  11511. if (*host_header == '[') {
  11512. pos = strchr(host_header, ']');
  11513. if (!pos) {
  11514. /* Malformed hostname starts with '[', but no ']' found */
  11515. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11516. return;
  11517. }
  11518. /* terminate after ']' */
  11519. host->ptr = host_header;
  11520. host->len = (size_t)(pos + 1 - host_header);
  11521. } else {
  11522. /* Otherwise, a ':' separates hostname and port number */
  11523. pos = strchr(host_header, ':');
  11524. if (pos != NULL) {
  11525. host->len = (size_t)(pos - host_header);
  11526. } else {
  11527. host->len = strlen(host_header);
  11528. }
  11529. host->ptr = host_header;
  11530. }
  11531. }
  11532. }
  11533. static int
  11534. switch_domain_context(struct mg_connection *conn)
  11535. {
  11536. struct vec host;
  11537. get_host_from_request_info(&host, &conn->request_info);
  11538. if (host.ptr) {
  11539. if (conn->ssl) {
  11540. /* This is a HTTPS connection, maybe we have a hostname
  11541. * from SNI (set in ssl_servername_callback). */
  11542. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11543. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11544. /* We are not using the default domain */
  11545. if ((strlen(sslhost) != host.len)
  11546. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11547. /* Mismatch between SNI domain and HTTP domain */
  11548. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11549. sslhost,
  11550. (int)host.len,
  11551. host.ptr);
  11552. return 0;
  11553. }
  11554. }
  11555. } else {
  11556. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11557. while (dom) {
  11558. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  11559. size_t domNameLen = strlen(domName);
  11560. if ((domNameLen == host.len)
  11561. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  11562. /* Found matching domain */
  11563. DEBUG_TRACE("HTTP domain %s found",
  11564. dom->config[AUTHENTICATION_DOMAIN]);
  11565. /* TODO: Check if this is a HTTP or HTTPS domain */
  11566. conn->dom_ctx = dom;
  11567. break;
  11568. }
  11569. mg_lock_context(conn->phys_ctx);
  11570. dom = dom->next;
  11571. mg_unlock_context(conn->phys_ctx);
  11572. }
  11573. }
  11574. DEBUG_TRACE("HTTP%s Host: %.*s",
  11575. conn->ssl ? "S" : "",
  11576. (int)host.len,
  11577. host.ptr);
  11578. } else {
  11579. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11580. return 1;
  11581. }
  11582. return 1;
  11583. }
  11584. static void
  11585. redirect_to_https_port(struct mg_connection *conn, int port)
  11586. {
  11587. char target_url[MG_BUF_LEN];
  11588. int truncated = 0;
  11589. const char *expect_proto =
  11590. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11591. /* Use "308 Permanent Redirect" */
  11592. int redirect_code = 308;
  11593. /* In any case, close the current connection */
  11594. conn->must_close = 1;
  11595. /* Send host, port, uri and (if it exists) ?query_string */
  11596. if (mg_construct_local_link(
  11597. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11598. < 0) {
  11599. truncated = 1;
  11600. } else if (conn->request_info.query_string != NULL) {
  11601. size_t slen1 = strlen(target_url);
  11602. size_t slen2 = strlen(conn->request_info.query_string);
  11603. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11604. target_url[slen1] = '?';
  11605. memcpy(target_url + slen1 + 1,
  11606. conn->request_info.query_string,
  11607. slen2);
  11608. target_url[slen1 + slen2 + 1] = 0;
  11609. } else {
  11610. truncated = 1;
  11611. }
  11612. }
  11613. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11614. * is used as buffer size) */
  11615. if (truncated) {
  11616. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11617. return;
  11618. }
  11619. /* Use redirect helper function */
  11620. mg_send_http_redirect(conn, target_url, redirect_code);
  11621. }
  11622. static void
  11623. mg_set_handler_type(struct mg_context *phys_ctx,
  11624. struct mg_domain_context *dom_ctx,
  11625. const char *uri,
  11626. int handler_type,
  11627. int is_delete_request,
  11628. mg_request_handler handler,
  11629. struct mg_websocket_subprotocols *subprotocols,
  11630. mg_websocket_connect_handler connect_handler,
  11631. mg_websocket_ready_handler ready_handler,
  11632. mg_websocket_data_handler data_handler,
  11633. mg_websocket_close_handler close_handler,
  11634. mg_authorization_handler auth_handler,
  11635. void *cbdata)
  11636. {
  11637. struct mg_handler_info *tmp_rh, **lastref;
  11638. size_t urilen = strlen(uri);
  11639. if (handler_type == WEBSOCKET_HANDLER) {
  11640. DEBUG_ASSERT(handler == NULL);
  11641. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11642. || ready_handler != NULL || data_handler != NULL
  11643. || close_handler != NULL);
  11644. DEBUG_ASSERT(auth_handler == NULL);
  11645. if (handler != NULL) {
  11646. return;
  11647. }
  11648. if (!is_delete_request && (connect_handler == NULL)
  11649. && (ready_handler == NULL) && (data_handler == NULL)
  11650. && (close_handler == NULL)) {
  11651. return;
  11652. }
  11653. if (auth_handler != NULL) {
  11654. return;
  11655. }
  11656. } else if (handler_type == REQUEST_HANDLER) {
  11657. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11658. && data_handler == NULL && close_handler == NULL);
  11659. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11660. DEBUG_ASSERT(auth_handler == NULL);
  11661. if ((connect_handler != NULL) || (ready_handler != NULL)
  11662. || (data_handler != NULL) || (close_handler != NULL)) {
  11663. return;
  11664. }
  11665. if (!is_delete_request && (handler == NULL)) {
  11666. return;
  11667. }
  11668. if (auth_handler != NULL) {
  11669. return;
  11670. }
  11671. } else if (handler_type == AUTH_HANDLER) {
  11672. DEBUG_ASSERT(handler == NULL);
  11673. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11674. && data_handler == NULL && close_handler == NULL);
  11675. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  11676. if (handler != NULL) {
  11677. return;
  11678. }
  11679. if ((connect_handler != NULL) || (ready_handler != NULL)
  11680. || (data_handler != NULL) || (close_handler != NULL)) {
  11681. return;
  11682. }
  11683. if (!is_delete_request && (auth_handler == NULL)) {
  11684. return;
  11685. }
  11686. } else {
  11687. /* Unknown handler type. */
  11688. return;
  11689. }
  11690. if (!phys_ctx || !dom_ctx) {
  11691. /* no context available */
  11692. return;
  11693. }
  11694. mg_lock_context(phys_ctx);
  11695. /* first try to find an existing handler */
  11696. do {
  11697. lastref = &(dom_ctx->handlers);
  11698. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11699. tmp_rh = tmp_rh->next) {
  11700. if (tmp_rh->handler_type == handler_type
  11701. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11702. if (!is_delete_request) {
  11703. /* update existing handler */
  11704. if (handler_type == REQUEST_HANDLER) {
  11705. /* Wait for end of use before updating */
  11706. if (tmp_rh->refcount) {
  11707. mg_unlock_context(phys_ctx);
  11708. mg_sleep(1);
  11709. mg_lock_context(phys_ctx);
  11710. /* tmp_rh might have been freed, search again. */
  11711. break;
  11712. }
  11713. /* Ok, the handler is no more use -> Update it */
  11714. tmp_rh->handler = handler;
  11715. } else if (handler_type == WEBSOCKET_HANDLER) {
  11716. tmp_rh->subprotocols = subprotocols;
  11717. tmp_rh->connect_handler = connect_handler;
  11718. tmp_rh->ready_handler = ready_handler;
  11719. tmp_rh->data_handler = data_handler;
  11720. tmp_rh->close_handler = close_handler;
  11721. } else { /* AUTH_HANDLER */
  11722. tmp_rh->auth_handler = auth_handler;
  11723. }
  11724. tmp_rh->cbdata = cbdata;
  11725. } else {
  11726. /* remove existing handler */
  11727. if (handler_type == REQUEST_HANDLER) {
  11728. /* Wait for end of use before removing */
  11729. if (tmp_rh->refcount) {
  11730. tmp_rh->removing = 1;
  11731. mg_unlock_context(phys_ctx);
  11732. mg_sleep(1);
  11733. mg_lock_context(phys_ctx);
  11734. /* tmp_rh might have been freed, search again. */
  11735. break;
  11736. }
  11737. /* Ok, the handler is no more used */
  11738. }
  11739. *lastref = tmp_rh->next;
  11740. mg_free(tmp_rh->uri);
  11741. mg_free(tmp_rh);
  11742. }
  11743. mg_unlock_context(phys_ctx);
  11744. return;
  11745. }
  11746. lastref = &(tmp_rh->next);
  11747. }
  11748. } while (tmp_rh != NULL);
  11749. if (is_delete_request) {
  11750. /* no handler to set, this was a remove request to a non-existing
  11751. * handler */
  11752. mg_unlock_context(phys_ctx);
  11753. return;
  11754. }
  11755. tmp_rh =
  11756. (struct mg_handler_info *)mg_calloc_ctx(1,
  11757. sizeof(struct mg_handler_info),
  11758. phys_ctx);
  11759. if (tmp_rh == NULL) {
  11760. mg_unlock_context(phys_ctx);
  11761. mg_cry_ctx_internal(phys_ctx,
  11762. "%s",
  11763. "Cannot create new request handler struct, OOM");
  11764. return;
  11765. }
  11766. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11767. if (!tmp_rh->uri) {
  11768. mg_unlock_context(phys_ctx);
  11769. mg_free(tmp_rh);
  11770. mg_cry_ctx_internal(phys_ctx,
  11771. "%s",
  11772. "Cannot create new request handler struct, OOM");
  11773. return;
  11774. }
  11775. tmp_rh->uri_len = urilen;
  11776. if (handler_type == REQUEST_HANDLER) {
  11777. tmp_rh->refcount = 0;
  11778. tmp_rh->removing = 0;
  11779. tmp_rh->handler = handler;
  11780. } else if (handler_type == WEBSOCKET_HANDLER) {
  11781. tmp_rh->subprotocols = subprotocols;
  11782. tmp_rh->connect_handler = connect_handler;
  11783. tmp_rh->ready_handler = ready_handler;
  11784. tmp_rh->data_handler = data_handler;
  11785. tmp_rh->close_handler = close_handler;
  11786. } else { /* AUTH_HANDLER */
  11787. tmp_rh->auth_handler = auth_handler;
  11788. }
  11789. tmp_rh->cbdata = cbdata;
  11790. tmp_rh->handler_type = handler_type;
  11791. tmp_rh->next = NULL;
  11792. *lastref = tmp_rh;
  11793. mg_unlock_context(phys_ctx);
  11794. }
  11795. void
  11796. mg_set_request_handler(struct mg_context *ctx,
  11797. const char *uri,
  11798. mg_request_handler handler,
  11799. void *cbdata)
  11800. {
  11801. mg_set_handler_type(ctx,
  11802. &(ctx->dd),
  11803. uri,
  11804. REQUEST_HANDLER,
  11805. handler == NULL,
  11806. handler,
  11807. NULL,
  11808. NULL,
  11809. NULL,
  11810. NULL,
  11811. NULL,
  11812. NULL,
  11813. cbdata);
  11814. }
  11815. void
  11816. mg_set_websocket_handler(struct mg_context *ctx,
  11817. const char *uri,
  11818. mg_websocket_connect_handler connect_handler,
  11819. mg_websocket_ready_handler ready_handler,
  11820. mg_websocket_data_handler data_handler,
  11821. mg_websocket_close_handler close_handler,
  11822. void *cbdata)
  11823. {
  11824. mg_set_websocket_handler_with_subprotocols(ctx,
  11825. uri,
  11826. NULL,
  11827. connect_handler,
  11828. ready_handler,
  11829. data_handler,
  11830. close_handler,
  11831. cbdata);
  11832. }
  11833. void
  11834. mg_set_websocket_handler_with_subprotocols(
  11835. struct mg_context *ctx,
  11836. const char *uri,
  11837. struct mg_websocket_subprotocols *subprotocols,
  11838. mg_websocket_connect_handler connect_handler,
  11839. mg_websocket_ready_handler ready_handler,
  11840. mg_websocket_data_handler data_handler,
  11841. mg_websocket_close_handler close_handler,
  11842. void *cbdata)
  11843. {
  11844. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11845. && (data_handler == NULL)
  11846. && (close_handler == NULL);
  11847. mg_set_handler_type(ctx,
  11848. &(ctx->dd),
  11849. uri,
  11850. WEBSOCKET_HANDLER,
  11851. is_delete_request,
  11852. NULL,
  11853. subprotocols,
  11854. connect_handler,
  11855. ready_handler,
  11856. data_handler,
  11857. close_handler,
  11858. NULL,
  11859. cbdata);
  11860. }
  11861. void
  11862. mg_set_auth_handler(struct mg_context *ctx,
  11863. const char *uri,
  11864. mg_authorization_handler handler,
  11865. void *cbdata)
  11866. {
  11867. mg_set_handler_type(ctx,
  11868. &(ctx->dd),
  11869. uri,
  11870. AUTH_HANDLER,
  11871. handler == NULL,
  11872. NULL,
  11873. NULL,
  11874. NULL,
  11875. NULL,
  11876. NULL,
  11877. NULL,
  11878. handler,
  11879. cbdata);
  11880. }
  11881. static int
  11882. get_request_handler(struct mg_connection *conn,
  11883. int handler_type,
  11884. mg_request_handler *handler,
  11885. struct mg_websocket_subprotocols **subprotocols,
  11886. mg_websocket_connect_handler *connect_handler,
  11887. mg_websocket_ready_handler *ready_handler,
  11888. mg_websocket_data_handler *data_handler,
  11889. mg_websocket_close_handler *close_handler,
  11890. mg_authorization_handler *auth_handler,
  11891. void **cbdata,
  11892. struct mg_handler_info **handler_info)
  11893. {
  11894. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11895. if (request_info) {
  11896. const char *uri = request_info->local_uri;
  11897. size_t urilen = strlen(uri);
  11898. struct mg_handler_info *tmp_rh;
  11899. int step, matched;
  11900. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11901. return 0;
  11902. }
  11903. mg_lock_context(conn->phys_ctx);
  11904. for (step = 0; step < 3; step++) {
  11905. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11906. tmp_rh = tmp_rh->next) {
  11907. if (tmp_rh->handler_type != handler_type) {
  11908. continue;
  11909. }
  11910. if (step == 0) {
  11911. /* first try for an exact match */
  11912. matched = (tmp_rh->uri_len == urilen)
  11913. && (strcmp(tmp_rh->uri, uri) == 0);
  11914. } else if (step == 1) {
  11915. /* next try for a partial match, we will accept
  11916. uri/something */
  11917. matched =
  11918. (tmp_rh->uri_len < urilen)
  11919. && (uri[tmp_rh->uri_len] == '/')
  11920. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  11921. } else {
  11922. /* finally try for pattern match */
  11923. matched =
  11924. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  11925. }
  11926. if (matched) {
  11927. if (handler_type == WEBSOCKET_HANDLER) {
  11928. *subprotocols = tmp_rh->subprotocols;
  11929. *connect_handler = tmp_rh->connect_handler;
  11930. *ready_handler = tmp_rh->ready_handler;
  11931. *data_handler = tmp_rh->data_handler;
  11932. *close_handler = tmp_rh->close_handler;
  11933. } else if (handler_type == REQUEST_HANDLER) {
  11934. if (tmp_rh->removing) {
  11935. /* Treat as none found */
  11936. step = 2;
  11937. break;
  11938. }
  11939. *handler = tmp_rh->handler;
  11940. /* Acquire handler and give it back */
  11941. tmp_rh->refcount++;
  11942. *handler_info = tmp_rh;
  11943. } else { /* AUTH_HANDLER */
  11944. *auth_handler = tmp_rh->auth_handler;
  11945. }
  11946. *cbdata = tmp_rh->cbdata;
  11947. mg_unlock_context(conn->phys_ctx);
  11948. return 1;
  11949. }
  11950. }
  11951. }
  11952. mg_unlock_context(conn->phys_ctx);
  11953. }
  11954. return 0; /* none found */
  11955. }
  11956. /* Check if the script file is in a path, allowed for script files.
  11957. * This can be used if uploading files is possible not only for the server
  11958. * admin, and the upload mechanism does not check the file extension.
  11959. */
  11960. static int
  11961. is_in_script_path(const struct mg_connection *conn, const char *path)
  11962. {
  11963. /* TODO (Feature): Add config value for allowed script path.
  11964. * Default: All allowed. */
  11965. (void)conn;
  11966. (void)path;
  11967. return 1;
  11968. }
  11969. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  11970. static int
  11971. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  11972. int bits,
  11973. char *data,
  11974. size_t len,
  11975. void *cbdata)
  11976. {
  11977. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11978. if (pcallbacks->websocket_data) {
  11979. return pcallbacks->websocket_data(conn, bits, data, len);
  11980. }
  11981. /* No handler set - assume "OK" */
  11982. return 1;
  11983. }
  11984. static void
  11985. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  11986. void *cbdata)
  11987. {
  11988. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11989. if (pcallbacks->connection_close) {
  11990. pcallbacks->connection_close(conn);
  11991. }
  11992. }
  11993. #endif
  11994. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  11995. */
  11996. static void
  11997. release_handler_ref(struct mg_connection *conn,
  11998. struct mg_handler_info *handler_info)
  11999. {
  12000. if (handler_info != NULL) {
  12001. /* Use context lock for ref counter */
  12002. mg_lock_context(conn->phys_ctx);
  12003. handler_info->refcount--;
  12004. mg_unlock_context(conn->phys_ctx);
  12005. }
  12006. }
  12007. /* This is the heart of the Civetweb's logic.
  12008. * This function is called when the request is read, parsed and validated,
  12009. * and Civetweb must decide what action to take: serve a file, or
  12010. * a directory, or call embedded function, etcetera. */
  12011. static void
  12012. handle_request(struct mg_connection *conn)
  12013. {
  12014. struct mg_request_info *ri = &conn->request_info;
  12015. char path[UTF8_PATH_MAX];
  12016. int uri_len, ssl_index;
  12017. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12018. is_put_or_delete_request = 0, is_callback_resource = 0,
  12019. is_template_text_file = 0;
  12020. int i;
  12021. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12022. mg_request_handler callback_handler = NULL;
  12023. struct mg_handler_info *handler_info = NULL;
  12024. struct mg_websocket_subprotocols *subprotocols;
  12025. mg_websocket_connect_handler ws_connect_handler = NULL;
  12026. mg_websocket_ready_handler ws_ready_handler = NULL;
  12027. mg_websocket_data_handler ws_data_handler = NULL;
  12028. mg_websocket_close_handler ws_close_handler = NULL;
  12029. void *callback_data = NULL;
  12030. mg_authorization_handler auth_handler = NULL;
  12031. void *auth_callback_data = NULL;
  12032. int handler_type;
  12033. time_t curtime = time(NULL);
  12034. char date[64];
  12035. char *tmp;
  12036. path[0] = 0;
  12037. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12038. conn->request_state = 0;
  12039. /* 1. get the request url */
  12040. /* 1.1. split into url and query string */
  12041. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12042. != NULL) {
  12043. *((char *)conn->request_info.query_string++) = '\0';
  12044. }
  12045. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12046. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12047. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12048. if (ssl_index >= 0) {
  12049. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12050. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12051. redirect_to_https_port(conn, port);
  12052. } else {
  12053. /* A http to https forward port has been specified,
  12054. * but no https port to forward to. */
  12055. mg_send_http_error(conn,
  12056. 503,
  12057. "%s",
  12058. "Error: SSL forward not configured properly");
  12059. mg_cry_internal(conn,
  12060. "%s",
  12061. "Can not redirect to SSL, no SSL port available");
  12062. }
  12063. return;
  12064. }
  12065. uri_len = (int)strlen(ri->local_uri);
  12066. /* 1.3. decode url (if config says so) */
  12067. if (should_decode_url(conn)) {
  12068. mg_url_decode(
  12069. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12070. }
  12071. /* URL decode the query-string only if explicity set in the configuration */
  12072. if (conn->request_info.query_string) {
  12073. if (should_decode_query_string(conn)) {
  12074. url_decode_in_place((char *)conn->request_info.query_string);
  12075. }
  12076. }
  12077. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12078. * possible. The fact that we cleaned the URI is stored in that the
  12079. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12080. * ri->local_uri_raw still points to memory allocated in
  12081. * worker_thread_run(). ri->local_uri is private to the request so we
  12082. * don't have to use preallocated memory here. */
  12083. tmp = mg_strdup(ri->local_uri_raw);
  12084. if (!tmp) {
  12085. /* Out of memory. We cannot do anything reasonable here. */
  12086. return;
  12087. }
  12088. remove_dot_segments(tmp);
  12089. ri->local_uri = tmp;
  12090. /* step 1. completed, the url is known now */
  12091. DEBUG_TRACE("URL: %s", ri->local_uri);
  12092. /* 2. if this ip has limited speed, set it for this connection */
  12093. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12094. &conn->client.rsa,
  12095. ri->local_uri);
  12096. /* 3. call a "handle everything" callback, if registered */
  12097. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12098. /* Note that since V1.7 the "begin_request" function is called
  12099. * before an authorization check. If an authorization check is
  12100. * required, use a request_handler instead. */
  12101. i = conn->phys_ctx->callbacks.begin_request(conn);
  12102. if (i > 0) {
  12103. /* callback already processed the request. Store the
  12104. return value as a status code for the access log. */
  12105. conn->status_code = i;
  12106. if (!conn->must_close) {
  12107. discard_unread_request_data(conn);
  12108. }
  12109. return;
  12110. } else if (i == 0) {
  12111. /* civetweb should process the request */
  12112. } else {
  12113. /* unspecified - may change with the next version */
  12114. return;
  12115. }
  12116. }
  12117. /* request not yet handled by a handler or redirect, so the request
  12118. * is processed here */
  12119. /* 4. Check for CORS preflight requests and handle them (if configured).
  12120. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12121. */
  12122. if (!strcmp(ri->request_method, "OPTIONS")) {
  12123. /* Send a response to CORS preflights only if
  12124. * access_control_allow_methods is not NULL and not an empty string.
  12125. * In this case, scripts can still handle CORS. */
  12126. const char *cors_meth_cfg =
  12127. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12128. const char *cors_orig_cfg =
  12129. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12130. const char *cors_origin =
  12131. get_header(ri->http_headers, ri->num_headers, "Origin");
  12132. const char *cors_acrm = get_header(ri->http_headers,
  12133. ri->num_headers,
  12134. "Access-Control-Request-Method");
  12135. /* Todo: check if cors_origin is in cors_orig_cfg.
  12136. * Or, let the client check this. */
  12137. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12138. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12139. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12140. /* This is a valid CORS preflight, and the server is configured
  12141. * to handle it automatically. */
  12142. const char *cors_acrh =
  12143. get_header(ri->http_headers,
  12144. ri->num_headers,
  12145. "Access-Control-Request-Headers");
  12146. gmt_time_string(date, sizeof(date), &curtime);
  12147. mg_printf(conn,
  12148. "HTTP/1.1 200 OK\r\n"
  12149. "Date: %s\r\n"
  12150. "Access-Control-Allow-Origin: %s\r\n"
  12151. "Access-Control-Allow-Methods: %s\r\n"
  12152. "Content-Length: 0\r\n"
  12153. "Connection: %s\r\n",
  12154. date,
  12155. cors_orig_cfg,
  12156. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12157. suggest_connection_header(conn));
  12158. if (cors_acrh != NULL) {
  12159. /* CORS request is asking for additional headers */
  12160. const char *cors_hdr_cfg =
  12161. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12162. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12163. /* Allow only if access_control_allow_headers is
  12164. * not NULL and not an empty string. If this
  12165. * configuration is set to *, allow everything.
  12166. * Otherwise this configuration must be a list
  12167. * of allowed HTTP header names. */
  12168. mg_printf(conn,
  12169. "Access-Control-Allow-Headers: %s\r\n",
  12170. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12171. : cors_hdr_cfg));
  12172. }
  12173. }
  12174. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12175. mg_printf(conn, "\r\n");
  12176. return;
  12177. }
  12178. }
  12179. /* 5. interpret the url to find out how the request must be handled
  12180. */
  12181. /* 5.1. first test, if the request targets the regular http(s)://
  12182. * protocol namespace or the websocket ws(s):// protocol namespace.
  12183. */
  12184. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12185. #if defined(USE_WEBSOCKET)
  12186. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12187. #else
  12188. handler_type = REQUEST_HANDLER;
  12189. #endif /* defined(USE_WEBSOCKET) */
  12190. if (is_websocket_request) {
  12191. HTTP1_only;
  12192. }
  12193. /* 5.2. check if the request will be handled by a callback */
  12194. if (get_request_handler(conn,
  12195. handler_type,
  12196. &callback_handler,
  12197. &subprotocols,
  12198. &ws_connect_handler,
  12199. &ws_ready_handler,
  12200. &ws_data_handler,
  12201. &ws_close_handler,
  12202. NULL,
  12203. &callback_data,
  12204. &handler_info)) {
  12205. /* 5.2.1. A callback will handle this request. All requests
  12206. * handled by a callback have to be considered as requests
  12207. * to a script resource. */
  12208. is_callback_resource = 1;
  12209. is_script_resource = 1;
  12210. is_put_or_delete_request = is_put_or_delete_method(conn);
  12211. } else {
  12212. no_callback_resource:
  12213. /* 5.2.2. No callback is responsible for this request. The URI
  12214. * addresses a file based resource (static content or Lua/cgi
  12215. * scripts in the file system). */
  12216. is_callback_resource = 0;
  12217. interpret_uri(conn,
  12218. path,
  12219. sizeof(path),
  12220. &file.stat,
  12221. &is_found,
  12222. &is_script_resource,
  12223. &is_websocket_request,
  12224. &is_put_or_delete_request,
  12225. &is_template_text_file);
  12226. }
  12227. /* 6. authorization check */
  12228. /* 6.1. a custom authorization handler is installed */
  12229. if (get_request_handler(conn,
  12230. AUTH_HANDLER,
  12231. NULL,
  12232. NULL,
  12233. NULL,
  12234. NULL,
  12235. NULL,
  12236. NULL,
  12237. &auth_handler,
  12238. &auth_callback_data,
  12239. NULL)) {
  12240. if (!auth_handler(conn, auth_callback_data)) {
  12241. /* Callback handler will not be used anymore. Release it */
  12242. release_handler_ref(conn, handler_info);
  12243. return;
  12244. }
  12245. } else if (is_put_or_delete_request && !is_script_resource
  12246. && !is_callback_resource) {
  12247. HTTP1_only;
  12248. /* 6.2. this request is a PUT/DELETE to a real file */
  12249. /* 6.2.1. thus, the server must have real files */
  12250. #if defined(NO_FILES)
  12251. if (1) {
  12252. #else
  12253. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12254. #endif
  12255. /* This code path will not be called for request handlers */
  12256. DEBUG_ASSERT(handler_info == NULL);
  12257. /* This server does not have any real files, thus the
  12258. * PUT/DELETE methods are not valid. */
  12259. mg_send_http_error(conn,
  12260. 405,
  12261. "%s method not allowed",
  12262. conn->request_info.request_method);
  12263. return;
  12264. }
  12265. #if !defined(NO_FILES)
  12266. /* 6.2.2. Check if put authorization for static files is
  12267. * available.
  12268. */
  12269. if (!is_authorized_for_put(conn)) {
  12270. send_authorization_request(conn, NULL);
  12271. return;
  12272. }
  12273. #endif
  12274. } else {
  12275. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12276. * or it is a PUT or DELETE request to a resource that does not
  12277. * correspond to a file. Check authorization. */
  12278. if (!check_authorization(conn, path)) {
  12279. send_authorization_request(conn, NULL);
  12280. /* Callback handler will not be used anymore. Release it */
  12281. release_handler_ref(conn, handler_info);
  12282. return;
  12283. }
  12284. }
  12285. /* request is authorized or does not need authorization */
  12286. /* 7. check if there are request handlers for this uri */
  12287. if (is_callback_resource) {
  12288. HTTP1_only;
  12289. if (!is_websocket_request) {
  12290. i = callback_handler(conn, callback_data);
  12291. /* Callback handler will not be used anymore. Release it */
  12292. release_handler_ref(conn, handler_info);
  12293. if (i > 0) {
  12294. /* Do nothing, callback has served the request. Store
  12295. * then return value as status code for the log and discard
  12296. * all data from the client not used by the callback. */
  12297. conn->status_code = i;
  12298. if (!conn->must_close) {
  12299. discard_unread_request_data(conn);
  12300. }
  12301. } else {
  12302. /* The handler did NOT handle the request. */
  12303. /* Some proper reactions would be:
  12304. * a) close the connections without sending anything
  12305. * b) send a 404 not found
  12306. * c) try if there is a file matching the URI
  12307. * It would be possible to do a, b or c in the callback
  12308. * implementation, and return 1 - we cannot do anything
  12309. * here, that is not possible in the callback.
  12310. *
  12311. * TODO: What would be the best reaction here?
  12312. * (Note: The reaction may change, if there is a better
  12313. * idea.)
  12314. */
  12315. /* For the moment, use option c: We look for a proper file,
  12316. * but since a file request is not always a script resource,
  12317. * the authorization check might be different. */
  12318. interpret_uri(conn,
  12319. path,
  12320. sizeof(path),
  12321. &file.stat,
  12322. &is_found,
  12323. &is_script_resource,
  12324. &is_websocket_request,
  12325. &is_put_or_delete_request,
  12326. &is_template_text_file);
  12327. callback_handler = NULL;
  12328. /* Here we are at a dead end:
  12329. * According to URI matching, a callback should be
  12330. * responsible for handling the request,
  12331. * we called it, but the callback declared itself
  12332. * not responsible.
  12333. * We use a goto here, to get out of this dead end,
  12334. * and continue with the default handling.
  12335. * A goto here is simpler and better to understand
  12336. * than some curious loop. */
  12337. goto no_callback_resource;
  12338. }
  12339. } else {
  12340. #if defined(USE_WEBSOCKET)
  12341. handle_websocket_request(conn,
  12342. path,
  12343. is_callback_resource,
  12344. subprotocols,
  12345. ws_connect_handler,
  12346. ws_ready_handler,
  12347. ws_data_handler,
  12348. ws_close_handler,
  12349. callback_data);
  12350. #endif
  12351. }
  12352. return;
  12353. }
  12354. /* 8. handle websocket requests */
  12355. #if defined(USE_WEBSOCKET)
  12356. if (is_websocket_request) {
  12357. HTTP1_only;
  12358. if (is_script_resource) {
  12359. if (is_in_script_path(conn, path)) {
  12360. /* Websocket Lua script */
  12361. handle_websocket_request(conn,
  12362. path,
  12363. 0 /* Lua Script */,
  12364. NULL,
  12365. NULL,
  12366. NULL,
  12367. NULL,
  12368. NULL,
  12369. conn->phys_ctx->user_data);
  12370. } else {
  12371. /* Script was in an illegal path */
  12372. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12373. }
  12374. } else {
  12375. mg_send_http_error(conn, 404, "%s", "Not found");
  12376. }
  12377. return;
  12378. } else
  12379. #endif
  12380. #if defined(NO_FILES)
  12381. /* 9a. In case the server uses only callbacks, this uri is
  12382. * unknown.
  12383. * Then, all request handling ends here. */
  12384. mg_send_http_error(conn, 404, "%s", "Not Found");
  12385. #else
  12386. /* 9b. This request is either for a static file or resource handled
  12387. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12388. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12389. mg_send_http_error(conn, 404, "%s", "Not Found");
  12390. return;
  12391. }
  12392. /* 10. Request is handled by a script */
  12393. if (is_script_resource) {
  12394. HTTP1_only;
  12395. handle_file_based_request(conn, path, &file);
  12396. return;
  12397. }
  12398. /* 11. Handle put/delete/mkcol requests */
  12399. if (is_put_or_delete_request) {
  12400. HTTP1_only;
  12401. /* 11.1. PUT method */
  12402. if (!strcmp(ri->request_method, "PUT")) {
  12403. put_file(conn, path);
  12404. return;
  12405. }
  12406. /* 11.2. DELETE method */
  12407. if (!strcmp(ri->request_method, "DELETE")) {
  12408. delete_file(conn, path);
  12409. return;
  12410. }
  12411. /* 11.3. MKCOL method */
  12412. if (!strcmp(ri->request_method, "MKCOL")) {
  12413. mkcol(conn, path);
  12414. return;
  12415. }
  12416. /* 11.4. PATCH method
  12417. * This method is not supported for static resources,
  12418. * only for scripts (Lua, CGI) and callbacks. */
  12419. mg_send_http_error(conn,
  12420. 405,
  12421. "%s method not allowed",
  12422. conn->request_info.request_method);
  12423. return;
  12424. }
  12425. /* 11. File does not exist, or it was configured that it should be
  12426. * hidden */
  12427. if (!is_found || (must_hide_file(conn, path))) {
  12428. mg_send_http_error(conn, 404, "%s", "Not found");
  12429. return;
  12430. }
  12431. /* 12. Directory uris should end with a slash */
  12432. if (file.stat.is_directory && (uri_len > 0)
  12433. && (ri->local_uri[uri_len - 1] != '/')) {
  12434. size_t len = strlen(ri->request_uri);
  12435. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12436. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12437. if (!new_path) {
  12438. mg_send_http_error(conn, 500, "out or memory");
  12439. } else {
  12440. memcpy(new_path, ri->request_uri, len);
  12441. new_path[len] = '/';
  12442. new_path[len + 1] = 0;
  12443. if (ri->query_string) {
  12444. new_path[len + 1] = '?';
  12445. /* Copy query string including terminating zero */
  12446. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12447. }
  12448. mg_send_http_redirect(conn, new_path, 301);
  12449. mg_free(new_path);
  12450. }
  12451. return;
  12452. }
  12453. /* 13. Handle other methods than GET/HEAD */
  12454. /* 13.1. Handle PROPFIND */
  12455. if (!strcmp(ri->request_method, "PROPFIND")) {
  12456. handle_propfind(conn, path, &file.stat);
  12457. return;
  12458. }
  12459. /* 13.2. Handle OPTIONS for files */
  12460. if (!strcmp(ri->request_method, "OPTIONS")) {
  12461. /* This standard handler is only used for real files.
  12462. * Scripts should support the OPTIONS method themselves, to allow a
  12463. * maximum flexibility.
  12464. * Lua and CGI scripts may fully support CORS this way (including
  12465. * preflights). */
  12466. send_options(conn);
  12467. return;
  12468. }
  12469. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12470. if ((0 != strcmp(ri->request_method, "GET"))
  12471. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12472. mg_send_http_error(conn,
  12473. 405,
  12474. "%s method not allowed",
  12475. conn->request_info.request_method);
  12476. return;
  12477. }
  12478. /* 14. directories */
  12479. if (file.stat.is_directory) {
  12480. /* Substitute files have already been handled above. */
  12481. /* Here we can either generate and send a directory listing,
  12482. * or send an "access denied" error. */
  12483. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12484. "yes")) {
  12485. handle_directory_request(conn, path);
  12486. } else {
  12487. mg_send_http_error(conn,
  12488. 403,
  12489. "%s",
  12490. "Error: Directory listing denied");
  12491. }
  12492. return;
  12493. }
  12494. /* 15. Files with search/replace patterns: LSP and SSI */
  12495. if (is_template_text_file) {
  12496. HTTP1_only;
  12497. handle_file_based_request(conn, path, &file);
  12498. return;
  12499. }
  12500. /* 16. Static file - maybe cached */
  12501. #if !defined(NO_CACHING)
  12502. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12503. /* Send 304 "Not Modified" - this must not send any body data */
  12504. handle_not_modified_static_file_request(conn, &file);
  12505. return;
  12506. }
  12507. #endif /* !NO_CACHING */
  12508. /* 17. Static file - not cached */
  12509. handle_static_file_request(conn, path, &file, NULL, NULL);
  12510. #endif /* !defined(NO_FILES) */
  12511. }
  12512. #if !defined(NO_FILESYSTEMS)
  12513. static void
  12514. handle_file_based_request(struct mg_connection *conn,
  12515. const char *path,
  12516. struct mg_file *file)
  12517. {
  12518. #if !defined(NO_CGI)
  12519. unsigned char cgi_config_idx, inc, max;
  12520. #endif
  12521. if (!conn || !conn->dom_ctx) {
  12522. return;
  12523. }
  12524. #if defined(USE_LUA)
  12525. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12526. path)
  12527. > 0) {
  12528. if (is_in_script_path(conn, path)) {
  12529. /* Lua server page: an SSI like page containing mostly plain
  12530. * html code plus some tags with server generated contents. */
  12531. handle_lsp_request(conn, path, file, NULL);
  12532. } else {
  12533. /* Script was in an illegal path */
  12534. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12535. }
  12536. return;
  12537. }
  12538. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  12539. > 0) {
  12540. if (is_in_script_path(conn, path)) {
  12541. /* Lua in-server module script: a CGI like script used to
  12542. * generate the entire reply. */
  12543. mg_exec_lua_script(conn, path, NULL);
  12544. } else {
  12545. /* Script was in an illegal path */
  12546. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12547. }
  12548. return;
  12549. }
  12550. #endif
  12551. #if defined(USE_DUKTAPE)
  12552. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12553. path)
  12554. > 0) {
  12555. if (is_in_script_path(conn, path)) {
  12556. /* Call duktape to generate the page */
  12557. mg_exec_duktape_script(conn, path);
  12558. } else {
  12559. /* Script was in an illegal path */
  12560. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12561. }
  12562. return;
  12563. }
  12564. #endif
  12565. #if !defined(NO_CGI)
  12566. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  12567. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  12568. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  12569. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  12570. if (match_prefix_strlen(
  12571. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  12572. path)
  12573. > 0) {
  12574. if (is_in_script_path(conn, path)) {
  12575. /* CGI scripts may support all HTTP methods */
  12576. handle_cgi_request(conn, path, 0);
  12577. } else {
  12578. /* Script was in an illegal path */
  12579. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12580. }
  12581. return;
  12582. }
  12583. }
  12584. }
  12585. #endif /* !NO_CGI */
  12586. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  12587. if (is_in_script_path(conn, path)) {
  12588. handle_ssi_file_request(conn, path, file);
  12589. } else {
  12590. /* Script was in an illegal path */
  12591. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12592. }
  12593. return;
  12594. }
  12595. #if !defined(NO_CACHING)
  12596. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  12597. /* Send 304 "Not Modified" - this must not send any body data */
  12598. handle_not_modified_static_file_request(conn, file);
  12599. return;
  12600. }
  12601. #endif /* !NO_CACHING */
  12602. handle_static_file_request(conn, path, file, NULL, NULL);
  12603. }
  12604. #endif /* NO_FILESYSTEMS */
  12605. static void
  12606. close_all_listening_sockets(struct mg_context *ctx)
  12607. {
  12608. unsigned int i;
  12609. if (!ctx) {
  12610. return;
  12611. }
  12612. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12613. closesocket(ctx->listening_sockets[i].sock);
  12614. #if defined(USE_X_DOM_SOCKET)
  12615. /* For unix domain sockets, the socket name represents a file that has
  12616. * to be deleted. */
  12617. /* See
  12618. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12619. */
  12620. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12621. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12622. IGNORE_UNUSED_RESULT(
  12623. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12624. }
  12625. #endif
  12626. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12627. }
  12628. mg_free(ctx->listening_sockets);
  12629. ctx->listening_sockets = NULL;
  12630. mg_free(ctx->listening_socket_fds);
  12631. ctx->listening_socket_fds = NULL;
  12632. }
  12633. /* Valid listening port specification is: [ip_address:]port[s]
  12634. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12635. * Examples for IPv6: [::]:80, [::1]:80,
  12636. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12637. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12638. * In order to bind to both, IPv4 and IPv6, you can either add
  12639. * both ports using 8080,[::]:8080, or the short form +8080.
  12640. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12641. * one only accepting IPv4 the other only IPv6. +8080 creates
  12642. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12643. * environment, they might work differently, or might not work
  12644. * at all - it must be tested what options work best in the
  12645. * relevant network environment.
  12646. */
  12647. static int
  12648. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12649. {
  12650. unsigned int a, b, c, d;
  12651. unsigned port;
  12652. unsigned long portUL;
  12653. int ch, len;
  12654. const char *cb;
  12655. char *endptr;
  12656. #if defined(USE_IPV6)
  12657. char buf[100] = {0};
  12658. #endif
  12659. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12660. * Also, all-zeroes in the socket address means binding to all addresses
  12661. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12662. memset(so, 0, sizeof(*so));
  12663. so->lsa.sin.sin_family = AF_INET;
  12664. *ip_version = 0;
  12665. /* Initialize len as invalid. */
  12666. port = 0;
  12667. len = 0;
  12668. /* Test for different ways to format this string */
  12669. if (sscanf(vec->ptr,
  12670. "%u.%u.%u.%u:%u%n",
  12671. &a,
  12672. &b,
  12673. &c,
  12674. &d,
  12675. &port,
  12676. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12677. // to an integer value, but function will not report
  12678. // conversion errors; consider using 'strtol' instead
  12679. == 5) {
  12680. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12681. so->lsa.sin.sin_addr.s_addr =
  12682. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12683. so->lsa.sin.sin_port = htons((uint16_t)port);
  12684. *ip_version = 4;
  12685. #if defined(USE_IPV6)
  12686. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12687. && ((size_t)len <= vec->len)
  12688. && mg_inet_pton(
  12689. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12690. /* IPv6 address, examples: see above */
  12691. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12692. */
  12693. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12694. *ip_version = 6;
  12695. #endif
  12696. } else if ((vec->ptr[0] == '+')
  12697. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  12698. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12699. // string to an integer value, but function will not
  12700. // report conversion errors; consider using 'strtol'
  12701. // instead
  12702. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12703. /* Add 1 to len for the + character we skipped before */
  12704. len++;
  12705. #if defined(USE_IPV6)
  12706. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12707. so->lsa.sin6.sin6_family = AF_INET6;
  12708. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12709. *ip_version = 4 + 6;
  12710. #else
  12711. /* Bind to IPv4 only, since IPv6 is not built in. */
  12712. so->lsa.sin.sin_port = htons((uint16_t)port);
  12713. *ip_version = 4;
  12714. #endif
  12715. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12716. && (vec->ptr != endptr)) {
  12717. len = (int)(endptr - vec->ptr);
  12718. port = (uint16_t)portUL;
  12719. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12720. so->lsa.sin.sin_port = htons((uint16_t)port);
  12721. *ip_version = 4;
  12722. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12723. /* String could be a hostname. This check algotithm
  12724. * will only work for RFC 952 compliant hostnames,
  12725. * starting with a letter, containing only letters,
  12726. * digits and hyphen ('-'). Newer specs may allow
  12727. * more, but this is not guaranteed here, since it
  12728. * may interfere with rules for port option lists. */
  12729. /* According to RFC 1035, hostnames are restricted to 255 characters
  12730. * in total (63 between two dots). */
  12731. char hostname[256];
  12732. size_t hostnlen = (size_t)(cb - vec->ptr);
  12733. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12734. /* This would be invalid in any case */
  12735. *ip_version = 0;
  12736. return 0;
  12737. }
  12738. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12739. if (mg_inet_pton(
  12740. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12741. if (sscanf(cb + 1, "%u%n", &port, &len)
  12742. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12743. // string to an integer value, but function will not
  12744. // report conversion errors; consider using 'strtol'
  12745. // instead
  12746. *ip_version = 4;
  12747. so->lsa.sin.sin_port = htons((uint16_t)port);
  12748. len += (int)(hostnlen + 1);
  12749. } else {
  12750. len = 0;
  12751. }
  12752. #if defined(USE_IPV6)
  12753. } else if (mg_inet_pton(AF_INET6,
  12754. hostname,
  12755. &so->lsa.sin6,
  12756. sizeof(so->lsa.sin6),
  12757. 1)) {
  12758. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12759. *ip_version = 6;
  12760. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12761. len += (int)(hostnlen + 1);
  12762. } else {
  12763. len = 0;
  12764. }
  12765. #endif
  12766. } else {
  12767. len = 0;
  12768. }
  12769. #if defined(USE_X_DOM_SOCKET)
  12770. } else if (vec->ptr[0] == 'x') {
  12771. /* unix (linux) domain socket */
  12772. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  12773. len = vec->len;
  12774. so->lsa.sun.sun_family = AF_UNIX;
  12775. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  12776. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  12777. port = 0;
  12778. *ip_version = 99;
  12779. } else {
  12780. /* String too long */
  12781. len = 0;
  12782. }
  12783. #endif
  12784. } else {
  12785. /* Parsing failure. */
  12786. len = 0;
  12787. }
  12788. /* sscanf and the option splitting code ensure the following condition
  12789. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12790. if ((len > 0) && is_valid_port(port)
  12791. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  12792. /* Next character after the port number */
  12793. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12794. so->is_ssl = (ch == 's');
  12795. so->ssl_redir = (ch == 'r');
  12796. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12797. return 1;
  12798. }
  12799. }
  12800. /* Reset ip_version to 0 if there is an error */
  12801. *ip_version = 0;
  12802. return 0;
  12803. }
  12804. /* Is there any SSL port in use? */
  12805. static int
  12806. is_ssl_port_used(const char *ports)
  12807. {
  12808. if (ports) {
  12809. /* There are several different allowed syntax variants:
  12810. * - "80" for a single port using every network interface
  12811. * - "localhost:80" for a single port using only localhost
  12812. * - "80,localhost:8080" for two ports, one bound to localhost
  12813. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12814. * to IPv4 localhost, one to IPv6 localhost
  12815. * - "+80" use port 80 for IPv4 and IPv6
  12816. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12817. * for both: IPv4 and IPv4
  12818. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12819. * additionally port 8080 bound to localhost connections
  12820. *
  12821. * If we just look for 's' anywhere in the string, "localhost:80"
  12822. * will be detected as SSL (false positive).
  12823. * Looking for 's' after a digit may cause false positives in
  12824. * "my24service:8080".
  12825. * Looking from 's' backward if there are only ':' and numbers
  12826. * before will not work for "24service:8080" (non SSL, port 8080)
  12827. * or "24s" (SSL, port 24).
  12828. *
  12829. * Remark: Initially hostnames were not allowed to start with a
  12830. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12831. * Section 2.1).
  12832. *
  12833. * To get this correct, the entire string must be parsed as a whole,
  12834. * reading it as a list element for element and parsing with an
  12835. * algorithm equivalent to parse_port_string.
  12836. *
  12837. * In fact, we use local interface names here, not arbitrary
  12838. * hostnames, so in most cases the only name will be "localhost".
  12839. *
  12840. * So, for now, we use this simple algorithm, that may still return
  12841. * a false positive in bizarre cases.
  12842. */
  12843. int i;
  12844. int portslen = (int)strlen(ports);
  12845. char prevIsNumber = 0;
  12846. for (i = 0; i < portslen; i++) {
  12847. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12848. return 1;
  12849. }
  12850. if (ports[i] >= '0' && ports[i] <= '9') {
  12851. prevIsNumber = 1;
  12852. } else {
  12853. prevIsNumber = 0;
  12854. }
  12855. }
  12856. }
  12857. return 0;
  12858. }
  12859. static int
  12860. set_ports_option(struct mg_context *phys_ctx)
  12861. {
  12862. const char *list;
  12863. int on = 1;
  12864. #if defined(USE_IPV6)
  12865. int off = 0;
  12866. #endif
  12867. struct vec vec;
  12868. struct socket so, *ptr;
  12869. struct mg_pollfd *pfd;
  12870. union usa usa;
  12871. socklen_t len;
  12872. int ip_version;
  12873. int portsTotal = 0;
  12874. int portsOk = 0;
  12875. const char *opt_txt;
  12876. long opt_listen_backlog;
  12877. if (!phys_ctx) {
  12878. return 0;
  12879. }
  12880. memset(&so, 0, sizeof(so));
  12881. memset(&usa, 0, sizeof(usa));
  12882. len = sizeof(usa);
  12883. list = phys_ctx->dd.config[LISTENING_PORTS];
  12884. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12885. portsTotal++;
  12886. if (!parse_port_string(&vec, &so, &ip_version)) {
  12887. mg_cry_ctx_internal(
  12888. phys_ctx,
  12889. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12890. (int)vec.len,
  12891. vec.ptr,
  12892. portsTotal,
  12893. "[IP_ADDRESS:]PORT[s|r]");
  12894. continue;
  12895. }
  12896. #if !defined(NO_SSL)
  12897. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12898. mg_cry_ctx_internal(phys_ctx,
  12899. "Cannot add SSL socket (entry %i)",
  12900. portsTotal);
  12901. continue;
  12902. }
  12903. #endif
  12904. /* Create socket. */
  12905. /* For a list of protocol numbers (e.g., TCP==6) see:
  12906. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  12907. */
  12908. if ((so.sock =
  12909. socket(so.lsa.sa.sa_family,
  12910. SOCK_STREAM,
  12911. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  12912. == INVALID_SOCKET) {
  12913. mg_cry_ctx_internal(phys_ctx,
  12914. "cannot create socket (entry %i)",
  12915. portsTotal);
  12916. continue;
  12917. }
  12918. #if defined(_WIN32)
  12919. /* Windows SO_REUSEADDR lets many procs binds to a
  12920. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12921. * if someone already has the socket -- DTL */
  12922. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12923. * Windows might need a few seconds before
  12924. * the same port can be used again in the
  12925. * same process, so a short Sleep may be
  12926. * required between mg_stop and mg_start.
  12927. */
  12928. if (setsockopt(so.sock,
  12929. SOL_SOCKET,
  12930. SO_EXCLUSIVEADDRUSE,
  12931. (SOCK_OPT_TYPE)&on,
  12932. sizeof(on))
  12933. != 0) {
  12934. /* Set reuse option, but don't abort on errors. */
  12935. mg_cry_ctx_internal(
  12936. phys_ctx,
  12937. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12938. portsTotal);
  12939. }
  12940. #else
  12941. if (setsockopt(so.sock,
  12942. SOL_SOCKET,
  12943. SO_REUSEADDR,
  12944. (SOCK_OPT_TYPE)&on,
  12945. sizeof(on))
  12946. != 0) {
  12947. /* Set reuse option, but don't abort on errors. */
  12948. mg_cry_ctx_internal(
  12949. phys_ctx,
  12950. "cannot set socket option SO_REUSEADDR (entry %i)",
  12951. portsTotal);
  12952. }
  12953. #endif
  12954. #if defined(USE_X_DOM_SOCKET)
  12955. if (ip_version == 99) {
  12956. /* Unix domain socket */
  12957. } else
  12958. #endif
  12959. if (ip_version > 4) {
  12960. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12961. #if defined(USE_IPV6)
  12962. if (ip_version > 6) {
  12963. if (so.lsa.sa.sa_family == AF_INET6
  12964. && setsockopt(so.sock,
  12965. IPPROTO_IPV6,
  12966. IPV6_V6ONLY,
  12967. (void *)&off,
  12968. sizeof(off))
  12969. != 0) {
  12970. /* Set IPv6 only option, but don't abort on errors. */
  12971. mg_cry_ctx_internal(phys_ctx,
  12972. "cannot set socket option "
  12973. "IPV6_V6ONLY=off (entry %i)",
  12974. portsTotal);
  12975. }
  12976. } else {
  12977. if (so.lsa.sa.sa_family == AF_INET6
  12978. && setsockopt(so.sock,
  12979. IPPROTO_IPV6,
  12980. IPV6_V6ONLY,
  12981. (void *)&on,
  12982. sizeof(on))
  12983. != 0) {
  12984. /* Set IPv6 only option, but don't abort on errors. */
  12985. mg_cry_ctx_internal(phys_ctx,
  12986. "cannot set socket option "
  12987. "IPV6_V6ONLY=on (entry %i)",
  12988. portsTotal);
  12989. }
  12990. }
  12991. #else
  12992. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12993. closesocket(so.sock);
  12994. so.sock = INVALID_SOCKET;
  12995. continue;
  12996. #endif
  12997. }
  12998. if (so.lsa.sa.sa_family == AF_INET) {
  12999. len = sizeof(so.lsa.sin);
  13000. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13001. mg_cry_ctx_internal(phys_ctx,
  13002. "cannot bind to %.*s: %d (%s)",
  13003. (int)vec.len,
  13004. vec.ptr,
  13005. (int)ERRNO,
  13006. strerror(errno));
  13007. closesocket(so.sock);
  13008. so.sock = INVALID_SOCKET;
  13009. continue;
  13010. }
  13011. }
  13012. #if defined(USE_IPV6)
  13013. else if (so.lsa.sa.sa_family == AF_INET6) {
  13014. len = sizeof(so.lsa.sin6);
  13015. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13016. mg_cry_ctx_internal(phys_ctx,
  13017. "cannot bind to IPv6 %.*s: %d (%s)",
  13018. (int)vec.len,
  13019. vec.ptr,
  13020. (int)ERRNO,
  13021. strerror(errno));
  13022. closesocket(so.sock);
  13023. so.sock = INVALID_SOCKET;
  13024. continue;
  13025. }
  13026. }
  13027. #endif
  13028. #if defined(USE_X_DOM_SOCKET)
  13029. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13030. len = sizeof(so.lsa.sun);
  13031. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13032. mg_cry_ctx_internal(phys_ctx,
  13033. "cannot bind to unix socket %s: %d (%s)",
  13034. so.lsa.sun.sun_path,
  13035. (int)ERRNO,
  13036. strerror(errno));
  13037. closesocket(so.sock);
  13038. so.sock = INVALID_SOCKET;
  13039. continue;
  13040. }
  13041. }
  13042. #endif
  13043. else {
  13044. mg_cry_ctx_internal(
  13045. phys_ctx,
  13046. "cannot bind: address family not supported (entry %i)",
  13047. portsTotal);
  13048. closesocket(so.sock);
  13049. so.sock = INVALID_SOCKET;
  13050. continue;
  13051. }
  13052. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13053. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13054. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13055. mg_cry_ctx_internal(phys_ctx,
  13056. "%s value \"%s\" is invalid",
  13057. config_options[LISTEN_BACKLOG_SIZE].name,
  13058. opt_txt);
  13059. closesocket(so.sock);
  13060. so.sock = INVALID_SOCKET;
  13061. continue;
  13062. }
  13063. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13064. mg_cry_ctx_internal(phys_ctx,
  13065. "cannot listen to %.*s: %d (%s)",
  13066. (int)vec.len,
  13067. vec.ptr,
  13068. (int)ERRNO,
  13069. strerror(errno));
  13070. closesocket(so.sock);
  13071. so.sock = INVALID_SOCKET;
  13072. continue;
  13073. }
  13074. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13075. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13076. int err = (int)ERRNO;
  13077. mg_cry_ctx_internal(phys_ctx,
  13078. "call to getsockname failed %.*s: %d (%s)",
  13079. (int)vec.len,
  13080. vec.ptr,
  13081. err,
  13082. strerror(errno));
  13083. closesocket(so.sock);
  13084. so.sock = INVALID_SOCKET;
  13085. continue;
  13086. }
  13087. /* Update lsa port in case of random free ports */
  13088. #if defined(USE_IPV6)
  13089. if (so.lsa.sa.sa_family == AF_INET6) {
  13090. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13091. } else
  13092. #endif
  13093. {
  13094. so.lsa.sin.sin_port = usa.sin.sin_port;
  13095. }
  13096. if ((ptr = (struct socket *)
  13097. mg_realloc_ctx(phys_ctx->listening_sockets,
  13098. (phys_ctx->num_listening_sockets + 1)
  13099. * sizeof(phys_ctx->listening_sockets[0]),
  13100. phys_ctx))
  13101. == NULL) {
  13102. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13103. closesocket(so.sock);
  13104. so.sock = INVALID_SOCKET;
  13105. continue;
  13106. }
  13107. if ((pfd = (struct mg_pollfd *)
  13108. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13109. (phys_ctx->num_listening_sockets + 1)
  13110. * sizeof(phys_ctx->listening_socket_fds[0]),
  13111. phys_ctx))
  13112. == NULL) {
  13113. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13114. closesocket(so.sock);
  13115. so.sock = INVALID_SOCKET;
  13116. mg_free(ptr);
  13117. continue;
  13118. }
  13119. set_close_on_exec(so.sock, NULL, phys_ctx);
  13120. phys_ctx->listening_sockets = ptr;
  13121. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13122. phys_ctx->listening_socket_fds = pfd;
  13123. phys_ctx->num_listening_sockets++;
  13124. portsOk++;
  13125. }
  13126. if (portsOk != portsTotal) {
  13127. close_all_listening_sockets(phys_ctx);
  13128. portsOk = 0;
  13129. }
  13130. return portsOk;
  13131. }
  13132. static const char *
  13133. header_val(const struct mg_connection *conn, const char *header)
  13134. {
  13135. const char *header_value;
  13136. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13137. return "-";
  13138. } else {
  13139. return header_value;
  13140. }
  13141. }
  13142. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13143. #include "external_log_access.inl"
  13144. #elif !defined(NO_FILESYSTEMS)
  13145. static void
  13146. log_access(const struct mg_connection *conn)
  13147. {
  13148. const struct mg_request_info *ri;
  13149. struct mg_file fi;
  13150. char date[64], src_addr[IP_ADDR_STR_LEN];
  13151. struct tm *tm;
  13152. const char *referer;
  13153. const char *user_agent;
  13154. char log_buf[4096];
  13155. if (!conn || !conn->dom_ctx) {
  13156. return;
  13157. }
  13158. /* Set log message to "empty" */
  13159. log_buf[0] = 0;
  13160. #if defined(USE_LUA)
  13161. if (conn->phys_ctx->lua_bg_log_available) {
  13162. int ret;
  13163. struct mg_context *ctx = conn->phys_ctx;
  13164. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13165. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13166. /* call "log()" in Lua */
  13167. lua_getglobal(lstate, "log");
  13168. prepare_lua_request_info_inner(conn, lstate);
  13169. push_lua_response_log_data(conn, lstate);
  13170. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13171. if (ret == 0) {
  13172. int t = lua_type(lstate, -1);
  13173. if (t == LUA_TBOOLEAN) {
  13174. if (lua_toboolean(lstate, -1) == 0) {
  13175. /* log() returned false: do not log */
  13176. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13177. return;
  13178. }
  13179. /* log returned true: continue logging */
  13180. } else if (t == LUA_TSTRING) {
  13181. size_t len;
  13182. const char *txt = lua_tolstring(lstate, -1, &len);
  13183. if ((len == 0) || (*txt == 0)) {
  13184. /* log() returned empty string: do not log */
  13185. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13186. return;
  13187. }
  13188. /* Copy test from Lua into log_buf */
  13189. if (len >= sizeof(log_buf)) {
  13190. len = sizeof(log_buf) - 1;
  13191. }
  13192. memcpy(log_buf, txt, len);
  13193. log_buf[len] = 0;
  13194. }
  13195. } else {
  13196. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13197. }
  13198. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13199. }
  13200. #endif
  13201. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13202. if (mg_fopen(conn,
  13203. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13204. MG_FOPEN_MODE_APPEND,
  13205. &fi)
  13206. == 0) {
  13207. fi.access.fp = NULL;
  13208. }
  13209. } else {
  13210. fi.access.fp = NULL;
  13211. }
  13212. /* Log is written to a file and/or a callback. If both are not set,
  13213. * executing the rest of the function is pointless. */
  13214. if ((fi.access.fp == NULL)
  13215. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13216. return;
  13217. }
  13218. /* If we did not get a log message from Lua, create it here. */
  13219. if (!log_buf[0]) {
  13220. tm = localtime(&conn->conn_birth_time);
  13221. if (tm != NULL) {
  13222. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13223. } else {
  13224. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13225. date[sizeof(date) - 1] = '\0';
  13226. }
  13227. ri = &conn->request_info;
  13228. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13229. referer = header_val(conn, "Referer");
  13230. user_agent = header_val(conn, "User-Agent");
  13231. mg_snprintf(conn,
  13232. NULL, /* Ignore truncation in access log */
  13233. log_buf,
  13234. sizeof(log_buf),
  13235. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13236. " %s %s",
  13237. src_addr,
  13238. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13239. date,
  13240. ri->request_method ? ri->request_method : "-",
  13241. ri->request_uri ? ri->request_uri : "-",
  13242. ri->query_string ? "?" : "",
  13243. ri->query_string ? ri->query_string : "",
  13244. ri->http_version,
  13245. conn->status_code,
  13246. conn->num_bytes_sent,
  13247. referer,
  13248. user_agent);
  13249. }
  13250. /* Here we have a log message in log_buf. Call the callback */
  13251. if (conn->phys_ctx->callbacks.log_access) {
  13252. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13253. /* do not log if callack returns non-zero */
  13254. if (fi.access.fp) {
  13255. mg_fclose(&fi.access);
  13256. }
  13257. return;
  13258. }
  13259. }
  13260. /* Store in file */
  13261. if (fi.access.fp) {
  13262. int ok = 1;
  13263. flockfile(fi.access.fp);
  13264. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13265. ok = 0;
  13266. }
  13267. if (fflush(fi.access.fp) != 0) {
  13268. ok = 0;
  13269. }
  13270. funlockfile(fi.access.fp);
  13271. if (mg_fclose(&fi.access) != 0) {
  13272. ok = 0;
  13273. }
  13274. if (!ok) {
  13275. mg_cry_internal(conn,
  13276. "Error writing log file %s",
  13277. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13278. }
  13279. }
  13280. }
  13281. #else
  13282. #error "Either enable filesystems or provide a custom log_access implementation"
  13283. #endif /* Externally provided function */
  13284. /* Verify given socket address against the ACL.
  13285. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13286. */
  13287. static int
  13288. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13289. {
  13290. int allowed, flag, matched;
  13291. struct vec vec;
  13292. if (phys_ctx) {
  13293. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13294. /* If any ACL is set, deny by default */
  13295. allowed = (list == NULL) ? '+' : '-';
  13296. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13297. flag = vec.ptr[0];
  13298. matched = -1;
  13299. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13300. vec.ptr++;
  13301. vec.len--;
  13302. matched = parse_match_net(&vec, sa, 1);
  13303. }
  13304. if (matched < 0) {
  13305. mg_cry_ctx_internal(phys_ctx,
  13306. "%s: subnet must be [+|-]IP-addr[/x]",
  13307. __func__);
  13308. return -1;
  13309. }
  13310. if (matched) {
  13311. allowed = flag;
  13312. }
  13313. }
  13314. return allowed == '+';
  13315. }
  13316. return -1;
  13317. }
  13318. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13319. static int
  13320. set_uid_option(struct mg_context *phys_ctx)
  13321. {
  13322. int success = 0;
  13323. if (phys_ctx) {
  13324. /* We are currently running as curr_uid. */
  13325. const uid_t curr_uid = getuid();
  13326. /* If set, we want to run as run_as_user. */
  13327. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13328. const struct passwd *to_pw = NULL;
  13329. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13330. /* run_as_user does not exist on the system. We can't proceed
  13331. * further. */
  13332. mg_cry_ctx_internal(phys_ctx,
  13333. "%s: unknown user [%s]",
  13334. __func__,
  13335. run_as_user);
  13336. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13337. /* There was either no request to change user, or we're already
  13338. * running as run_as_user. Nothing else to do.
  13339. */
  13340. success = 1;
  13341. } else {
  13342. /* Valid change request. */
  13343. if (setgid(to_pw->pw_gid) == -1) {
  13344. mg_cry_ctx_internal(phys_ctx,
  13345. "%s: setgid(%s): %s",
  13346. __func__,
  13347. run_as_user,
  13348. strerror(errno));
  13349. } else if (setgroups(0, NULL) == -1) {
  13350. mg_cry_ctx_internal(phys_ctx,
  13351. "%s: setgroups(): %s",
  13352. __func__,
  13353. strerror(errno));
  13354. } else if (setuid(to_pw->pw_uid) == -1) {
  13355. mg_cry_ctx_internal(phys_ctx,
  13356. "%s: setuid(%s): %s",
  13357. __func__,
  13358. run_as_user,
  13359. strerror(errno));
  13360. } else {
  13361. success = 1;
  13362. }
  13363. }
  13364. }
  13365. return success;
  13366. }
  13367. #endif /* !_WIN32 */
  13368. static void
  13369. tls_dtor(void *key)
  13370. {
  13371. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13372. /* key == pthread_getspecific(sTlsKey); */
  13373. if (tls) {
  13374. if (tls->is_master == 2) {
  13375. tls->is_master = -3; /* Mark memory as dead */
  13376. mg_free(tls);
  13377. }
  13378. }
  13379. pthread_setspecific(sTlsKey, NULL);
  13380. }
  13381. #if defined(USE_MBEDTLS)
  13382. /* Check if SSL is required.
  13383. * If so, set up ctx->ssl_ctx pointer. */
  13384. static int
  13385. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13386. {
  13387. if (!phys_ctx) {
  13388. return 0;
  13389. }
  13390. if (!dom_ctx) {
  13391. dom_ctx = &(phys_ctx->dd);
  13392. }
  13393. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13394. /* No SSL port is set. No need to setup SSL. */
  13395. return 1;
  13396. }
  13397. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13398. if (dom_ctx->ssl_ctx == NULL) {
  13399. fprintf(stderr, "ssl_ctx malloc failed\n");
  13400. return 0;
  13401. }
  13402. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13403. == 0
  13404. ? 1
  13405. : 0;
  13406. }
  13407. #elif !defined(NO_SSL)
  13408. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13409. struct mg_domain_context *dom_ctx,
  13410. const char *pem,
  13411. const char *chain);
  13412. static const char *ssl_error(void);
  13413. static int
  13414. refresh_trust(struct mg_connection *conn)
  13415. {
  13416. struct stat cert_buf;
  13417. int64_t t = 0;
  13418. const char *pem;
  13419. const char *chain;
  13420. int should_verify_peer;
  13421. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13422. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13423. * refresh_trust still can not work. */
  13424. return 0;
  13425. }
  13426. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13427. if (chain == NULL) {
  13428. /* pem is not NULL here */
  13429. chain = pem;
  13430. }
  13431. if (*chain == 0) {
  13432. chain = NULL;
  13433. }
  13434. if (stat(pem, &cert_buf) != -1) {
  13435. t = (int64_t)cert_buf.st_mtime;
  13436. }
  13437. mg_lock_context(conn->phys_ctx);
  13438. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13439. conn->dom_ctx->ssl_cert_last_mtime = t;
  13440. should_verify_peer = 0;
  13441. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13442. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13443. == 0) {
  13444. should_verify_peer = 1;
  13445. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13446. "optional")
  13447. == 0) {
  13448. should_verify_peer = 1;
  13449. }
  13450. }
  13451. if (should_verify_peer) {
  13452. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13453. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13454. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13455. ca_file,
  13456. ca_path)
  13457. != 1) {
  13458. mg_unlock_context(conn->phys_ctx);
  13459. mg_cry_ctx_internal(
  13460. conn->phys_ctx,
  13461. "SSL_CTX_load_verify_locations error: %s "
  13462. "ssl_verify_peer requires setting "
  13463. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13464. "present in "
  13465. "the .conf file?",
  13466. ssl_error());
  13467. return 0;
  13468. }
  13469. }
  13470. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13471. mg_unlock_context(conn->phys_ctx);
  13472. return 0;
  13473. }
  13474. }
  13475. mg_unlock_context(conn->phys_ctx);
  13476. return 1;
  13477. }
  13478. #if defined(OPENSSL_API_1_1)
  13479. #else
  13480. static pthread_mutex_t *ssl_mutexes;
  13481. #endif /* OPENSSL_API_1_1 */
  13482. static int
  13483. sslize(struct mg_connection *conn,
  13484. int (*func)(SSL *),
  13485. const struct mg_client_options *client_options)
  13486. {
  13487. int ret, err;
  13488. int short_trust;
  13489. unsigned timeout = 1024;
  13490. unsigned i;
  13491. if (!conn) {
  13492. return 0;
  13493. }
  13494. short_trust =
  13495. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13496. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13497. if (short_trust) {
  13498. int trust_ret = refresh_trust(conn);
  13499. if (!trust_ret) {
  13500. return trust_ret;
  13501. }
  13502. }
  13503. mg_lock_context(conn->phys_ctx);
  13504. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13505. mg_unlock_context(conn->phys_ctx);
  13506. if (conn->ssl == NULL) {
  13507. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13508. OPENSSL_REMOVE_THREAD_STATE();
  13509. return 0;
  13510. }
  13511. SSL_set_app_data(conn->ssl, (char *)conn);
  13512. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13513. if (ret != 1) {
  13514. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13515. SSL_free(conn->ssl);
  13516. conn->ssl = NULL;
  13517. OPENSSL_REMOVE_THREAD_STATE();
  13518. return 0;
  13519. }
  13520. if (client_options) {
  13521. if (client_options->host_name) {
  13522. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13523. }
  13524. }
  13525. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13526. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13527. /* NOTE: The loop below acts as a back-off, so we can end
  13528. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13529. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13530. if (to >= 0) {
  13531. timeout = (unsigned)to;
  13532. }
  13533. }
  13534. /* SSL functions may fail and require to be called again:
  13535. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13536. * Here "func" could be SSL_connect or SSL_accept. */
  13537. for (i = 0; i <= timeout; i += 50) {
  13538. ERR_clear_error();
  13539. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13540. ret = func(conn->ssl);
  13541. if (ret != 1) {
  13542. err = SSL_get_error(conn->ssl, ret);
  13543. if ((err == SSL_ERROR_WANT_CONNECT)
  13544. || (err == SSL_ERROR_WANT_ACCEPT)
  13545. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13546. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13547. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13548. /* Don't wait if the server is going to be stopped. */
  13549. break;
  13550. }
  13551. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13552. /* Simply retry the function call. */
  13553. mg_sleep(50);
  13554. } else {
  13555. /* Need to retry the function call "later".
  13556. * See https://linux.die.net/man/3/ssl_get_error
  13557. * This is typical for non-blocking sockets. */
  13558. struct mg_pollfd pfd;
  13559. int pollres;
  13560. pfd.fd = conn->client.sock;
  13561. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13562. || (err == SSL_ERROR_WANT_WRITE))
  13563. ? POLLOUT
  13564. : POLLIN;
  13565. pollres =
  13566. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13567. if (pollres < 0) {
  13568. /* Break if error occured (-1)
  13569. * or server shutdown (-2) */
  13570. break;
  13571. }
  13572. }
  13573. } else if (err == SSL_ERROR_SYSCALL) {
  13574. /* This is an IO error. Look at errno. */
  13575. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13576. break;
  13577. } else {
  13578. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13579. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13580. break;
  13581. }
  13582. } else {
  13583. /* success */
  13584. break;
  13585. }
  13586. }
  13587. ERR_clear_error();
  13588. if (ret != 1) {
  13589. SSL_free(conn->ssl);
  13590. conn->ssl = NULL;
  13591. OPENSSL_REMOVE_THREAD_STATE();
  13592. return 0;
  13593. }
  13594. return 1;
  13595. }
  13596. /* Return OpenSSL error message (from CRYPTO lib) */
  13597. static const char *
  13598. ssl_error(void)
  13599. {
  13600. unsigned long err;
  13601. err = ERR_get_error();
  13602. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13603. }
  13604. static int
  13605. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13606. {
  13607. int i;
  13608. const char hexdigit[] = "0123456789abcdef";
  13609. if ((memlen <= 0) || (buflen <= 0)) {
  13610. return 0;
  13611. }
  13612. if (buflen < (3 * memlen)) {
  13613. return 0;
  13614. }
  13615. for (i = 0; i < memlen; i++) {
  13616. if (i > 0) {
  13617. buf[3 * i - 1] = ' ';
  13618. }
  13619. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13620. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13621. }
  13622. buf[3 * memlen - 1] = 0;
  13623. return 1;
  13624. }
  13625. static int
  13626. ssl_get_client_cert_info(const struct mg_connection *conn,
  13627. struct mg_client_cert *client_cert)
  13628. {
  13629. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13630. if (cert) {
  13631. char str_buf[1024];
  13632. unsigned char buf[256];
  13633. char *str_serial = NULL;
  13634. unsigned int ulen;
  13635. int ilen;
  13636. unsigned char *tmp_buf;
  13637. unsigned char *tmp_p;
  13638. /* Handle to algorithm used for fingerprint */
  13639. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13640. /* Get Subject and issuer */
  13641. X509_NAME *subj = X509_get_subject_name(cert);
  13642. X509_NAME *iss = X509_get_issuer_name(cert);
  13643. /* Get serial number */
  13644. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13645. /* Translate serial number to a hex string */
  13646. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13647. if (serial_bn) {
  13648. str_serial = BN_bn2hex(serial_bn);
  13649. BN_free(serial_bn);
  13650. }
  13651. client_cert->serial =
  13652. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13653. /* Translate subject and issuer to a string */
  13654. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13655. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13656. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13657. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13658. /* Calculate SHA1 fingerprint and store as a hex string */
  13659. ulen = 0;
  13660. /* ASN1_digest is deprecated. Do the calculation manually,
  13661. * using EVP_Digest. */
  13662. ilen = i2d_X509(cert, NULL);
  13663. tmp_buf = (ilen > 0)
  13664. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13665. conn->phys_ctx)
  13666. : NULL;
  13667. if (tmp_buf) {
  13668. tmp_p = tmp_buf;
  13669. (void)i2d_X509(cert, &tmp_p);
  13670. if (!EVP_Digest(
  13671. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13672. ulen = 0;
  13673. }
  13674. mg_free(tmp_buf);
  13675. }
  13676. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13677. *str_buf = 0;
  13678. }
  13679. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13680. client_cert->peer_cert = (void *)cert;
  13681. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13682. * see https://linux.die.net/man/3/bn_bn2hex */
  13683. OPENSSL_free(str_serial);
  13684. return 1;
  13685. }
  13686. return 0;
  13687. }
  13688. #if defined(OPENSSL_API_1_1)
  13689. #else
  13690. static void
  13691. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13692. {
  13693. (void)line;
  13694. (void)file;
  13695. if (mode & 1) {
  13696. /* 1 is CRYPTO_LOCK */
  13697. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13698. } else {
  13699. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13700. }
  13701. }
  13702. #endif /* OPENSSL_API_1_1 */
  13703. #if !defined(NO_SSL_DL)
  13704. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13705. static void *
  13706. load_tls_dll(char *ebuf,
  13707. size_t ebuf_len,
  13708. const char *dll_name,
  13709. struct ssl_func *sw,
  13710. int *feature_missing)
  13711. {
  13712. union {
  13713. void *p;
  13714. void (*fp)(void);
  13715. } u;
  13716. void *dll_handle;
  13717. struct ssl_func *fp;
  13718. int ok;
  13719. int truncated = 0;
  13720. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13721. mg_snprintf(NULL,
  13722. NULL, /* No truncation check for ebuf */
  13723. ebuf,
  13724. ebuf_len,
  13725. "%s: cannot load %s",
  13726. __func__,
  13727. dll_name);
  13728. return NULL;
  13729. }
  13730. ok = 1;
  13731. for (fp = sw; fp->name != NULL; fp++) {
  13732. #if defined(_WIN32)
  13733. /* GetProcAddress() returns pointer to function */
  13734. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13735. #else
  13736. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13737. * pointers to function pointers. We need to use a union to make a
  13738. * cast. */
  13739. u.p = dlsym(dll_handle, fp->name);
  13740. #endif /* _WIN32 */
  13741. /* Set pointer (might be NULL) */
  13742. fp->ptr = u.fp;
  13743. if (u.fp == NULL) {
  13744. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13745. if (feature_missing) {
  13746. feature_missing[fp->required]++;
  13747. }
  13748. if (fp->required == TLS_Mandatory) {
  13749. /* Mandatory function is missing */
  13750. if (ok) {
  13751. /* This is the first missing function.
  13752. * Create a new error message. */
  13753. mg_snprintf(NULL,
  13754. &truncated,
  13755. ebuf,
  13756. ebuf_len,
  13757. "%s: %s: cannot find %s",
  13758. __func__,
  13759. dll_name,
  13760. fp->name);
  13761. ok = 0;
  13762. } else {
  13763. /* This is yet anothermissing function.
  13764. * Append existing error message. */
  13765. size_t cur_len = strlen(ebuf);
  13766. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13767. mg_snprintf(NULL,
  13768. &truncated,
  13769. ebuf + cur_len,
  13770. ebuf_len - cur_len - 3,
  13771. ", %s",
  13772. fp->name);
  13773. if (truncated) {
  13774. /* If truncated, add "..." */
  13775. strcat(ebuf, "...");
  13776. }
  13777. }
  13778. }
  13779. }
  13780. }
  13781. }
  13782. if (!ok) {
  13783. (void)dlclose(dll_handle);
  13784. return NULL;
  13785. }
  13786. return dll_handle;
  13787. }
  13788. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13789. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13790. #endif /* NO_SSL_DL */
  13791. #if defined(SSL_ALREADY_INITIALIZED)
  13792. static volatile ptrdiff_t cryptolib_users =
  13793. 1; /* Reference counter for crypto library. */
  13794. #else
  13795. static volatile ptrdiff_t cryptolib_users =
  13796. 0; /* Reference counter for crypto library. */
  13797. #endif
  13798. static int
  13799. initialize_openssl(char *ebuf, size_t ebuf_len)
  13800. {
  13801. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13802. int i, num_locks;
  13803. size_t size;
  13804. #endif
  13805. if (ebuf_len > 0) {
  13806. ebuf[0] = 0;
  13807. }
  13808. #if !defined(NO_SSL_DL)
  13809. if (!cryptolib_dll_handle) {
  13810. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13811. cryptolib_dll_handle = load_tls_dll(
  13812. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13813. if (!cryptolib_dll_handle) {
  13814. mg_snprintf(NULL,
  13815. NULL, /* No truncation check for ebuf */
  13816. ebuf,
  13817. ebuf_len,
  13818. "%s: error loading library %s",
  13819. __func__,
  13820. CRYPTO_LIB);
  13821. DEBUG_TRACE("%s", ebuf);
  13822. return 0;
  13823. }
  13824. }
  13825. #endif /* NO_SSL_DL */
  13826. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13827. return 1;
  13828. }
  13829. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13830. /* Initialize locking callbacks, needed for thread safety.
  13831. * http://www.openssl.org/support/faq.html#PROG1
  13832. */
  13833. num_locks = CRYPTO_num_locks();
  13834. if (num_locks < 0) {
  13835. num_locks = 0;
  13836. }
  13837. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13838. /* allocate mutex array, if required */
  13839. if (num_locks == 0) {
  13840. /* No mutex array required */
  13841. ssl_mutexes = NULL;
  13842. } else {
  13843. /* Mutex array required - allocate it */
  13844. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13845. /* Check OOM */
  13846. if (ssl_mutexes == NULL) {
  13847. mg_snprintf(NULL,
  13848. NULL, /* No truncation check for ebuf */
  13849. ebuf,
  13850. ebuf_len,
  13851. "%s: cannot allocate mutexes: %s",
  13852. __func__,
  13853. ssl_error());
  13854. DEBUG_TRACE("%s", ebuf);
  13855. return 0;
  13856. }
  13857. /* initialize mutex array */
  13858. for (i = 0; i < num_locks; i++) {
  13859. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13860. mg_snprintf(NULL,
  13861. NULL, /* No truncation check for ebuf */
  13862. ebuf,
  13863. ebuf_len,
  13864. "%s: error initializing mutex %i of %i",
  13865. __func__,
  13866. i,
  13867. num_locks);
  13868. DEBUG_TRACE("%s", ebuf);
  13869. mg_free(ssl_mutexes);
  13870. return 0;
  13871. }
  13872. }
  13873. }
  13874. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13875. CRYPTO_set_id_callback(&mg_current_thread_id);
  13876. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  13877. #if !defined(NO_SSL_DL)
  13878. if (!ssllib_dll_handle) {
  13879. ssllib_dll_handle =
  13880. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13881. if (!ssllib_dll_handle) {
  13882. #if !defined(OPENSSL_API_1_1)
  13883. mg_free(ssl_mutexes);
  13884. #endif
  13885. DEBUG_TRACE("%s", ebuf);
  13886. return 0;
  13887. }
  13888. }
  13889. #endif /* NO_SSL_DL */
  13890. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  13891. && !defined(NO_SSL_DL)
  13892. /* Initialize SSL library */
  13893. OPENSSL_init_ssl(0, NULL);
  13894. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13895. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13896. NULL);
  13897. #else
  13898. /* Initialize SSL library */
  13899. SSL_library_init();
  13900. SSL_load_error_strings();
  13901. #endif
  13902. return 1;
  13903. }
  13904. static int
  13905. ssl_use_pem_file(struct mg_context *phys_ctx,
  13906. struct mg_domain_context *dom_ctx,
  13907. const char *pem,
  13908. const char *chain)
  13909. {
  13910. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13911. mg_cry_ctx_internal(phys_ctx,
  13912. "%s: cannot open certificate file %s: %s",
  13913. __func__,
  13914. pem,
  13915. ssl_error());
  13916. return 0;
  13917. }
  13918. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13919. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13920. mg_cry_ctx_internal(phys_ctx,
  13921. "%s: cannot open private key file %s: %s",
  13922. __func__,
  13923. pem,
  13924. ssl_error());
  13925. return 0;
  13926. }
  13927. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13928. mg_cry_ctx_internal(phys_ctx,
  13929. "%s: certificate and private key do not match: %s",
  13930. __func__,
  13931. pem);
  13932. return 0;
  13933. }
  13934. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13935. * chain files that contain private keys and certificates in
  13936. * SSL_CTX_use_certificate_chain_file.
  13937. * The CivetWeb-Server used pem-Files that contained both information.
  13938. * In order to make wolfSSL work, it is split in two files.
  13939. * One file that contains key and certificate used by the server and
  13940. * an optional chain file for the ssl stack.
  13941. */
  13942. if (chain) {
  13943. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13944. mg_cry_ctx_internal(phys_ctx,
  13945. "%s: cannot use certificate chain file %s: %s",
  13946. __func__,
  13947. chain,
  13948. ssl_error());
  13949. return 0;
  13950. }
  13951. }
  13952. return 1;
  13953. }
  13954. #if defined(OPENSSL_API_1_1)
  13955. static unsigned long
  13956. ssl_get_protocol(int version_id)
  13957. {
  13958. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13959. if (version_id > 0)
  13960. ret |= SSL_OP_NO_SSLv2;
  13961. if (version_id > 1)
  13962. ret |= SSL_OP_NO_SSLv3;
  13963. if (version_id > 2)
  13964. ret |= SSL_OP_NO_TLSv1;
  13965. if (version_id > 3)
  13966. ret |= SSL_OP_NO_TLSv1_1;
  13967. if (version_id > 4)
  13968. ret |= SSL_OP_NO_TLSv1_2;
  13969. #if defined(SSL_OP_NO_TLSv1_3)
  13970. if (version_id > 5)
  13971. ret |= SSL_OP_NO_TLSv1_3;
  13972. #endif
  13973. return ret;
  13974. }
  13975. #else
  13976. static long
  13977. ssl_get_protocol(int version_id)
  13978. {
  13979. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13980. if (version_id > 0)
  13981. ret |= SSL_OP_NO_SSLv2;
  13982. if (version_id > 1)
  13983. ret |= SSL_OP_NO_SSLv3;
  13984. if (version_id > 2)
  13985. ret |= SSL_OP_NO_TLSv1;
  13986. if (version_id > 3)
  13987. ret |= SSL_OP_NO_TLSv1_1;
  13988. if (version_id > 4)
  13989. ret |= SSL_OP_NO_TLSv1_2;
  13990. #if defined(SSL_OP_NO_TLSv1_3)
  13991. if (version_id > 5)
  13992. ret |= SSL_OP_NO_TLSv1_3;
  13993. #endif
  13994. return (long)ret;
  13995. }
  13996. #endif /* OPENSSL_API_1_1 */
  13997. /* SSL callback documentation:
  13998. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13999. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14000. * https://linux.die.net/man/3/ssl_set_info_callback */
  14001. /* Note: There is no "const" for the first argument in the documentation
  14002. * examples, however some (maybe most, but not all) headers of OpenSSL
  14003. * versions / OpenSSL compatibility layers have it. Having a different
  14004. * definition will cause a warning in C and an error in C++. Use "const SSL
  14005. * *", while automatical conversion from "SSL *" works for all compilers,
  14006. * but not other way around */
  14007. static void
  14008. ssl_info_callback(const SSL *ssl, int what, int ret)
  14009. {
  14010. (void)ret;
  14011. if (what & SSL_CB_HANDSHAKE_START) {
  14012. SSL_get_app_data(ssl);
  14013. }
  14014. if (what & SSL_CB_HANDSHAKE_DONE) {
  14015. /* TODO: check for openSSL 1.1 */
  14016. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14017. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14018. }
  14019. }
  14020. static int
  14021. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14022. {
  14023. #if defined(GCC_DIAGNOSTIC)
  14024. #pragma GCC diagnostic push
  14025. #pragma GCC diagnostic ignored "-Wcast-align"
  14026. #endif /* defined(GCC_DIAGNOSTIC) */
  14027. /* We used an aligned pointer in SSL_set_app_data */
  14028. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14029. #if defined(GCC_DIAGNOSTIC)
  14030. #pragma GCC diagnostic pop
  14031. #endif /* defined(GCC_DIAGNOSTIC) */
  14032. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14033. (void)ad;
  14034. (void)arg;
  14035. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14036. DEBUG_ASSERT(0);
  14037. return SSL_TLSEXT_ERR_NOACK;
  14038. }
  14039. conn->dom_ctx = &(conn->phys_ctx->dd);
  14040. /* Old clients (Win XP) will not support SNI. Then, there
  14041. * is no server name available in the request - we can
  14042. * only work with the default certificate.
  14043. * Multiple HTTPS hosts on one IP+port are only possible
  14044. * with a certificate containing all alternative names.
  14045. */
  14046. if ((servername == NULL) || (*servername == 0)) {
  14047. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14048. mg_lock_context(conn->phys_ctx);
  14049. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14050. mg_unlock_context(conn->phys_ctx);
  14051. return SSL_TLSEXT_ERR_NOACK;
  14052. }
  14053. DEBUG_TRACE("TLS connection to host %s", servername);
  14054. while (conn->dom_ctx) {
  14055. if (!mg_strcasecmp(servername,
  14056. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14057. /* Found matching domain */
  14058. DEBUG_TRACE("TLS domain %s found",
  14059. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14060. break;
  14061. }
  14062. mg_lock_context(conn->phys_ctx);
  14063. conn->dom_ctx = conn->dom_ctx->next;
  14064. mg_unlock_context(conn->phys_ctx);
  14065. }
  14066. if (conn->dom_ctx == NULL) {
  14067. /* Default domain */
  14068. DEBUG_TRACE("TLS default domain %s used",
  14069. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14070. conn->dom_ctx = &(conn->phys_ctx->dd);
  14071. }
  14072. mg_lock_context(conn->phys_ctx);
  14073. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14074. mg_unlock_context(conn->phys_ctx);
  14075. return SSL_TLSEXT_ERR_OK;
  14076. }
  14077. #if defined(USE_ALPN)
  14078. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14079. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14080. alpn_proto_list + 3 + 8,
  14081. NULL};
  14082. #if defined(USE_HTTP2)
  14083. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14084. alpn_proto_list + 3,
  14085. alpn_proto_list + 3 + 8,
  14086. NULL};
  14087. #endif
  14088. static int
  14089. alpn_select_cb(SSL *ssl,
  14090. const unsigned char **out,
  14091. unsigned char *outlen,
  14092. const unsigned char *in,
  14093. unsigned int inlen,
  14094. void *arg)
  14095. {
  14096. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14097. unsigned int i, j, enable_http2 = 0;
  14098. const char **alpn_proto_order = alpn_proto_order_http1;
  14099. struct mg_workerTLS *tls =
  14100. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14101. (void)ssl;
  14102. if (tls == NULL) {
  14103. /* Need to store protocol in Thread Local Storage */
  14104. /* If there is no Thread Local Storage, don't use ALPN */
  14105. return SSL_TLSEXT_ERR_NOACK;
  14106. }
  14107. #if defined(USE_HTTP2)
  14108. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14109. if (enable_http2) {
  14110. alpn_proto_order = alpn_proto_order_http2;
  14111. }
  14112. #endif
  14113. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14114. /* check all accepted protocols in this order */
  14115. const char *alpn_proto = alpn_proto_order[j];
  14116. /* search input for matching protocol */
  14117. for (i = 0; i < inlen; i++) {
  14118. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14119. *out = in + i + 1;
  14120. *outlen = in[i];
  14121. tls->alpn_proto = alpn_proto;
  14122. return SSL_TLSEXT_ERR_OK;
  14123. }
  14124. }
  14125. }
  14126. /* Nothing found */
  14127. return SSL_TLSEXT_ERR_NOACK;
  14128. }
  14129. static int
  14130. next_protos_advertised_cb(SSL *ssl,
  14131. const unsigned char **data,
  14132. unsigned int *len,
  14133. void *arg)
  14134. {
  14135. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14136. *data = (const unsigned char *)alpn_proto_list;
  14137. *len = (unsigned int)strlen((const char *)data);
  14138. (void)ssl;
  14139. (void)dom_ctx;
  14140. return SSL_TLSEXT_ERR_OK;
  14141. }
  14142. static int
  14143. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14144. {
  14145. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14146. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14147. (const unsigned char *)alpn_proto_list,
  14148. alpn_len);
  14149. if (ret != 0) {
  14150. mg_cry_ctx_internal(phys_ctx,
  14151. "SSL_CTX_set_alpn_protos error: %s",
  14152. ssl_error());
  14153. }
  14154. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14155. alpn_select_cb,
  14156. (void *)dom_ctx);
  14157. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14158. next_protos_advertised_cb,
  14159. (void *)dom_ctx);
  14160. return ret;
  14161. }
  14162. #endif
  14163. /* Setup SSL CTX as required by CivetWeb */
  14164. static int
  14165. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14166. struct mg_domain_context *dom_ctx,
  14167. const char *pem,
  14168. const char *chain)
  14169. {
  14170. int callback_ret;
  14171. int should_verify_peer;
  14172. int peer_certificate_optional;
  14173. const char *ca_path;
  14174. const char *ca_file;
  14175. int use_default_verify_paths;
  14176. int verify_depth;
  14177. struct timespec now_mt;
  14178. md5_byte_t ssl_context_id[16];
  14179. md5_state_t md5state;
  14180. int protocol_ver;
  14181. int ssl_cache_timeout;
  14182. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14183. && !defined(NO_SSL_DL)
  14184. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14185. mg_cry_ctx_internal(phys_ctx,
  14186. "SSL_CTX_new (server) error: %s",
  14187. ssl_error());
  14188. return 0;
  14189. }
  14190. #else
  14191. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14192. mg_cry_ctx_internal(phys_ctx,
  14193. "SSL_CTX_new (server) error: %s",
  14194. ssl_error());
  14195. return 0;
  14196. }
  14197. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14198. #if defined(SSL_OP_NO_TLSv1_3)
  14199. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14200. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14201. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14202. | SSL_OP_NO_TLSv1_3);
  14203. #else
  14204. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14205. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14206. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14207. #endif
  14208. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14209. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14210. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14211. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14212. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14213. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14214. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14215. #if defined(SSL_OP_NO_RENEGOTIATION)
  14216. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14217. #endif
  14218. #if !defined(NO_SSL_DL)
  14219. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14220. #endif /* NO_SSL_DL */
  14221. /* In SSL documentation examples callback defined without const
  14222. * specifier 'void (*)(SSL *, int, int)' See:
  14223. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14224. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14225. * But in the source code const SSL is used:
  14226. * 'void (*)(const SSL *, int, int)' See:
  14227. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14228. * Problem about wrong documentation described, but not resolved:
  14229. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14230. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14231. * But when compiled with modern C++ compiler, correct const should be
  14232. * provided
  14233. */
  14234. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14235. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14236. ssl_servername_callback);
  14237. /* If a callback has been specified, call it. */
  14238. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14239. ? 0
  14240. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14241. phys_ctx->user_data));
  14242. /* If callback returns 0, civetweb sets up the SSL certificate.
  14243. * If it returns 1, civetweb assumes the calback already did this.
  14244. * If it returns -1, initializing ssl fails. */
  14245. if (callback_ret < 0) {
  14246. mg_cry_ctx_internal(phys_ctx,
  14247. "SSL callback returned error: %i",
  14248. callback_ret);
  14249. return 0;
  14250. }
  14251. if (callback_ret > 0) {
  14252. /* Callback did everything. */
  14253. return 1;
  14254. }
  14255. /* If a domain callback has been specified, call it. */
  14256. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14257. ? 0
  14258. : (phys_ctx->callbacks.init_ssl_domain(
  14259. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14260. dom_ctx->ssl_ctx,
  14261. phys_ctx->user_data));
  14262. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14263. * If it returns 1, civetweb assumes the calback already did this.
  14264. * If it returns -1, initializing ssl fails. */
  14265. if (callback_ret < 0) {
  14266. mg_cry_ctx_internal(phys_ctx,
  14267. "Domain SSL callback returned error: %i",
  14268. callback_ret);
  14269. return 0;
  14270. }
  14271. if (callback_ret > 0) {
  14272. /* Domain callback did everything. */
  14273. return 1;
  14274. }
  14275. /* Use some combination of start time, domain and port as a SSL
  14276. * context ID. This should be unique on the current machine. */
  14277. md5_init(&md5state);
  14278. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14279. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14280. md5_append(&md5state,
  14281. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14282. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14283. md5_append(&md5state,
  14284. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14285. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14286. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14287. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14288. md5_finish(&md5state, ssl_context_id);
  14289. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14290. (unsigned char *)ssl_context_id,
  14291. sizeof(ssl_context_id));
  14292. if (pem != NULL) {
  14293. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14294. return 0;
  14295. }
  14296. }
  14297. /* Should we support client certificates? */
  14298. /* Default is "no". */
  14299. should_verify_peer = 0;
  14300. peer_certificate_optional = 0;
  14301. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14302. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14303. /* Yes, they are mandatory */
  14304. should_verify_peer = 1;
  14305. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14306. "optional")
  14307. == 0) {
  14308. /* Yes, they are optional */
  14309. should_verify_peer = 1;
  14310. peer_certificate_optional = 1;
  14311. }
  14312. }
  14313. use_default_verify_paths =
  14314. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14315. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14316. == 0);
  14317. if (should_verify_peer) {
  14318. ca_path = dom_ctx->config[SSL_CA_PATH];
  14319. ca_file = dom_ctx->config[SSL_CA_FILE];
  14320. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14321. != 1) {
  14322. mg_cry_ctx_internal(phys_ctx,
  14323. "SSL_CTX_load_verify_locations error: %s "
  14324. "ssl_verify_peer requires setting "
  14325. "either ssl_ca_path or ssl_ca_file. "
  14326. "Is any of them present in the "
  14327. ".conf file?",
  14328. ssl_error());
  14329. return 0;
  14330. }
  14331. if (peer_certificate_optional) {
  14332. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14333. } else {
  14334. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14335. SSL_VERIFY_PEER
  14336. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14337. NULL);
  14338. }
  14339. if (use_default_verify_paths
  14340. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14341. mg_cry_ctx_internal(phys_ctx,
  14342. "SSL_CTX_set_default_verify_paths error: %s",
  14343. ssl_error());
  14344. return 0;
  14345. }
  14346. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14347. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14348. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14349. }
  14350. }
  14351. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14352. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14353. dom_ctx->config[SSL_CIPHER_LIST])
  14354. != 1) {
  14355. mg_cry_ctx_internal(phys_ctx,
  14356. "SSL_CTX_set_cipher_list error: %s",
  14357. ssl_error());
  14358. }
  14359. }
  14360. /* SSL session caching */
  14361. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14362. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14363. : 0);
  14364. if (ssl_cache_timeout > 0) {
  14365. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14366. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14367. * default */
  14368. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14369. }
  14370. #if defined(USE_ALPN)
  14371. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14372. #if !defined(NO_SSL_DL)
  14373. if (!tls_feature_missing[TLS_ALPN])
  14374. #endif
  14375. {
  14376. init_alpn(phys_ctx, dom_ctx);
  14377. }
  14378. #endif
  14379. return 1;
  14380. }
  14381. /* Check if SSL is required.
  14382. * If so, dynamically load SSL library
  14383. * and set up ctx->ssl_ctx pointer. */
  14384. static int
  14385. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14386. {
  14387. void *ssl_ctx = 0;
  14388. int callback_ret;
  14389. const char *pem;
  14390. const char *chain;
  14391. char ebuf[128];
  14392. if (!phys_ctx) {
  14393. return 0;
  14394. }
  14395. if (!dom_ctx) {
  14396. dom_ctx = &(phys_ctx->dd);
  14397. }
  14398. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14399. /* No SSL port is set. No need to setup SSL. */
  14400. return 1;
  14401. }
  14402. /* Check for external SSL_CTX */
  14403. callback_ret =
  14404. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14405. ? 0
  14406. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14407. phys_ctx->user_data));
  14408. if (callback_ret < 0) {
  14409. /* Callback exists and returns <0: Initializing failed. */
  14410. mg_cry_ctx_internal(phys_ctx,
  14411. "external_ssl_ctx callback returned error: %i",
  14412. callback_ret);
  14413. return 0;
  14414. } else if (callback_ret > 0) {
  14415. /* Callback exists and returns >0: Initializing complete,
  14416. * civetweb should not modify the SSL context. */
  14417. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14418. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14419. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14420. return 0;
  14421. }
  14422. return 1;
  14423. }
  14424. /* If the callback does not exist or return 0, civetweb must initialize
  14425. * the SSL context. Handle "domain" callback next. */
  14426. /* Check for external domain SSL_CTX callback. */
  14427. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14428. ? 0
  14429. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14430. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14431. &ssl_ctx,
  14432. phys_ctx->user_data));
  14433. if (callback_ret < 0) {
  14434. /* Callback < 0: Error. Abort init. */
  14435. mg_cry_ctx_internal(
  14436. phys_ctx,
  14437. "external_ssl_ctx_domain callback returned error: %i",
  14438. callback_ret);
  14439. return 0;
  14440. } else if (callback_ret > 0) {
  14441. /* Callback > 0: Consider init done. */
  14442. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14443. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14444. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14445. return 0;
  14446. }
  14447. return 1;
  14448. }
  14449. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14450. * 0, CivetWeb should continue initializing SSL */
  14451. /* If PEM file is not specified and the init_ssl callbacks
  14452. * are not specified, setup will fail. */
  14453. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14454. && (phys_ctx->callbacks.init_ssl == NULL)
  14455. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14456. /* No certificate and no init_ssl callbacks:
  14457. * Essential data to set up TLS is missing.
  14458. */
  14459. mg_cry_ctx_internal(phys_ctx,
  14460. "Initializing SSL failed: -%s is not set",
  14461. config_options[SSL_CERTIFICATE].name);
  14462. return 0;
  14463. }
  14464. /* If a certificate chain is configured, use it. */
  14465. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14466. if (chain == NULL) {
  14467. /* Default: certificate chain in PEM file */
  14468. chain = pem;
  14469. }
  14470. if ((chain != NULL) && (*chain == 0)) {
  14471. /* If the chain is an empty string, don't use it. */
  14472. chain = NULL;
  14473. }
  14474. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14475. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14476. return 0;
  14477. }
  14478. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14479. }
  14480. static void
  14481. uninitialize_openssl(void)
  14482. {
  14483. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14484. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14485. /* Shutdown according to
  14486. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14487. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14488. */
  14489. CONF_modules_unload(1);
  14490. #else
  14491. int i;
  14492. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14493. /* Shutdown according to
  14494. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14495. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14496. */
  14497. CRYPTO_set_locking_callback(NULL);
  14498. CRYPTO_set_id_callback(NULL);
  14499. ENGINE_cleanup();
  14500. CONF_modules_unload(1);
  14501. ERR_free_strings();
  14502. EVP_cleanup();
  14503. CRYPTO_cleanup_all_ex_data();
  14504. OPENSSL_REMOVE_THREAD_STATE();
  14505. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14506. pthread_mutex_destroy(&ssl_mutexes[i]);
  14507. }
  14508. mg_free(ssl_mutexes);
  14509. ssl_mutexes = NULL;
  14510. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14511. }
  14512. }
  14513. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  14514. #if !defined(NO_FILESYSTEMS)
  14515. static int
  14516. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14517. {
  14518. if (phys_ctx) {
  14519. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14520. const char *path;
  14521. struct mg_connection fc;
  14522. if (!dom_ctx) {
  14523. dom_ctx = &(phys_ctx->dd);
  14524. }
  14525. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14526. if ((path != NULL)
  14527. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14528. mg_cry_ctx_internal(phys_ctx,
  14529. "Cannot open %s: %s",
  14530. path,
  14531. strerror(ERRNO));
  14532. return 0;
  14533. }
  14534. return 1;
  14535. }
  14536. return 0;
  14537. }
  14538. #endif /* NO_FILESYSTEMS */
  14539. static int
  14540. set_acl_option(struct mg_context *phys_ctx)
  14541. {
  14542. union usa sa;
  14543. memset(&sa, 0, sizeof(sa));
  14544. #if defined(USE_IPV6)
  14545. sa.sin6.sin6_family = AF_INET6;
  14546. #else
  14547. sa.sin.sin_family = AF_INET;
  14548. #endif
  14549. return check_acl(phys_ctx, &sa) != -1;
  14550. }
  14551. static void
  14552. reset_per_request_attributes(struct mg_connection *conn)
  14553. {
  14554. if (!conn) {
  14555. return;
  14556. }
  14557. conn->num_bytes_sent = conn->consumed_content = 0;
  14558. conn->path_info = NULL;
  14559. conn->status_code = -1;
  14560. conn->content_len = -1;
  14561. conn->is_chunked = 0;
  14562. conn->must_close = 0;
  14563. conn->request_len = 0;
  14564. conn->request_state = 0;
  14565. conn->throttle = 0;
  14566. conn->accept_gzip = 0;
  14567. conn->response_info.content_length = conn->request_info.content_length = -1;
  14568. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14569. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14570. conn->response_info.status_text = NULL;
  14571. conn->response_info.status_code = 0;
  14572. conn->request_info.remote_user = NULL;
  14573. conn->request_info.request_method = NULL;
  14574. conn->request_info.request_uri = NULL;
  14575. /* Free cleaned local URI (if any) */
  14576. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  14577. mg_free((void *)conn->request_info.local_uri);
  14578. conn->request_info.local_uri = NULL;
  14579. }
  14580. conn->request_info.local_uri = NULL;
  14581. #if defined(USE_SERVER_STATS)
  14582. conn->processing_time = 0;
  14583. #endif
  14584. }
  14585. static int
  14586. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14587. {
  14588. if ((so->lsa.sa.sa_family == AF_INET)
  14589. || (so->lsa.sa.sa_family == AF_INET6)) {
  14590. /* Only for TCP sockets */
  14591. if (setsockopt(so->sock,
  14592. IPPROTO_TCP,
  14593. TCP_NODELAY,
  14594. (SOCK_OPT_TYPE)&nodelay_on,
  14595. sizeof(nodelay_on))
  14596. != 0) {
  14597. /* Error */
  14598. return 1;
  14599. }
  14600. }
  14601. /* OK */
  14602. return 0;
  14603. }
  14604. #if !defined(__ZEPHYR__)
  14605. static void
  14606. close_socket_gracefully(struct mg_connection *conn)
  14607. {
  14608. #if defined(_WIN32)
  14609. char buf[MG_BUF_LEN];
  14610. int n;
  14611. #endif
  14612. struct linger linger;
  14613. int error_code = 0;
  14614. int linger_timeout = -2;
  14615. socklen_t opt_len = sizeof(error_code);
  14616. if (!conn) {
  14617. return;
  14618. }
  14619. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14620. * "Note that enabling a nonzero timeout on a nonblocking socket
  14621. * is not recommended.", so set it to blocking now */
  14622. set_blocking_mode(conn->client.sock);
  14623. /* Send FIN to the client */
  14624. shutdown(conn->client.sock, SHUTDOWN_WR);
  14625. #if defined(_WIN32)
  14626. /* Read and discard pending incoming data. If we do not do that and
  14627. * close
  14628. * the socket, the data in the send buffer may be discarded. This
  14629. * behaviour is seen on Windows, when client keeps sending data
  14630. * when server decides to close the connection; then when client
  14631. * does recv() it gets no data back. */
  14632. do {
  14633. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14634. } while (n > 0);
  14635. #endif
  14636. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14637. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14638. }
  14639. /* Set linger option according to configuration */
  14640. if (linger_timeout >= 0) {
  14641. /* Set linger option to avoid socket hanging out after close. This
  14642. * prevent ephemeral port exhaust problem under high QPS. */
  14643. linger.l_onoff = 1;
  14644. #if defined(_MSC_VER)
  14645. #pragma warning(push)
  14646. #pragma warning(disable : 4244)
  14647. #endif
  14648. #if defined(GCC_DIAGNOSTIC)
  14649. #pragma GCC diagnostic push
  14650. #pragma GCC diagnostic ignored "-Wconversion"
  14651. #endif
  14652. /* Data type of linger structure elements may differ,
  14653. * so we don't know what cast we need here.
  14654. * Disable type conversion warnings. */
  14655. linger.l_linger = (linger_timeout + 999) / 1000;
  14656. #if defined(GCC_DIAGNOSTIC)
  14657. #pragma GCC diagnostic pop
  14658. #endif
  14659. #if defined(_MSC_VER)
  14660. #pragma warning(pop)
  14661. #endif
  14662. } else {
  14663. linger.l_onoff = 0;
  14664. linger.l_linger = 0;
  14665. }
  14666. if (linger_timeout < -1) {
  14667. /* Default: don't configure any linger */
  14668. } else if (getsockopt(conn->client.sock,
  14669. SOL_SOCKET,
  14670. SO_ERROR,
  14671. #if defined(_WIN32) /* WinSock uses different data type here */
  14672. (char *)&error_code,
  14673. #else
  14674. &error_code,
  14675. #endif
  14676. &opt_len)
  14677. != 0) {
  14678. /* Cannot determine if socket is already closed. This should
  14679. * not occur and never did in a test. Log an error message
  14680. * and continue. */
  14681. mg_cry_internal(conn,
  14682. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14683. __func__,
  14684. strerror(ERRNO));
  14685. #if defined(_WIN32)
  14686. } else if (error_code == WSAECONNRESET) {
  14687. #else
  14688. } else if (error_code == ECONNRESET) {
  14689. #endif
  14690. /* Socket already closed by client/peer, close socket without linger
  14691. */
  14692. } else {
  14693. /* Set linger timeout */
  14694. if (setsockopt(conn->client.sock,
  14695. SOL_SOCKET,
  14696. SO_LINGER,
  14697. (char *)&linger,
  14698. sizeof(linger))
  14699. != 0) {
  14700. mg_cry_internal(
  14701. conn,
  14702. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14703. __func__,
  14704. linger.l_onoff,
  14705. linger.l_linger,
  14706. strerror(ERRNO));
  14707. }
  14708. }
  14709. /* Now we know that our FIN is ACK-ed, safe to close */
  14710. closesocket(conn->client.sock);
  14711. conn->client.sock = INVALID_SOCKET;
  14712. }
  14713. #endif
  14714. static void
  14715. close_connection(struct mg_connection *conn)
  14716. {
  14717. #if defined(USE_SERVER_STATS)
  14718. conn->conn_state = 6; /* to close */
  14719. #endif
  14720. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14721. if (conn->lua_websocket_state) {
  14722. lua_websocket_close(conn, conn->lua_websocket_state);
  14723. conn->lua_websocket_state = NULL;
  14724. }
  14725. #endif
  14726. mg_lock_connection(conn);
  14727. /* Set close flag, so keep-alive loops will stop */
  14728. conn->must_close = 1;
  14729. /* call the connection_close callback if assigned */
  14730. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14731. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14732. conn->phys_ctx->callbacks.connection_close(conn);
  14733. }
  14734. }
  14735. /* Reset user data, after close callback is called.
  14736. * Do not reuse it. If the user needs a destructor,
  14737. * it must be done in the connection_close callback. */
  14738. mg_set_user_connection_data(conn, NULL);
  14739. #if defined(USE_SERVER_STATS)
  14740. conn->conn_state = 7; /* closing */
  14741. #endif
  14742. #if defined(USE_MBEDTLS)
  14743. if (conn->ssl != NULL) {
  14744. mbed_ssl_close(conn->ssl);
  14745. conn->ssl = NULL;
  14746. }
  14747. #elif !defined(NO_SSL)
  14748. if (conn->ssl != NULL) {
  14749. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14750. */
  14751. SSL_shutdown(conn->ssl);
  14752. SSL_free(conn->ssl);
  14753. OPENSSL_REMOVE_THREAD_STATE();
  14754. conn->ssl = NULL;
  14755. }
  14756. #endif
  14757. if (conn->client.sock != INVALID_SOCKET) {
  14758. #if defined(__ZEPHYR__)
  14759. closesocket(conn->client.sock);
  14760. #else
  14761. close_socket_gracefully(conn);
  14762. #endif
  14763. conn->client.sock = INVALID_SOCKET;
  14764. }
  14765. /* call the connection_closed callback if assigned */
  14766. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  14767. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14768. conn->phys_ctx->callbacks.connection_closed(conn);
  14769. }
  14770. }
  14771. mg_unlock_connection(conn);
  14772. #if defined(USE_SERVER_STATS)
  14773. conn->conn_state = 8; /* closed */
  14774. #endif
  14775. }
  14776. void
  14777. mg_close_connection(struct mg_connection *conn)
  14778. {
  14779. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14780. return;
  14781. }
  14782. #if defined(USE_WEBSOCKET)
  14783. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14784. if (conn->in_websocket_handling) {
  14785. /* Set close flag, so the server thread can exit. */
  14786. conn->must_close = 1;
  14787. return;
  14788. }
  14789. }
  14790. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14791. unsigned int i;
  14792. /* client context: loops must end */
  14793. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14794. conn->must_close = 1;
  14795. /* We need to get the client thread out of the select/recv call
  14796. * here. */
  14797. /* Since we use a sleep quantum of some seconds to check for recv
  14798. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14799. /* join worker thread */
  14800. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14801. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14802. }
  14803. }
  14804. #endif /* defined(USE_WEBSOCKET) */
  14805. close_connection(conn);
  14806. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14807. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14808. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14809. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14810. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14811. }
  14812. #endif
  14813. #if defined(USE_WEBSOCKET)
  14814. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14815. mg_free(conn->phys_ctx->worker_threadids);
  14816. (void)pthread_mutex_destroy(&conn->mutex);
  14817. mg_free(conn);
  14818. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14819. (void)pthread_mutex_destroy(&conn->mutex);
  14820. mg_free(conn);
  14821. }
  14822. #else
  14823. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14824. (void)pthread_mutex_destroy(&conn->mutex);
  14825. mg_free(conn);
  14826. }
  14827. #endif /* defined(USE_WEBSOCKET) */
  14828. }
  14829. static struct mg_connection *
  14830. mg_connect_client_impl(const struct mg_client_options *client_options,
  14831. int use_ssl,
  14832. char *ebuf,
  14833. size_t ebuf_len)
  14834. {
  14835. struct mg_connection *conn = NULL;
  14836. SOCKET sock;
  14837. union usa sa;
  14838. struct sockaddr *psa;
  14839. socklen_t len;
  14840. unsigned max_req_size =
  14841. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14842. /* Size of structures, aligned to 8 bytes */
  14843. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14844. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14845. conn =
  14846. (struct mg_connection *)mg_calloc(1,
  14847. conn_size + ctx_size + max_req_size);
  14848. if (conn == NULL) {
  14849. mg_snprintf(NULL,
  14850. NULL, /* No truncation check for ebuf */
  14851. ebuf,
  14852. ebuf_len,
  14853. "calloc(): %s",
  14854. strerror(ERRNO));
  14855. return NULL;
  14856. }
  14857. #if defined(GCC_DIAGNOSTIC)
  14858. #pragma GCC diagnostic push
  14859. #pragma GCC diagnostic ignored "-Wcast-align"
  14860. #endif /* defined(GCC_DIAGNOSTIC) */
  14861. /* conn_size is aligned to 8 bytes */
  14862. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14863. #if defined(GCC_DIAGNOSTIC)
  14864. #pragma GCC diagnostic pop
  14865. #endif /* defined(GCC_DIAGNOSTIC) */
  14866. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14867. conn->buf_size = (int)max_req_size;
  14868. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14869. conn->dom_ctx = &(conn->phys_ctx->dd);
  14870. if (!connect_socket(conn->phys_ctx,
  14871. client_options->host,
  14872. client_options->port,
  14873. use_ssl,
  14874. ebuf,
  14875. ebuf_len,
  14876. &sock,
  14877. &sa)) {
  14878. /* ebuf is set by connect_socket,
  14879. * free all memory and return NULL; */
  14880. mg_free(conn);
  14881. return NULL;
  14882. }
  14883. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14884. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14885. && !defined(NO_SSL_DL)
  14886. if (use_ssl
  14887. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14888. == NULL) {
  14889. mg_snprintf(NULL,
  14890. NULL, /* No truncation check for ebuf */
  14891. ebuf,
  14892. ebuf_len,
  14893. "SSL_CTX_new error: %s",
  14894. ssl_error());
  14895. closesocket(sock);
  14896. mg_free(conn);
  14897. return NULL;
  14898. }
  14899. #else
  14900. if (use_ssl
  14901. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14902. == NULL) {
  14903. mg_snprintf(NULL,
  14904. NULL, /* No truncation check for ebuf */
  14905. ebuf,
  14906. ebuf_len,
  14907. "SSL_CTX_new error: %s",
  14908. ssl_error());
  14909. closesocket(sock);
  14910. mg_free(conn);
  14911. return NULL;
  14912. }
  14913. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14914. #endif /* NO_SSL */
  14915. #if defined(USE_IPV6)
  14916. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14917. : sizeof(conn->client.rsa.sin6);
  14918. psa = (sa.sa.sa_family == AF_INET)
  14919. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14920. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14921. #else
  14922. len = sizeof(conn->client.rsa.sin);
  14923. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14924. #endif
  14925. conn->client.sock = sock;
  14926. conn->client.lsa = sa;
  14927. if (getsockname(sock, psa, &len) != 0) {
  14928. mg_cry_internal(conn,
  14929. "%s: getsockname() failed: %s",
  14930. __func__,
  14931. strerror(ERRNO));
  14932. }
  14933. conn->client.is_ssl = use_ssl ? 1 : 0;
  14934. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14935. mg_snprintf(NULL,
  14936. NULL, /* No truncation check for ebuf */
  14937. ebuf,
  14938. ebuf_len,
  14939. "Can not create mutex");
  14940. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14941. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14942. #endif
  14943. closesocket(sock);
  14944. mg_free(conn);
  14945. return NULL;
  14946. }
  14947. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14948. if (use_ssl) {
  14949. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14950. * SSL_CTX_set_verify call is needed to switch off server
  14951. * certificate checking, which is off by default in OpenSSL and
  14952. * on in yaSSL. */
  14953. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14954. * SSL_VERIFY_PEER, verify_ssl_server); */
  14955. if (client_options->client_cert) {
  14956. if (!ssl_use_pem_file(conn->phys_ctx,
  14957. conn->dom_ctx,
  14958. client_options->client_cert,
  14959. NULL)) {
  14960. mg_snprintf(NULL,
  14961. NULL, /* No truncation check for ebuf */
  14962. ebuf,
  14963. ebuf_len,
  14964. "Can not use SSL client certificate");
  14965. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14966. closesocket(sock);
  14967. mg_free(conn);
  14968. return NULL;
  14969. }
  14970. }
  14971. if (client_options->server_cert) {
  14972. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14973. client_options->server_cert,
  14974. NULL)
  14975. != 1) {
  14976. mg_cry_internal(conn,
  14977. "SSL_CTX_load_verify_locations error: %s ",
  14978. ssl_error());
  14979. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14980. closesocket(sock);
  14981. mg_free(conn);
  14982. return NULL;
  14983. }
  14984. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14985. } else {
  14986. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14987. }
  14988. if (!sslize(conn, SSL_connect, client_options)) {
  14989. mg_snprintf(NULL,
  14990. NULL, /* No truncation check for ebuf */
  14991. ebuf,
  14992. ebuf_len,
  14993. "SSL connection error");
  14994. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14995. closesocket(sock);
  14996. mg_free(conn);
  14997. return NULL;
  14998. }
  14999. }
  15000. #endif
  15001. return conn;
  15002. }
  15003. CIVETWEB_API struct mg_connection *
  15004. mg_connect_client_secure(const struct mg_client_options *client_options,
  15005. char *error_buffer,
  15006. size_t error_buffer_size)
  15007. {
  15008. return mg_connect_client_impl(client_options,
  15009. 1,
  15010. error_buffer,
  15011. error_buffer_size);
  15012. }
  15013. struct mg_connection *
  15014. mg_connect_client(const char *host,
  15015. int port,
  15016. int use_ssl,
  15017. char *error_buffer,
  15018. size_t error_buffer_size)
  15019. {
  15020. struct mg_client_options opts;
  15021. memset(&opts, 0, sizeof(opts));
  15022. opts.host = host;
  15023. opts.port = port;
  15024. return mg_connect_client_impl(&opts,
  15025. use_ssl,
  15026. error_buffer,
  15027. error_buffer_size);
  15028. }
  15029. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15030. struct mg_connection *
  15031. mg_connect_client2(const char *host,
  15032. const char *protocol,
  15033. int port,
  15034. const char *path,
  15035. struct mg_init_data *init,
  15036. struct mg_error_data *error)
  15037. {
  15038. (void)path;
  15039. (void)init;
  15040. int is_ssl, is_ws;
  15041. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15042. if (error != NULL) {
  15043. error->code = 0;
  15044. if (error->text_buffer_size > 0) {
  15045. *error->text = 0;
  15046. }
  15047. }
  15048. if ((host == NULL) || (protocol == NULL)) {
  15049. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15050. mg_snprintf(NULL,
  15051. NULL, /* No truncation check for error buffers */
  15052. error->text,
  15053. error->text_buffer_size,
  15054. "%s",
  15055. "Invalid parameters");
  15056. }
  15057. return NULL;
  15058. }
  15059. /* check all known protocolls */
  15060. if (!mg_strcasecmp(protocol, "http")) {
  15061. is_ssl = 0;
  15062. is_ws = 0;
  15063. } else if (!mg_strcasecmp(protocol, "https")) {
  15064. is_ssl = 1;
  15065. is_ws = 0;
  15066. #if defined(USE_WEBSOCKET)
  15067. } else if (!mg_strcasecmp(protocol, "ws")) {
  15068. is_ssl = 0;
  15069. is_ws = 1;
  15070. } else if (!mg_strcasecmp(protocol, "wss")) {
  15071. is_ssl = 1;
  15072. is_ws = 1;
  15073. #endif
  15074. } else {
  15075. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15076. mg_snprintf(NULL,
  15077. NULL, /* No truncation check for error buffers */
  15078. error->text,
  15079. error->text_buffer_size,
  15080. "Protocol %s not supported",
  15081. protocol);
  15082. }
  15083. return NULL;
  15084. }
  15085. /* TODO: The current implementation here just calls the old
  15086. * implementations, without using any new options. This is just a first
  15087. * step to test the new interfaces. */
  15088. #if defined(USE_WEBSOCKET)
  15089. if (is_ws) {
  15090. /* TODO: implement all options */
  15091. return mg_connect_websocket_client(
  15092. host,
  15093. port,
  15094. is_ssl,
  15095. ((error != NULL) ? error->text : NULL),
  15096. ((error != NULL) ? error->text_buffer_size : 0),
  15097. (path ? path : ""),
  15098. NULL /* TODO: origin */,
  15099. experimental_websocket_client_data_wrapper,
  15100. experimental_websocket_client_close_wrapper,
  15101. (void *)init->callbacks);
  15102. }
  15103. #else
  15104. (void)is_ws;
  15105. #endif
  15106. /* TODO: all additional options */
  15107. struct mg_client_options opts;
  15108. memset(&opts, 0, sizeof(opts));
  15109. opts.host = host;
  15110. opts.port = port;
  15111. return mg_connect_client_impl(&opts,
  15112. is_ssl,
  15113. ((error != NULL) ? error->text : NULL),
  15114. ((error != NULL) ? error->text_buffer_size
  15115. : 0));
  15116. }
  15117. #endif
  15118. static const struct {
  15119. const char *proto;
  15120. size_t proto_len;
  15121. unsigned default_port;
  15122. } abs_uri_protocols[] = {{"http://", 7, 80},
  15123. {"https://", 8, 443},
  15124. {"ws://", 5, 80},
  15125. {"wss://", 6, 443},
  15126. {NULL, 0, 0}};
  15127. /* Check if the uri is valid.
  15128. * return 0 for invalid uri,
  15129. * return 1 for *,
  15130. * return 2 for relative uri,
  15131. * return 3 for absolute uri without port,
  15132. * return 4 for absolute uri with port */
  15133. static int
  15134. get_uri_type(const char *uri)
  15135. {
  15136. int i;
  15137. const char *hostend, *portbegin;
  15138. char *portend;
  15139. unsigned long port;
  15140. /* According to the HTTP standard
  15141. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15142. * URI can be an asterisk (*) or should start with slash (relative uri),
  15143. * or it should start with the protocol (absolute uri). */
  15144. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15145. /* asterisk */
  15146. return 1;
  15147. }
  15148. /* Valid URIs according to RFC 3986
  15149. * (https://www.ietf.org/rfc/rfc3986.txt)
  15150. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15151. * and unreserved characters A-Z a-z 0-9 and -._~
  15152. * and % encoded symbols.
  15153. */
  15154. for (i = 0; uri[i] != 0; i++) {
  15155. if (uri[i] < 33) {
  15156. /* control characters and spaces are invalid */
  15157. return 0;
  15158. }
  15159. /* Allow everything else here (See #894) */
  15160. }
  15161. /* A relative uri starts with a / character */
  15162. if (uri[0] == '/') {
  15163. /* relative uri */
  15164. return 2;
  15165. }
  15166. /* It could be an absolute uri: */
  15167. /* This function only checks if the uri is valid, not if it is
  15168. * addressing the current server. So civetweb can also be used
  15169. * as a proxy server. */
  15170. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15171. if (mg_strncasecmp(uri,
  15172. abs_uri_protocols[i].proto,
  15173. abs_uri_protocols[i].proto_len)
  15174. == 0) {
  15175. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15176. if (!hostend) {
  15177. return 0;
  15178. }
  15179. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15180. if (!portbegin) {
  15181. return 3;
  15182. }
  15183. port = strtoul(portbegin + 1, &portend, 10);
  15184. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15185. return 0;
  15186. }
  15187. return 4;
  15188. }
  15189. }
  15190. return 0;
  15191. }
  15192. /* Return NULL or the relative uri at the current server */
  15193. static const char *
  15194. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15195. {
  15196. const char *server_domain;
  15197. size_t server_domain_len;
  15198. size_t request_domain_len = 0;
  15199. unsigned long port = 0;
  15200. int i, auth_domain_check_enabled;
  15201. const char *hostbegin = NULL;
  15202. const char *hostend = NULL;
  15203. const char *portbegin;
  15204. char *portend;
  15205. auth_domain_check_enabled =
  15206. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15207. /* DNS is case insensitive, so use case insensitive string compare here
  15208. */
  15209. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15210. if (mg_strncasecmp(uri,
  15211. abs_uri_protocols[i].proto,
  15212. abs_uri_protocols[i].proto_len)
  15213. == 0) {
  15214. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15215. hostend = strchr(hostbegin, '/');
  15216. if (!hostend) {
  15217. return 0;
  15218. }
  15219. portbegin = strchr(hostbegin, ':');
  15220. if ((!portbegin) || (portbegin > hostend)) {
  15221. port = abs_uri_protocols[i].default_port;
  15222. request_domain_len = (size_t)(hostend - hostbegin);
  15223. } else {
  15224. port = strtoul(portbegin + 1, &portend, 10);
  15225. if ((portend != hostend) || (port <= 0)
  15226. || !is_valid_port(port)) {
  15227. return 0;
  15228. }
  15229. request_domain_len = (size_t)(portbegin - hostbegin);
  15230. }
  15231. /* protocol found, port set */
  15232. break;
  15233. }
  15234. }
  15235. if (!port) {
  15236. /* port remains 0 if the protocol is not found */
  15237. return 0;
  15238. }
  15239. /* Check if the request is directed to a different server. */
  15240. /* First check if the port is the same. */
  15241. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15242. /* Request is directed to a different port */
  15243. return 0;
  15244. }
  15245. /* Finally check if the server corresponds to the authentication
  15246. * domain of the server (the server domain).
  15247. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15248. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15249. * but do not allow substrings (like
  15250. * http://notmydomain.com/path/file.ext
  15251. * or http://mydomain.com.fake/path/file.ext).
  15252. */
  15253. if (auth_domain_check_enabled) {
  15254. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15255. server_domain_len = strlen(server_domain);
  15256. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15257. return 0;
  15258. }
  15259. if ((request_domain_len == server_domain_len)
  15260. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15261. /* Request is directed to this server - full name match. */
  15262. } else {
  15263. if (request_domain_len < (server_domain_len + 2)) {
  15264. /* Request is directed to another server: The server name
  15265. * is longer than the request name.
  15266. * Drop this case here to avoid overflows in the
  15267. * following checks. */
  15268. return 0;
  15269. }
  15270. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15271. /* Request is directed to another server: It could be a
  15272. * substring
  15273. * like notmyserver.com */
  15274. return 0;
  15275. }
  15276. if (0
  15277. != memcmp(server_domain,
  15278. hostbegin + request_domain_len - server_domain_len,
  15279. server_domain_len)) {
  15280. /* Request is directed to another server:
  15281. * The server name is different. */
  15282. return 0;
  15283. }
  15284. }
  15285. }
  15286. return hostend;
  15287. }
  15288. static int
  15289. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15290. {
  15291. if (ebuf_len > 0) {
  15292. ebuf[0] = '\0';
  15293. }
  15294. *err = 0;
  15295. reset_per_request_attributes(conn);
  15296. if (!conn) {
  15297. mg_snprintf(conn,
  15298. NULL, /* No truncation check for ebuf */
  15299. ebuf,
  15300. ebuf_len,
  15301. "%s",
  15302. "Internal error");
  15303. *err = 500;
  15304. return 0;
  15305. }
  15306. /* Set the time the request was received. This value should be used for
  15307. * timeouts. */
  15308. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15309. conn->request_len =
  15310. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15311. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15312. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15313. mg_snprintf(conn,
  15314. NULL, /* No truncation check for ebuf */
  15315. ebuf,
  15316. ebuf_len,
  15317. "%s",
  15318. "Invalid message size");
  15319. *err = 500;
  15320. return 0;
  15321. }
  15322. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15323. mg_snprintf(conn,
  15324. NULL, /* No truncation check for ebuf */
  15325. ebuf,
  15326. ebuf_len,
  15327. "%s",
  15328. "Message too large");
  15329. *err = 413;
  15330. return 0;
  15331. }
  15332. if (conn->request_len <= 0) {
  15333. if (conn->data_len > 0) {
  15334. mg_snprintf(conn,
  15335. NULL, /* No truncation check for ebuf */
  15336. ebuf,
  15337. ebuf_len,
  15338. "%s",
  15339. "Malformed message");
  15340. *err = 400;
  15341. } else {
  15342. /* Server did not recv anything -> just close the connection */
  15343. conn->must_close = 1;
  15344. mg_snprintf(conn,
  15345. NULL, /* No truncation check for ebuf */
  15346. ebuf,
  15347. ebuf_len,
  15348. "%s",
  15349. "No data received");
  15350. *err = 0;
  15351. }
  15352. return 0;
  15353. }
  15354. return 1;
  15355. }
  15356. static int
  15357. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15358. {
  15359. const char *cl;
  15360. conn->connection_type =
  15361. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15362. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15363. return 0;
  15364. }
  15365. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15366. <= 0) {
  15367. mg_snprintf(conn,
  15368. NULL, /* No truncation check for ebuf */
  15369. ebuf,
  15370. ebuf_len,
  15371. "%s",
  15372. "Bad request");
  15373. *err = 400;
  15374. return 0;
  15375. }
  15376. /* Message is a valid request */
  15377. if (!switch_domain_context(conn)) {
  15378. mg_snprintf(conn,
  15379. NULL, /* No truncation check for ebuf */
  15380. ebuf,
  15381. ebuf_len,
  15382. "%s",
  15383. "Bad request: Host mismatch");
  15384. *err = 400;
  15385. return 0;
  15386. }
  15387. #if USE_ZLIB
  15388. if (((cl = get_header(conn->request_info.http_headers,
  15389. conn->request_info.num_headers,
  15390. "Accept-Encoding"))
  15391. != NULL)
  15392. && strstr(cl, "gzip")) {
  15393. conn->accept_gzip = 1;
  15394. }
  15395. #endif
  15396. if (((cl = get_header(conn->request_info.http_headers,
  15397. conn->request_info.num_headers,
  15398. "Transfer-Encoding"))
  15399. != NULL)
  15400. && mg_strcasecmp(cl, "identity")) {
  15401. if (mg_strcasecmp(cl, "chunked")) {
  15402. mg_snprintf(conn,
  15403. NULL, /* No truncation check for ebuf */
  15404. ebuf,
  15405. ebuf_len,
  15406. "%s",
  15407. "Bad request");
  15408. *err = 400;
  15409. return 0;
  15410. }
  15411. conn->is_chunked = 1;
  15412. conn->content_len = 0; /* not yet read */
  15413. } else if ((cl = get_header(conn->request_info.http_headers,
  15414. conn->request_info.num_headers,
  15415. "Content-Length"))
  15416. != NULL) {
  15417. /* Request has content length set */
  15418. char *endptr = NULL;
  15419. conn->content_len = strtoll(cl, &endptr, 10);
  15420. if ((endptr == cl) || (conn->content_len < 0)) {
  15421. mg_snprintf(conn,
  15422. NULL, /* No truncation check for ebuf */
  15423. ebuf,
  15424. ebuf_len,
  15425. "%s",
  15426. "Bad request");
  15427. *err = 411;
  15428. return 0;
  15429. }
  15430. /* Publish the content length back to the request info. */
  15431. conn->request_info.content_length = conn->content_len;
  15432. } else {
  15433. /* There is no exception, see RFC7230. */
  15434. conn->content_len = 0;
  15435. }
  15436. return 1;
  15437. }
  15438. /* conn is assumed to be valid in this internal function */
  15439. static int
  15440. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15441. {
  15442. const char *cl;
  15443. conn->connection_type =
  15444. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15445. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15446. return 0;
  15447. }
  15448. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15449. <= 0) {
  15450. mg_snprintf(conn,
  15451. NULL, /* No truncation check for ebuf */
  15452. ebuf,
  15453. ebuf_len,
  15454. "%s",
  15455. "Bad response");
  15456. *err = 400;
  15457. return 0;
  15458. }
  15459. /* Message is a valid response */
  15460. if (((cl = get_header(conn->response_info.http_headers,
  15461. conn->response_info.num_headers,
  15462. "Transfer-Encoding"))
  15463. != NULL)
  15464. && mg_strcasecmp(cl, "identity")) {
  15465. if (mg_strcasecmp(cl, "chunked")) {
  15466. mg_snprintf(conn,
  15467. NULL, /* No truncation check for ebuf */
  15468. ebuf,
  15469. ebuf_len,
  15470. "%s",
  15471. "Bad request");
  15472. *err = 400;
  15473. return 0;
  15474. }
  15475. conn->is_chunked = 1;
  15476. conn->content_len = 0; /* not yet read */
  15477. } else if ((cl = get_header(conn->response_info.http_headers,
  15478. conn->response_info.num_headers,
  15479. "Content-Length"))
  15480. != NULL) {
  15481. char *endptr = NULL;
  15482. conn->content_len = strtoll(cl, &endptr, 10);
  15483. if ((endptr == cl) || (conn->content_len < 0)) {
  15484. mg_snprintf(conn,
  15485. NULL, /* No truncation check for ebuf */
  15486. ebuf,
  15487. ebuf_len,
  15488. "%s",
  15489. "Bad request");
  15490. *err = 411;
  15491. return 0;
  15492. }
  15493. /* Publish the content length back to the response info. */
  15494. conn->response_info.content_length = conn->content_len;
  15495. /* TODO: check if it is still used in response_info */
  15496. conn->request_info.content_length = conn->content_len;
  15497. /* TODO: we should also consider HEAD method */
  15498. if (conn->response_info.status_code == 304) {
  15499. conn->content_len = 0;
  15500. }
  15501. } else {
  15502. /* TODO: we should also consider HEAD method */
  15503. if (((conn->response_info.status_code >= 100)
  15504. && (conn->response_info.status_code <= 199))
  15505. || (conn->response_info.status_code == 204)
  15506. || (conn->response_info.status_code == 304)) {
  15507. conn->content_len = 0;
  15508. } else {
  15509. conn->content_len = -1; /* unknown content length */
  15510. }
  15511. }
  15512. return 1;
  15513. }
  15514. int
  15515. mg_get_response(struct mg_connection *conn,
  15516. char *ebuf,
  15517. size_t ebuf_len,
  15518. int timeout)
  15519. {
  15520. int err, ret;
  15521. char txt[32]; /* will not overflow */
  15522. char *save_timeout;
  15523. char *new_timeout;
  15524. if (ebuf_len > 0) {
  15525. ebuf[0] = '\0';
  15526. }
  15527. if (!conn) {
  15528. mg_snprintf(conn,
  15529. NULL, /* No truncation check for ebuf */
  15530. ebuf,
  15531. ebuf_len,
  15532. "%s",
  15533. "Parameter error");
  15534. return -1;
  15535. }
  15536. /* Reset the previous responses */
  15537. conn->data_len = 0;
  15538. /* Implementation of API function for HTTP clients */
  15539. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15540. if (timeout >= 0) {
  15541. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15542. new_timeout = txt;
  15543. } else {
  15544. new_timeout = NULL;
  15545. }
  15546. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15547. ret = get_response(conn, ebuf, ebuf_len, &err);
  15548. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15549. /* TODO: here, the URI is the http response code */
  15550. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15551. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15552. /* TODO (mid): Define proper return values - maybe return length?
  15553. * For the first test use <0 for error and >0 for OK */
  15554. return (ret == 0) ? -1 : +1;
  15555. }
  15556. struct mg_connection *
  15557. mg_download(const char *host,
  15558. int port,
  15559. int use_ssl,
  15560. char *ebuf,
  15561. size_t ebuf_len,
  15562. const char *fmt,
  15563. ...)
  15564. {
  15565. struct mg_connection *conn;
  15566. va_list ap;
  15567. int i;
  15568. int reqerr;
  15569. if (ebuf_len > 0) {
  15570. ebuf[0] = '\0';
  15571. }
  15572. va_start(ap, fmt);
  15573. /* open a connection */
  15574. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15575. if (conn != NULL) {
  15576. i = mg_vprintf(conn, fmt, ap);
  15577. if (i <= 0) {
  15578. mg_snprintf(conn,
  15579. NULL, /* No truncation check for ebuf */
  15580. ebuf,
  15581. ebuf_len,
  15582. "%s",
  15583. "Error sending request");
  15584. } else {
  15585. /* make sure the buffer is clear */
  15586. conn->data_len = 0;
  15587. get_response(conn, ebuf, ebuf_len, &reqerr);
  15588. /* TODO: here, the URI is the http response code */
  15589. conn->request_info.local_uri = conn->request_info.request_uri;
  15590. }
  15591. }
  15592. /* if an error occurred, close the connection */
  15593. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15594. mg_close_connection(conn);
  15595. conn = NULL;
  15596. }
  15597. va_end(ap);
  15598. return conn;
  15599. }
  15600. struct websocket_client_thread_data {
  15601. struct mg_connection *conn;
  15602. mg_websocket_data_handler data_handler;
  15603. mg_websocket_close_handler close_handler;
  15604. void *callback_data;
  15605. };
  15606. #if defined(USE_WEBSOCKET)
  15607. #if defined(_WIN32)
  15608. static unsigned __stdcall websocket_client_thread(void *data)
  15609. #else
  15610. static void *
  15611. websocket_client_thread(void *data)
  15612. #endif
  15613. {
  15614. struct websocket_client_thread_data *cdata =
  15615. (struct websocket_client_thread_data *)data;
  15616. void *user_thread_ptr = NULL;
  15617. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15618. struct sigaction sa;
  15619. /* Ignore SIGPIPE */
  15620. memset(&sa, 0, sizeof(sa));
  15621. sa.sa_handler = SIG_IGN;
  15622. sigaction(SIGPIPE, &sa, NULL);
  15623. #endif
  15624. mg_set_thread_name("ws-clnt");
  15625. if (cdata->conn->phys_ctx) {
  15626. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15627. /* 3 indicates a websocket client thread */
  15628. /* TODO: check if conn->phys_ctx can be set */
  15629. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15630. cdata->conn->phys_ctx, 3);
  15631. }
  15632. }
  15633. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15634. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15635. if (cdata->close_handler != NULL) {
  15636. cdata->close_handler(cdata->conn, cdata->callback_data);
  15637. }
  15638. /* The websocket_client context has only this thread. If it runs out,
  15639. set the stop_flag to 2 (= "stopped"). */
  15640. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15641. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15642. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15643. 3,
  15644. user_thread_ptr);
  15645. }
  15646. mg_free((void *)cdata);
  15647. #if defined(_WIN32)
  15648. return 0;
  15649. #else
  15650. return NULL;
  15651. #endif
  15652. }
  15653. #endif
  15654. static struct mg_connection *
  15655. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15656. int use_ssl,
  15657. char *error_buffer,
  15658. size_t error_buffer_size,
  15659. const char *path,
  15660. const char *origin,
  15661. const char *extensions,
  15662. mg_websocket_data_handler data_func,
  15663. mg_websocket_close_handler close_func,
  15664. void *user_data)
  15665. {
  15666. struct mg_connection *conn = NULL;
  15667. #if defined(USE_WEBSOCKET)
  15668. struct websocket_client_thread_data *thread_data;
  15669. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15670. const char *host = client_options->host;
  15671. int i;
  15672. #if defined(__clang__)
  15673. #pragma clang diagnostic push
  15674. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15675. #endif
  15676. /* Establish the client connection and request upgrade */
  15677. conn = mg_connect_client_impl(client_options,
  15678. use_ssl,
  15679. error_buffer,
  15680. error_buffer_size);
  15681. /* Connection object will be null if something goes wrong */
  15682. if (conn == NULL) {
  15683. /* error_buffer should be already filled ... */
  15684. if (!error_buffer[0]) {
  15685. /* ... if not add an error message */
  15686. mg_snprintf(conn,
  15687. NULL, /* No truncation check for ebuf */
  15688. error_buffer,
  15689. error_buffer_size,
  15690. "Unexpected error");
  15691. }
  15692. return NULL;
  15693. }
  15694. if (origin != NULL) {
  15695. if (extensions != NULL) {
  15696. i = mg_printf(conn,
  15697. "GET %s HTTP/1.1\r\n"
  15698. "Host: %s\r\n"
  15699. "Upgrade: websocket\r\n"
  15700. "Connection: Upgrade\r\n"
  15701. "Sec-WebSocket-Key: %s\r\n"
  15702. "Sec-WebSocket-Version: 13\r\n"
  15703. "Sec-WebSocket-Extensions: %s\r\n"
  15704. "Origin: %s\r\n"
  15705. "\r\n",
  15706. path,
  15707. host,
  15708. magic,
  15709. extensions,
  15710. origin);
  15711. } else {
  15712. i = mg_printf(conn,
  15713. "GET %s HTTP/1.1\r\n"
  15714. "Host: %s\r\n"
  15715. "Upgrade: websocket\r\n"
  15716. "Connection: Upgrade\r\n"
  15717. "Sec-WebSocket-Key: %s\r\n"
  15718. "Sec-WebSocket-Version: 13\r\n"
  15719. "Origin: %s\r\n"
  15720. "\r\n",
  15721. path,
  15722. host,
  15723. magic,
  15724. origin);
  15725. }
  15726. } else {
  15727. if (extensions != NULL) {
  15728. i = mg_printf(conn,
  15729. "GET %s HTTP/1.1\r\n"
  15730. "Host: %s\r\n"
  15731. "Upgrade: websocket\r\n"
  15732. "Connection: Upgrade\r\n"
  15733. "Sec-WebSocket-Key: %s\r\n"
  15734. "Sec-WebSocket-Version: 13\r\n"
  15735. "Sec-WebSocket-Extensions: %s\r\n"
  15736. "\r\n",
  15737. path,
  15738. host,
  15739. magic,
  15740. extensions);
  15741. } else {
  15742. i = mg_printf(conn,
  15743. "GET %s HTTP/1.1\r\n"
  15744. "Host: %s\r\n"
  15745. "Upgrade: websocket\r\n"
  15746. "Connection: Upgrade\r\n"
  15747. "Sec-WebSocket-Key: %s\r\n"
  15748. "Sec-WebSocket-Version: 13\r\n"
  15749. "\r\n",
  15750. path,
  15751. host,
  15752. magic);
  15753. }
  15754. }
  15755. if (i <= 0) {
  15756. mg_snprintf(conn,
  15757. NULL, /* No truncation check for ebuf */
  15758. error_buffer,
  15759. error_buffer_size,
  15760. "%s",
  15761. "Error sending request");
  15762. mg_close_connection(conn);
  15763. return NULL;
  15764. }
  15765. conn->data_len = 0;
  15766. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15767. mg_close_connection(conn);
  15768. return NULL;
  15769. }
  15770. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15771. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15772. #if defined(__clang__)
  15773. #pragma clang diagnostic pop
  15774. #endif
  15775. if (conn->response_info.status_code != 101) {
  15776. /* We sent an "upgrade" request. For a correct websocket
  15777. * protocol handshake, we expect a "101 Continue" response.
  15778. * Otherwise it is a protocol violation. Maybe the HTTP
  15779. * Server does not know websockets. */
  15780. if (!*error_buffer) {
  15781. /* set an error, if not yet set */
  15782. mg_snprintf(conn,
  15783. NULL, /* No truncation check for ebuf */
  15784. error_buffer,
  15785. error_buffer_size,
  15786. "Unexpected server reply");
  15787. }
  15788. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15789. mg_close_connection(conn);
  15790. return NULL;
  15791. }
  15792. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15793. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15794. if (!thread_data) {
  15795. DEBUG_TRACE("%s\r\n", "Out of memory");
  15796. mg_close_connection(conn);
  15797. return NULL;
  15798. }
  15799. thread_data->conn = conn;
  15800. thread_data->data_handler = data_func;
  15801. thread_data->close_handler = close_func;
  15802. thread_data->callback_data = user_data;
  15803. conn->phys_ctx->worker_threadids =
  15804. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15805. if (!conn->phys_ctx->worker_threadids) {
  15806. DEBUG_TRACE("%s\r\n", "Out of memory");
  15807. mg_free(thread_data);
  15808. mg_close_connection(conn);
  15809. return NULL;
  15810. }
  15811. /* Now upgrade to ws/wss client context */
  15812. conn->phys_ctx->user_data = user_data;
  15813. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15814. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15815. /* Start a thread to read the websocket client connection
  15816. * This thread will automatically stop when mg_disconnect is
  15817. * called on the client connection */
  15818. if (mg_start_thread_with_id(websocket_client_thread,
  15819. thread_data,
  15820. conn->phys_ctx->worker_threadids)
  15821. != 0) {
  15822. conn->phys_ctx->cfg_worker_threads = 0;
  15823. mg_free(thread_data);
  15824. mg_close_connection(conn);
  15825. conn = NULL;
  15826. DEBUG_TRACE("%s",
  15827. "Websocket client connect thread could not be started\r\n");
  15828. }
  15829. #else
  15830. /* Appease "unused parameter" warnings */
  15831. (void)client_options;
  15832. (void)use_ssl;
  15833. (void)error_buffer;
  15834. (void)error_buffer_size;
  15835. (void)path;
  15836. (void)origin;
  15837. (void)extensions;
  15838. (void)user_data;
  15839. (void)data_func;
  15840. (void)close_func;
  15841. #endif
  15842. return conn;
  15843. }
  15844. struct mg_connection *
  15845. mg_connect_websocket_client(const char *host,
  15846. int port,
  15847. int use_ssl,
  15848. char *error_buffer,
  15849. size_t error_buffer_size,
  15850. const char *path,
  15851. const char *origin,
  15852. mg_websocket_data_handler data_func,
  15853. mg_websocket_close_handler close_func,
  15854. void *user_data)
  15855. {
  15856. struct mg_client_options client_options;
  15857. memset(&client_options, 0, sizeof(client_options));
  15858. client_options.host = host;
  15859. client_options.port = port;
  15860. return mg_connect_websocket_client_impl(&client_options,
  15861. use_ssl,
  15862. error_buffer,
  15863. error_buffer_size,
  15864. path,
  15865. origin,
  15866. NULL,
  15867. data_func,
  15868. close_func,
  15869. user_data);
  15870. }
  15871. struct mg_connection *
  15872. mg_connect_websocket_client_secure(
  15873. const struct mg_client_options *client_options,
  15874. char *error_buffer,
  15875. size_t error_buffer_size,
  15876. const char *path,
  15877. const char *origin,
  15878. mg_websocket_data_handler data_func,
  15879. mg_websocket_close_handler close_func,
  15880. void *user_data)
  15881. {
  15882. if (!client_options) {
  15883. return NULL;
  15884. }
  15885. return mg_connect_websocket_client_impl(client_options,
  15886. 1,
  15887. error_buffer,
  15888. error_buffer_size,
  15889. path,
  15890. origin,
  15891. NULL,
  15892. data_func,
  15893. close_func,
  15894. user_data);
  15895. }
  15896. struct mg_connection *
  15897. mg_connect_websocket_client_extensions(const char *host,
  15898. int port,
  15899. int use_ssl,
  15900. char *error_buffer,
  15901. size_t error_buffer_size,
  15902. const char *path,
  15903. const char *origin,
  15904. const char *extensions,
  15905. mg_websocket_data_handler data_func,
  15906. mg_websocket_close_handler close_func,
  15907. void *user_data)
  15908. {
  15909. struct mg_client_options client_options;
  15910. memset(&client_options, 0, sizeof(client_options));
  15911. client_options.host = host;
  15912. client_options.port = port;
  15913. return mg_connect_websocket_client_impl(&client_options,
  15914. use_ssl,
  15915. error_buffer,
  15916. error_buffer_size,
  15917. path,
  15918. origin,
  15919. extensions,
  15920. data_func,
  15921. close_func,
  15922. user_data);
  15923. }
  15924. struct mg_connection *
  15925. mg_connect_websocket_client_secure_extensions(
  15926. const struct mg_client_options *client_options,
  15927. char *error_buffer,
  15928. size_t error_buffer_size,
  15929. const char *path,
  15930. const char *origin,
  15931. const char *extensions,
  15932. mg_websocket_data_handler data_func,
  15933. mg_websocket_close_handler close_func,
  15934. void *user_data)
  15935. {
  15936. if (!client_options) {
  15937. return NULL;
  15938. }
  15939. return mg_connect_websocket_client_impl(client_options,
  15940. 1,
  15941. error_buffer,
  15942. error_buffer_size,
  15943. path,
  15944. origin,
  15945. extensions,
  15946. data_func,
  15947. close_func,
  15948. user_data);
  15949. }
  15950. /* Prepare connection data structure */
  15951. static void
  15952. init_connection(struct mg_connection *conn)
  15953. {
  15954. /* Is keep alive allowed by the server */
  15955. int keep_alive_enabled =
  15956. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15957. if (!keep_alive_enabled) {
  15958. conn->must_close = 1;
  15959. }
  15960. /* Important: on new connection, reset the receiving buffer. Credit
  15961. * goes to crule42. */
  15962. conn->data_len = 0;
  15963. conn->handled_requests = 0;
  15964. conn->connection_type = CONNECTION_TYPE_INVALID;
  15965. mg_set_user_connection_data(conn, NULL);
  15966. #if defined(USE_SERVER_STATS)
  15967. conn->conn_state = 2; /* init */
  15968. #endif
  15969. /* call the init_connection callback if assigned */
  15970. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15971. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15972. void *conn_data = NULL;
  15973. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15974. mg_set_user_connection_data(conn, conn_data);
  15975. }
  15976. }
  15977. }
  15978. /* Process a connection - may handle multiple requests
  15979. * using the same connection.
  15980. * Must be called with a valid connection (conn and
  15981. * conn->phys_ctx must be valid).
  15982. */
  15983. static void
  15984. process_new_connection(struct mg_connection *conn)
  15985. {
  15986. struct mg_request_info *ri = &conn->request_info;
  15987. int keep_alive, discard_len;
  15988. char ebuf[100];
  15989. const char *hostend;
  15990. int reqerr, uri_type;
  15991. #if defined(USE_SERVER_STATS)
  15992. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15993. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15994. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15995. #endif
  15996. DEBUG_TRACE("Start processing connection from %s",
  15997. conn->request_info.remote_addr);
  15998. /* Loop over multiple requests sent using the same connection
  15999. * (while "keep alive"). */
  16000. do {
  16001. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16002. conn->handled_requests + 1);
  16003. #if defined(USE_SERVER_STATS)
  16004. conn->conn_state = 3; /* ready */
  16005. #endif
  16006. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16007. /* The request sent by the client could not be understood by
  16008. * the server, or it was incomplete or a timeout. Send an
  16009. * error message and close the connection. */
  16010. if (reqerr > 0) {
  16011. DEBUG_ASSERT(ebuf[0] != '\0');
  16012. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16013. }
  16014. } else if (strcmp(ri->http_version, "1.0")
  16015. && strcmp(ri->http_version, "1.1")) {
  16016. /* HTTP/2 is not allowed here */
  16017. mg_snprintf(conn,
  16018. NULL, /* No truncation check for ebuf */
  16019. ebuf,
  16020. sizeof(ebuf),
  16021. "Bad HTTP version: [%s]",
  16022. ri->http_version);
  16023. mg_send_http_error(conn, 505, "%s", ebuf);
  16024. }
  16025. if (ebuf[0] == '\0') {
  16026. uri_type = get_uri_type(conn->request_info.request_uri);
  16027. switch (uri_type) {
  16028. case 1:
  16029. /* Asterisk */
  16030. conn->request_info.local_uri_raw = 0;
  16031. /* TODO: Deal with '*'. */
  16032. break;
  16033. case 2:
  16034. /* relative uri */
  16035. conn->request_info.local_uri_raw =
  16036. conn->request_info.request_uri;
  16037. break;
  16038. case 3:
  16039. case 4:
  16040. /* absolute uri (with/without port) */
  16041. hostend = get_rel_url_at_current_server(
  16042. conn->request_info.request_uri, conn);
  16043. if (hostend) {
  16044. conn->request_info.local_uri_raw = hostend;
  16045. } else {
  16046. conn->request_info.local_uri_raw = NULL;
  16047. }
  16048. break;
  16049. default:
  16050. mg_snprintf(conn,
  16051. NULL, /* No truncation check for ebuf */
  16052. ebuf,
  16053. sizeof(ebuf),
  16054. "Invalid URI");
  16055. mg_send_http_error(conn, 400, "%s", ebuf);
  16056. conn->request_info.local_uri_raw = NULL;
  16057. break;
  16058. }
  16059. conn->request_info.local_uri =
  16060. (char *)conn->request_info.local_uri_raw;
  16061. }
  16062. if (ebuf[0] != '\0') {
  16063. conn->protocol_type = -1;
  16064. } else {
  16065. /* HTTP/1 allows protocol upgrade */
  16066. conn->protocol_type = should_switch_to_protocol(conn);
  16067. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16068. /* This will occur, if a HTTP/1.1 request should be upgraded
  16069. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16070. * Since most (all?) major browsers only support HTTP/2 using
  16071. * ALPN, this is hard to test and very low priority.
  16072. * Deactivate it (at least for now).
  16073. */
  16074. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16075. }
  16076. }
  16077. DEBUG_TRACE("http: %s, error: %s",
  16078. (ri->http_version ? ri->http_version : "none"),
  16079. (ebuf[0] ? ebuf : "none"));
  16080. if (ebuf[0] == '\0') {
  16081. if (conn->request_info.local_uri) {
  16082. /* handle request to local server */
  16083. handle_request_stat_log(conn);
  16084. } else {
  16085. /* TODO: handle non-local request (PROXY) */
  16086. conn->must_close = 1;
  16087. }
  16088. } else {
  16089. conn->must_close = 1;
  16090. }
  16091. /* Response complete. Free header buffer */
  16092. free_buffered_response_header_list(conn);
  16093. if (ri->remote_user != NULL) {
  16094. mg_free((void *)ri->remote_user);
  16095. /* Important! When having connections with and without auth
  16096. * would cause double free and then crash */
  16097. ri->remote_user = NULL;
  16098. }
  16099. /* NOTE(lsm): order is important here. should_keep_alive() call
  16100. * is using parsed request, which will be invalid after
  16101. * memmove's below.
  16102. * Therefore, memorize should_keep_alive() result now for later
  16103. * use in loop exit condition. */
  16104. /* Enable it only if this request is completely discardable. */
  16105. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16106. && should_keep_alive(conn) && (conn->content_len >= 0)
  16107. && (conn->request_len > 0)
  16108. && ((conn->is_chunked == 4)
  16109. || (!conn->is_chunked
  16110. && ((conn->consumed_content == conn->content_len)
  16111. || ((conn->request_len + conn->content_len)
  16112. <= conn->data_len))))
  16113. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16114. if (keep_alive) {
  16115. /* Discard all buffered data for this request */
  16116. discard_len =
  16117. ((conn->request_len + conn->content_len) < conn->data_len)
  16118. ? (int)(conn->request_len + conn->content_len)
  16119. : conn->data_len;
  16120. conn->data_len -= discard_len;
  16121. if (conn->data_len > 0) {
  16122. DEBUG_TRACE("discard_len = %d", discard_len);
  16123. memmove(conn->buf,
  16124. conn->buf + discard_len,
  16125. (size_t)conn->data_len);
  16126. }
  16127. }
  16128. DEBUG_ASSERT(conn->data_len >= 0);
  16129. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16130. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16131. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16132. (long int)conn->data_len,
  16133. (long int)conn->buf_size);
  16134. break;
  16135. }
  16136. conn->handled_requests++;
  16137. } while (keep_alive);
  16138. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16139. conn->request_info.remote_addr,
  16140. difftime(time(NULL), conn->conn_birth_time));
  16141. close_connection(conn);
  16142. #if defined(USE_SERVER_STATS)
  16143. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16144. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16145. #endif
  16146. }
  16147. #if defined(ALTERNATIVE_QUEUE)
  16148. static void
  16149. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16150. {
  16151. unsigned int i;
  16152. while (!ctx->stop_flag) {
  16153. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16154. /* find a free worker slot and signal it */
  16155. if (ctx->client_socks[i].in_use == 2) {
  16156. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16157. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16158. ctx->client_socks[i] = *sp;
  16159. ctx->client_socks[i].in_use = 1;
  16160. /* socket has been moved to the consumer */
  16161. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16162. (void)event_signal(ctx->client_wait_events[i]);
  16163. return;
  16164. }
  16165. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16166. }
  16167. }
  16168. /* queue is full */
  16169. mg_sleep(1);
  16170. }
  16171. /* must consume */
  16172. set_blocking_mode(sp->sock);
  16173. closesocket(sp->sock);
  16174. }
  16175. static int
  16176. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16177. {
  16178. DEBUG_TRACE("%s", "going idle");
  16179. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16180. ctx->client_socks[thread_index].in_use = 2;
  16181. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16182. event_wait(ctx->client_wait_events[thread_index]);
  16183. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16184. *sp = ctx->client_socks[thread_index];
  16185. if (ctx->stop_flag) {
  16186. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16187. if (sp->in_use == 1) {
  16188. /* must consume */
  16189. set_blocking_mode(sp->sock);
  16190. closesocket(sp->sock);
  16191. }
  16192. return 0;
  16193. }
  16194. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16195. if (sp->in_use == 1) {
  16196. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16197. return 1;
  16198. }
  16199. /* must not reach here */
  16200. DEBUG_ASSERT(0);
  16201. return 0;
  16202. }
  16203. #else /* ALTERNATIVE_QUEUE */
  16204. /* Worker threads take accepted socket from the queue */
  16205. static int
  16206. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16207. {
  16208. (void)thread_index;
  16209. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16210. DEBUG_TRACE("%s", "going idle");
  16211. /* If the queue is empty, wait. We're idle at this point. */
  16212. while ((ctx->sq_head == ctx->sq_tail)
  16213. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16214. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16215. }
  16216. /* If we're stopping, sq_head may be equal to sq_tail. */
  16217. if (ctx->sq_head > ctx->sq_tail) {
  16218. /* Copy socket from the queue and increment tail */
  16219. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16220. ctx->sq_tail++;
  16221. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16222. /* Wrap pointers if needed */
  16223. while (ctx->sq_tail > ctx->sq_size) {
  16224. ctx->sq_tail -= ctx->sq_size;
  16225. ctx->sq_head -= ctx->sq_size;
  16226. }
  16227. }
  16228. (void)pthread_cond_signal(&ctx->sq_empty);
  16229. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16230. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16231. }
  16232. /* Master thread adds accepted socket to a queue */
  16233. static void
  16234. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16235. {
  16236. int queue_filled;
  16237. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16238. queue_filled = ctx->sq_head - ctx->sq_tail;
  16239. /* If the queue is full, wait */
  16240. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16241. && (queue_filled >= ctx->sq_size)) {
  16242. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16243. #if defined(USE_SERVER_STATS)
  16244. if (queue_filled > ctx->sq_max_fill) {
  16245. ctx->sq_max_fill = queue_filled;
  16246. }
  16247. #endif
  16248. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16249. ctx->sq_blocked = 0; /* Not blocked now */
  16250. queue_filled = ctx->sq_head - ctx->sq_tail;
  16251. }
  16252. if (queue_filled < ctx->sq_size) {
  16253. /* Copy socket to the queue and increment head */
  16254. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16255. ctx->sq_head++;
  16256. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16257. }
  16258. queue_filled = ctx->sq_head - ctx->sq_tail;
  16259. #if defined(USE_SERVER_STATS)
  16260. if (queue_filled > ctx->sq_max_fill) {
  16261. ctx->sq_max_fill = queue_filled;
  16262. }
  16263. #endif
  16264. (void)pthread_cond_signal(&ctx->sq_full);
  16265. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16266. }
  16267. #endif /* ALTERNATIVE_QUEUE */
  16268. static void
  16269. worker_thread_run(struct mg_connection *conn)
  16270. {
  16271. struct mg_context *ctx = conn->phys_ctx;
  16272. int thread_index;
  16273. struct mg_workerTLS tls;
  16274. mg_set_thread_name("worker");
  16275. tls.is_master = 0;
  16276. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16277. #if defined(_WIN32)
  16278. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16279. #endif
  16280. /* Initialize thread local storage before calling any callback */
  16281. pthread_setspecific(sTlsKey, &tls);
  16282. /* Check if there is a user callback */
  16283. if (ctx->callbacks.init_thread) {
  16284. /* call init_thread for a worker thread (type 1), and store the
  16285. * return value */
  16286. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16287. } else {
  16288. /* No callback: set user pointer to NULL */
  16289. tls.user_ptr = NULL;
  16290. }
  16291. /* Connection structure has been pre-allocated */
  16292. thread_index = (int)(conn - ctx->worker_connections);
  16293. if ((thread_index < 0)
  16294. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16295. mg_cry_ctx_internal(ctx,
  16296. "Internal error: Invalid worker index %i",
  16297. thread_index);
  16298. return;
  16299. }
  16300. /* Request buffers are not pre-allocated. They are private to the
  16301. * request and do not contain any state information that might be
  16302. * of interest to anyone observing a server status. */
  16303. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16304. if (conn->buf == NULL) {
  16305. mg_cry_ctx_internal(
  16306. ctx,
  16307. "Out of memory: Cannot allocate buffer for worker %i",
  16308. thread_index);
  16309. return;
  16310. }
  16311. conn->buf_size = (int)ctx->max_request_size;
  16312. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16313. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16314. conn->request_info.user_data = ctx->user_data;
  16315. /* Allocate a mutex for this connection to allow communication both
  16316. * within the request handler and from elsewhere in the application
  16317. */
  16318. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16319. mg_free(conn->buf);
  16320. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16321. return;
  16322. }
  16323. #if defined(USE_SERVER_STATS)
  16324. conn->conn_state = 1; /* not consumed */
  16325. #endif
  16326. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16327. * signal sq_empty condvar to wake up the master waiting in
  16328. * produce_socket() */
  16329. while (consume_socket(ctx, &conn->client, thread_index)) {
  16330. /* New connections must start with new protocol negotiation */
  16331. tls.alpn_proto = NULL;
  16332. #if defined(USE_SERVER_STATS)
  16333. conn->conn_close_time = 0;
  16334. #endif
  16335. conn->conn_birth_time = time(NULL);
  16336. /* Fill in IP, port info early so even if SSL setup below fails,
  16337. * error handler would have the corresponding info.
  16338. * Thanks to Johannes Winkelmann for the patch.
  16339. */
  16340. conn->request_info.remote_port =
  16341. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16342. conn->request_info.server_port =
  16343. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16344. sockaddr_to_string(conn->request_info.remote_addr,
  16345. sizeof(conn->request_info.remote_addr),
  16346. &conn->client.rsa);
  16347. DEBUG_TRACE("Incomming %sconnection from %s",
  16348. (conn->client.is_ssl ? "SSL " : ""),
  16349. conn->request_info.remote_addr);
  16350. conn->request_info.is_ssl = conn->client.is_ssl;
  16351. if (conn->client.is_ssl) {
  16352. #if defined(USE_MBEDTLS)
  16353. /* HTTPS connection */
  16354. if (mbed_ssl_accept(&(conn->ssl),
  16355. conn->dom_ctx->ssl_ctx,
  16356. (int *)&(conn->client.sock),
  16357. conn->phys_ctx)
  16358. == 0) {
  16359. /* conn->dom_ctx is set in get_request */
  16360. /* process HTTPS connection */
  16361. init_connection(conn);
  16362. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16363. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16364. process_new_connection(conn);
  16365. } else {
  16366. /* make sure the connection is cleaned up on SSL failure */
  16367. close_connection(conn);
  16368. }
  16369. #elif !defined(NO_SSL)
  16370. /* HTTPS connection */
  16371. if (sslize(conn, SSL_accept, NULL)) {
  16372. /* conn->dom_ctx is set in get_request */
  16373. /* Get SSL client certificate information (if set) */
  16374. struct mg_client_cert client_cert;
  16375. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16376. conn->request_info.client_cert = &client_cert;
  16377. }
  16378. /* process HTTPS connection */
  16379. #if defined(USE_HTTP2)
  16380. if ((tls.alpn_proto != NULL)
  16381. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16382. /* process HTTPS/2 connection */
  16383. init_connection(conn);
  16384. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16385. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16386. conn->content_len =
  16387. -1; /* content length is not predefined */
  16388. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16389. process_new_http2_connection(conn);
  16390. } else
  16391. #endif
  16392. {
  16393. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16394. init_connection(conn);
  16395. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16396. /* Start with HTTP, WS will be an "upgrade" request later */
  16397. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16398. process_new_connection(conn);
  16399. }
  16400. /* Free client certificate info */
  16401. if (conn->request_info.client_cert) {
  16402. mg_free((void *)(conn->request_info.client_cert->subject));
  16403. mg_free((void *)(conn->request_info.client_cert->issuer));
  16404. mg_free((void *)(conn->request_info.client_cert->serial));
  16405. mg_free((void *)(conn->request_info.client_cert->finger));
  16406. /* Free certificate memory */
  16407. X509_free(
  16408. (X509 *)conn->request_info.client_cert->peer_cert);
  16409. conn->request_info.client_cert->peer_cert = 0;
  16410. conn->request_info.client_cert->subject = 0;
  16411. conn->request_info.client_cert->issuer = 0;
  16412. conn->request_info.client_cert->serial = 0;
  16413. conn->request_info.client_cert->finger = 0;
  16414. conn->request_info.client_cert = 0;
  16415. }
  16416. } else {
  16417. /* make sure the connection is cleaned up on SSL failure */
  16418. close_connection(conn);
  16419. }
  16420. #endif
  16421. } else {
  16422. /* process HTTP connection */
  16423. init_connection(conn);
  16424. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16425. /* Start with HTTP, WS will be an "upgrade" request later */
  16426. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16427. process_new_connection(conn);
  16428. }
  16429. DEBUG_TRACE("%s", "Connection closed");
  16430. #if defined(USE_SERVER_STATS)
  16431. conn->conn_close_time = time(NULL);
  16432. #endif
  16433. }
  16434. /* Call exit thread user callback */
  16435. if (ctx->callbacks.exit_thread) {
  16436. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16437. }
  16438. /* delete thread local storage objects */
  16439. pthread_setspecific(sTlsKey, NULL);
  16440. #if defined(_WIN32)
  16441. CloseHandle(tls.pthread_cond_helper_mutex);
  16442. #endif
  16443. pthread_mutex_destroy(&conn->mutex);
  16444. /* Free the request buffer. */
  16445. conn->buf_size = 0;
  16446. mg_free(conn->buf);
  16447. conn->buf = NULL;
  16448. /* Free cleaned URI (if any) */
  16449. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16450. mg_free((void *)conn->request_info.local_uri);
  16451. conn->request_info.local_uri = NULL;
  16452. }
  16453. #if defined(USE_SERVER_STATS)
  16454. conn->conn_state = 9; /* done */
  16455. #endif
  16456. DEBUG_TRACE("%s", "exiting");
  16457. }
  16458. /* Threads have different return types on Windows and Unix. */
  16459. #if defined(_WIN32)
  16460. static unsigned __stdcall worker_thread(void *thread_func_param)
  16461. {
  16462. worker_thread_run((struct mg_connection *)thread_func_param);
  16463. return 0;
  16464. }
  16465. #else
  16466. static void *
  16467. worker_thread(void *thread_func_param)
  16468. {
  16469. #if !defined(__ZEPHYR__)
  16470. struct sigaction sa;
  16471. /* Ignore SIGPIPE */
  16472. memset(&sa, 0, sizeof(sa));
  16473. sa.sa_handler = SIG_IGN;
  16474. sigaction(SIGPIPE, &sa, NULL);
  16475. #endif
  16476. worker_thread_run((struct mg_connection *)thread_func_param);
  16477. return NULL;
  16478. }
  16479. #endif /* _WIN32 */
  16480. /* This is an internal function, thus all arguments are expected to be
  16481. * valid - a NULL check is not required. */
  16482. static void
  16483. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16484. {
  16485. struct socket so;
  16486. char src_addr[IP_ADDR_STR_LEN];
  16487. socklen_t len = sizeof(so.rsa);
  16488. #if !defined(__ZEPHYR__)
  16489. int on = 1;
  16490. #endif
  16491. memset(&so, 0, sizeof(so));
  16492. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16493. == INVALID_SOCKET) {
  16494. } else if (check_acl(ctx, &so.rsa) != 1) {
  16495. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16496. mg_cry_ctx_internal(ctx,
  16497. "%s: %s is not allowed to connect",
  16498. __func__,
  16499. src_addr);
  16500. closesocket(so.sock);
  16501. } else {
  16502. /* Put so socket structure into the queue */
  16503. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16504. set_close_on_exec(so.sock, NULL, ctx);
  16505. so.is_ssl = listener->is_ssl;
  16506. so.ssl_redir = listener->ssl_redir;
  16507. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16508. mg_cry_ctx_internal(ctx,
  16509. "%s: getsockname() failed: %s",
  16510. __func__,
  16511. strerror(ERRNO));
  16512. }
  16513. #if !defined(__ZEPHYR__)
  16514. if ((so.lsa.sa.sa_family == AF_INET)
  16515. || (so.lsa.sa.sa_family == AF_INET6)) {
  16516. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16517. * This is needed because if HTTP-level keep-alive
  16518. * is enabled, and client resets the connection, server won't get
  16519. * TCP FIN or RST and will keep the connection open forever. With
  16520. * TCP keep-alive, next keep-alive handshake will figure out that
  16521. * the client is down and will close the server end.
  16522. * Thanks to Igor Klopov who suggested the patch. */
  16523. if (setsockopt(so.sock,
  16524. SOL_SOCKET,
  16525. SO_KEEPALIVE,
  16526. (SOCK_OPT_TYPE)&on,
  16527. sizeof(on))
  16528. != 0) {
  16529. mg_cry_ctx_internal(
  16530. ctx,
  16531. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16532. __func__,
  16533. strerror(ERRNO));
  16534. }
  16535. }
  16536. #endif
  16537. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16538. * to effectively fill up the underlying IP packet payload and
  16539. * reduce the overhead of sending lots of small buffers. However
  16540. * this hurts the server's throughput (ie. operations per second)
  16541. * when HTTP 1.1 persistent connections are used and the responses
  16542. * are relatively small (eg. less than 1400 bytes).
  16543. */
  16544. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16545. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16546. if (set_tcp_nodelay(&so, 1) != 0) {
  16547. mg_cry_ctx_internal(
  16548. ctx,
  16549. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16550. __func__,
  16551. strerror(ERRNO));
  16552. }
  16553. }
  16554. /* The "non blocking" property should already be
  16555. * inherited from the parent socket. Set it for
  16556. * non-compliant socket implementations. */
  16557. set_non_blocking_mode(so.sock);
  16558. so.in_use = 0;
  16559. produce_socket(ctx, &so);
  16560. }
  16561. }
  16562. static void
  16563. master_thread_run(struct mg_context *ctx)
  16564. {
  16565. struct mg_workerTLS tls;
  16566. struct mg_pollfd *pfd;
  16567. unsigned int i;
  16568. unsigned int workerthreadcount;
  16569. if (!ctx) {
  16570. return;
  16571. }
  16572. mg_set_thread_name("master");
  16573. /* Increase priority of the master thread */
  16574. #if defined(_WIN32)
  16575. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16576. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16577. int min_prio = sched_get_priority_min(SCHED_RR);
  16578. int max_prio = sched_get_priority_max(SCHED_RR);
  16579. if ((min_prio >= 0) && (max_prio >= 0)
  16580. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16581. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16582. struct sched_param sched_param = {0};
  16583. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16584. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16585. }
  16586. #endif
  16587. /* Initialize thread local storage */
  16588. #if defined(_WIN32)
  16589. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16590. #endif
  16591. tls.is_master = 1;
  16592. pthread_setspecific(sTlsKey, &tls);
  16593. if (ctx->callbacks.init_thread) {
  16594. /* Callback for the master thread (type 0) */
  16595. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16596. } else {
  16597. tls.user_ptr = NULL;
  16598. }
  16599. /* Lua background script "start" event */
  16600. #if defined(USE_LUA)
  16601. if (ctx->lua_background_state) {
  16602. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16603. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16604. /* call "start()" in Lua */
  16605. lua_getglobal(lstate, "start");
  16606. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16607. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16608. if (ret != 0) {
  16609. struct mg_connection fc;
  16610. lua_cry(fake_connection(&fc, ctx),
  16611. ret,
  16612. lstate,
  16613. "lua_background_script",
  16614. "start");
  16615. }
  16616. } else {
  16617. lua_pop(lstate, 1);
  16618. }
  16619. /* determine if there is a "log()" function in Lua background script */
  16620. lua_getglobal(lstate, "log");
  16621. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16622. ctx->lua_bg_log_available = 1;
  16623. }
  16624. lua_pop(lstate, 1);
  16625. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16626. }
  16627. #endif
  16628. /* Server starts *now* */
  16629. ctx->start_time = time(NULL);
  16630. /* Server accept loop */
  16631. pfd = ctx->listening_socket_fds;
  16632. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16633. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16634. pfd[i].fd = ctx->listening_sockets[i].sock;
  16635. pfd[i].events = POLLIN;
  16636. }
  16637. if (mg_poll(pfd,
  16638. ctx->num_listening_sockets,
  16639. SOCKET_TIMEOUT_QUANTUM,
  16640. &(ctx->stop_flag))
  16641. > 0) {
  16642. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16643. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16644. * successful poll, and POLLIN is defined as
  16645. * (POLLRDNORM | POLLRDBAND)
  16646. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16647. * pfd[i].revents == POLLIN. */
  16648. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16649. && (pfd[i].revents & POLLIN)) {
  16650. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16651. }
  16652. }
  16653. }
  16654. }
  16655. /* Here stop_flag is 1 - Initiate shutdown. */
  16656. DEBUG_TRACE("%s", "stopping workers");
  16657. /* Stop signal received: somebody called mg_stop. Quit. */
  16658. close_all_listening_sockets(ctx);
  16659. /* Wakeup workers that are waiting for connections to handle. */
  16660. #if defined(ALTERNATIVE_QUEUE)
  16661. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16662. event_signal(ctx->client_wait_events[i]);
  16663. }
  16664. #else
  16665. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16666. pthread_cond_broadcast(&ctx->sq_full);
  16667. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16668. #endif
  16669. /* Join all worker threads to avoid leaking threads. */
  16670. workerthreadcount = ctx->cfg_worker_threads;
  16671. for (i = 0; i < workerthreadcount; i++) {
  16672. if (ctx->worker_threadids[i] != 0) {
  16673. mg_join_thread(ctx->worker_threadids[i]);
  16674. }
  16675. }
  16676. #if defined(USE_LUA)
  16677. /* Free Lua state of lua background task */
  16678. if (ctx->lua_background_state) {
  16679. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16680. ctx->lua_bg_log_available = 0;
  16681. /* call "stop()" in Lua */
  16682. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16683. lua_getglobal(lstate, "stop");
  16684. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16685. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16686. if (ret != 0) {
  16687. struct mg_connection fc;
  16688. lua_cry(fake_connection(&fc, ctx),
  16689. ret,
  16690. lstate,
  16691. "lua_background_script",
  16692. "stop");
  16693. }
  16694. }
  16695. lua_close(lstate);
  16696. ctx->lua_background_state = 0;
  16697. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16698. }
  16699. #endif
  16700. DEBUG_TRACE("%s", "exiting");
  16701. /* call exit thread callback */
  16702. if (ctx->callbacks.exit_thread) {
  16703. /* Callback for the master thread (type 0) */
  16704. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16705. }
  16706. #if defined(_WIN32)
  16707. CloseHandle(tls.pthread_cond_helper_mutex);
  16708. #endif
  16709. pthread_setspecific(sTlsKey, NULL);
  16710. /* Signal mg_stop() that we're done.
  16711. * WARNING: This must be the very last thing this
  16712. * thread does, as ctx becomes invalid after this line. */
  16713. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16714. }
  16715. /* Threads have different return types on Windows and Unix. */
  16716. #if defined(_WIN32)
  16717. static unsigned __stdcall master_thread(void *thread_func_param)
  16718. {
  16719. master_thread_run((struct mg_context *)thread_func_param);
  16720. return 0;
  16721. }
  16722. #else
  16723. static void *
  16724. master_thread(void *thread_func_param)
  16725. {
  16726. #if !defined(__ZEPHYR__)
  16727. struct sigaction sa;
  16728. /* Ignore SIGPIPE */
  16729. memset(&sa, 0, sizeof(sa));
  16730. sa.sa_handler = SIG_IGN;
  16731. sigaction(SIGPIPE, &sa, NULL);
  16732. #endif
  16733. master_thread_run((struct mg_context *)thread_func_param);
  16734. return NULL;
  16735. }
  16736. #endif /* _WIN32 */
  16737. static void
  16738. free_context(struct mg_context *ctx)
  16739. {
  16740. int i;
  16741. struct mg_handler_info *tmp_rh;
  16742. if (ctx == NULL) {
  16743. return;
  16744. }
  16745. /* Call user callback */
  16746. if (ctx->callbacks.exit_context) {
  16747. ctx->callbacks.exit_context(ctx);
  16748. }
  16749. /* All threads exited, no sync is needed. Destroy thread mutex and
  16750. * condvars
  16751. */
  16752. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16753. #if defined(ALTERNATIVE_QUEUE)
  16754. mg_free(ctx->client_socks);
  16755. if (ctx->client_wait_events != NULL) {
  16756. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16757. event_destroy(ctx->client_wait_events[i]);
  16758. }
  16759. mg_free(ctx->client_wait_events);
  16760. }
  16761. #else
  16762. (void)pthread_cond_destroy(&ctx->sq_empty);
  16763. (void)pthread_cond_destroy(&ctx->sq_full);
  16764. mg_free(ctx->squeue);
  16765. #endif
  16766. /* Destroy other context global data structures mutex */
  16767. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16768. #if defined(USE_LUA)
  16769. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  16770. #endif
  16771. /* Deallocate config parameters */
  16772. for (i = 0; i < NUM_OPTIONS; i++) {
  16773. if (ctx->dd.config[i] != NULL) {
  16774. #if defined(_MSC_VER)
  16775. #pragma warning(suppress : 6001)
  16776. #endif
  16777. mg_free(ctx->dd.config[i]);
  16778. }
  16779. }
  16780. /* Deallocate request handlers */
  16781. while (ctx->dd.handlers) {
  16782. tmp_rh = ctx->dd.handlers;
  16783. ctx->dd.handlers = tmp_rh->next;
  16784. mg_free(tmp_rh->uri);
  16785. mg_free(tmp_rh);
  16786. }
  16787. #if defined(USE_MBEDTLS)
  16788. if (ctx->dd.ssl_ctx != NULL) {
  16789. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16790. mg_free(ctx->dd.ssl_ctx);
  16791. ctx->dd.ssl_ctx = NULL;
  16792. }
  16793. #elif !defined(NO_SSL)
  16794. /* Deallocate SSL context */
  16795. if (ctx->dd.ssl_ctx != NULL) {
  16796. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16797. int callback_ret =
  16798. (ctx->callbacks.external_ssl_ctx == NULL)
  16799. ? 0
  16800. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16801. if (callback_ret == 0) {
  16802. SSL_CTX_free(ctx->dd.ssl_ctx);
  16803. }
  16804. /* else: ignore error and ommit SSL_CTX_free in case
  16805. * callback_ret is 1 */
  16806. }
  16807. #endif /* !NO_SSL */
  16808. /* Deallocate worker thread ID array */
  16809. mg_free(ctx->worker_threadids);
  16810. /* Deallocate worker thread ID array */
  16811. mg_free(ctx->worker_connections);
  16812. /* deallocate system name string */
  16813. mg_free(ctx->systemName);
  16814. /* Deallocate context itself */
  16815. mg_free(ctx);
  16816. }
  16817. void
  16818. mg_stop(struct mg_context *ctx)
  16819. {
  16820. pthread_t mt;
  16821. if (!ctx) {
  16822. return;
  16823. }
  16824. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16825. * two threads is not allowed. */
  16826. mt = ctx->masterthreadid;
  16827. if (mt == 0) {
  16828. return;
  16829. }
  16830. ctx->masterthreadid = 0;
  16831. /* Set stop flag, so all threads know they have to exit. */
  16832. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16833. /* Join timer thread */
  16834. #if defined(USE_TIMERS)
  16835. timers_exit(ctx);
  16836. #endif
  16837. /* Wait until everything has stopped. */
  16838. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16839. (void)mg_sleep(10);
  16840. }
  16841. /* Wait to stop master thread */
  16842. mg_join_thread(mt);
  16843. /* Close remaining Lua states */
  16844. #if defined(USE_LUA)
  16845. lua_ctx_exit(ctx);
  16846. #endif
  16847. /* Free memory */
  16848. free_context(ctx);
  16849. }
  16850. static void
  16851. get_system_name(char **sysName)
  16852. {
  16853. #if defined(_WIN32)
  16854. char name[128];
  16855. DWORD dwVersion = 0;
  16856. DWORD dwMajorVersion = 0;
  16857. DWORD dwMinorVersion = 0;
  16858. DWORD dwBuild = 0;
  16859. BOOL wowRet, isWoW = FALSE;
  16860. #if defined(_MSC_VER)
  16861. #pragma warning(push)
  16862. /* GetVersion was declared deprecated */
  16863. #pragma warning(disable : 4996)
  16864. #endif
  16865. dwVersion = GetVersion();
  16866. #if defined(_MSC_VER)
  16867. #pragma warning(pop)
  16868. #endif
  16869. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16870. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16871. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16872. (void)dwBuild;
  16873. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16874. sprintf(name,
  16875. "Windows %u.%u%s",
  16876. (unsigned)dwMajorVersion,
  16877. (unsigned)dwMinorVersion,
  16878. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16879. *sysName = mg_strdup(name);
  16880. #elif defined(__ZEPHYR__)
  16881. *sysName = mg_strdup("Zephyr OS");
  16882. #else
  16883. struct utsname name;
  16884. memset(&name, 0, sizeof(name));
  16885. uname(&name);
  16886. *sysName = mg_strdup(name.sysname);
  16887. #endif
  16888. }
  16889. static void
  16890. legacy_init(const char **options)
  16891. {
  16892. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16893. if (options) {
  16894. const char **run_options = options;
  16895. const char *optname = config_options[LISTENING_PORTS].name;
  16896. /* Try to find the "listening_ports" option */
  16897. while (*run_options) {
  16898. if (!strcmp(*run_options, optname)) {
  16899. ports_option = run_options[1];
  16900. }
  16901. run_options += 2;
  16902. }
  16903. }
  16904. if (is_ssl_port_used(ports_option)) {
  16905. /* Initialize with SSL support */
  16906. mg_init_library(MG_FEATURES_TLS);
  16907. } else {
  16908. /* Initialize without SSL support */
  16909. mg_init_library(MG_FEATURES_DEFAULT);
  16910. }
  16911. }
  16912. struct mg_context *
  16913. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16914. {
  16915. struct mg_context *ctx;
  16916. const char *name, *value, *default_value;
  16917. int idx, ok, workerthreadcount;
  16918. unsigned int i;
  16919. int itmp;
  16920. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16921. const char **options =
  16922. ((init != NULL) ? (init->configuration_options) : (NULL));
  16923. struct mg_workerTLS tls;
  16924. if (error != NULL) {
  16925. error->code = 0;
  16926. if (error->text_buffer_size > 0) {
  16927. *error->text = 0;
  16928. }
  16929. }
  16930. if (mg_init_library_called == 0) {
  16931. /* Legacy INIT, if mg_start is called without mg_init_library.
  16932. * Note: This will cause a memory leak when unloading the library.
  16933. */
  16934. legacy_init(options);
  16935. }
  16936. if (mg_init_library_called == 0) {
  16937. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16938. mg_snprintf(NULL,
  16939. NULL, /* No truncation check for error buffers */
  16940. error->text,
  16941. error->text_buffer_size,
  16942. "%s",
  16943. "Library uninitialized");
  16944. }
  16945. return NULL;
  16946. }
  16947. /* Allocate context and initialize reasonable general case defaults. */
  16948. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16949. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16950. mg_snprintf(NULL,
  16951. NULL, /* No truncation check for error buffers */
  16952. error->text,
  16953. error->text_buffer_size,
  16954. "%s",
  16955. "Out of memory");
  16956. }
  16957. return NULL;
  16958. }
  16959. /* Random number generator will initialize at the first call */
  16960. ctx->dd.auth_nonce_mask =
  16961. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16962. /* Save started thread index to reuse in other external API calls
  16963. * For the sake of thread synchronization all non-civetweb threads
  16964. * can be considered as single external thread */
  16965. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16966. tls.is_master = -1; /* Thread calling mg_start */
  16967. tls.thread_idx = ctx->starter_thread_idx;
  16968. #if defined(_WIN32)
  16969. tls.pthread_cond_helper_mutex = NULL;
  16970. #endif
  16971. pthread_setspecific(sTlsKey, &tls);
  16972. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16973. #if !defined(ALTERNATIVE_QUEUE)
  16974. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16975. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16976. ctx->sq_blocked = 0;
  16977. #endif
  16978. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16979. #if defined(USE_LUA)
  16980. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  16981. #endif
  16982. if (!ok) {
  16983. const char *err_msg =
  16984. "Cannot initialize thread synchronization objects";
  16985. /* Fatal error - abort start. However, this situation should never
  16986. * occur in practice. */
  16987. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16988. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16989. mg_snprintf(NULL,
  16990. NULL, /* No truncation check for error buffers */
  16991. error->text,
  16992. error->text_buffer_size,
  16993. "%s",
  16994. err_msg);
  16995. }
  16996. mg_free(ctx);
  16997. pthread_setspecific(sTlsKey, NULL);
  16998. return NULL;
  16999. }
  17000. if ((init != NULL) && (init->callbacks != NULL)) {
  17001. /* Set all callbacks except exit_context. */
  17002. ctx->callbacks = *init->callbacks;
  17003. exit_callback = init->callbacks->exit_context;
  17004. /* The exit callback is activated once the context is successfully
  17005. * created. It should not be called, if an incomplete context object
  17006. * is deleted during a failed initialization. */
  17007. ctx->callbacks.exit_context = 0;
  17008. }
  17009. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17010. ctx->dd.handlers = NULL;
  17011. ctx->dd.next = NULL;
  17012. #if defined(USE_LUA)
  17013. lua_ctx_init(ctx);
  17014. #endif
  17015. /* Store options */
  17016. while (options && (name = *options++) != NULL) {
  17017. if ((idx = get_option_index(name)) == -1) {
  17018. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17019. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17020. mg_snprintf(NULL,
  17021. NULL, /* No truncation check for error buffers */
  17022. error->text,
  17023. error->text_buffer_size,
  17024. "Invalid configuration option: %s",
  17025. name);
  17026. }
  17027. free_context(ctx);
  17028. pthread_setspecific(sTlsKey, NULL);
  17029. return NULL;
  17030. } else if ((value = *options++) == NULL) {
  17031. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17032. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17033. mg_snprintf(NULL,
  17034. NULL, /* No truncation check for error buffers */
  17035. error->text,
  17036. error->text_buffer_size,
  17037. "Invalid configuration option value: %s",
  17038. name);
  17039. }
  17040. free_context(ctx);
  17041. pthread_setspecific(sTlsKey, NULL);
  17042. return NULL;
  17043. }
  17044. if (ctx->dd.config[idx] != NULL) {
  17045. /* A duplicate configuration option is not an error - the last
  17046. * option value will be used. */
  17047. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17048. mg_free(ctx->dd.config[idx]);
  17049. }
  17050. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17051. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17052. }
  17053. /* Set default value if needed */
  17054. for (i = 0; config_options[i].name != NULL; i++) {
  17055. default_value = config_options[i].default_value;
  17056. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17057. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17058. }
  17059. }
  17060. /* Request size option */
  17061. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17062. if (itmp < 1024) {
  17063. mg_cry_ctx_internal(ctx,
  17064. "%s too small",
  17065. config_options[MAX_REQUEST_SIZE].name);
  17066. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17067. mg_snprintf(NULL,
  17068. NULL, /* No truncation check for error buffers */
  17069. error->text,
  17070. error->text_buffer_size,
  17071. "Invalid configuration option value: %s",
  17072. config_options[MAX_REQUEST_SIZE].name);
  17073. }
  17074. free_context(ctx);
  17075. pthread_setspecific(sTlsKey, NULL);
  17076. return NULL;
  17077. }
  17078. ctx->max_request_size = (unsigned)itmp;
  17079. /* Queue length */
  17080. #if !defined(ALTERNATIVE_QUEUE)
  17081. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17082. if (itmp < 1) {
  17083. mg_cry_ctx_internal(ctx,
  17084. "%s too small",
  17085. config_options[CONNECTION_QUEUE_SIZE].name);
  17086. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17087. mg_snprintf(NULL,
  17088. NULL, /* No truncation check for error buffers */
  17089. error->text,
  17090. error->text_buffer_size,
  17091. "Invalid configuration option value: %s",
  17092. config_options[CONNECTION_QUEUE_SIZE].name);
  17093. }
  17094. free_context(ctx);
  17095. pthread_setspecific(sTlsKey, NULL);
  17096. return NULL;
  17097. }
  17098. ctx->squeue =
  17099. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17100. if (ctx->squeue == NULL) {
  17101. mg_cry_ctx_internal(ctx,
  17102. "Out of memory: Cannot allocate %s",
  17103. config_options[CONNECTION_QUEUE_SIZE].name);
  17104. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17105. mg_snprintf(NULL,
  17106. NULL, /* No truncation check for error buffers */
  17107. error->text,
  17108. error->text_buffer_size,
  17109. "Out of memory: Cannot allocate %s",
  17110. config_options[CONNECTION_QUEUE_SIZE].name);
  17111. }
  17112. free_context(ctx);
  17113. pthread_setspecific(sTlsKey, NULL);
  17114. return NULL;
  17115. }
  17116. ctx->sq_size = itmp;
  17117. #endif
  17118. /* Worker thread count option */
  17119. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17120. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17121. if (workerthreadcount <= 0) {
  17122. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17123. } else {
  17124. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17125. }
  17126. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17127. mg_snprintf(NULL,
  17128. NULL, /* No truncation check for error buffers */
  17129. error->text,
  17130. error->text_buffer_size,
  17131. "Invalid configuration option value: %s",
  17132. config_options[NUM_THREADS].name);
  17133. }
  17134. free_context(ctx);
  17135. pthread_setspecific(sTlsKey, NULL);
  17136. return NULL;
  17137. }
  17138. /* Document root */
  17139. #if defined(NO_FILES)
  17140. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17141. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17142. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17143. mg_snprintf(NULL,
  17144. NULL, /* No truncation check for error buffers */
  17145. error->text,
  17146. error->text_buffer_size,
  17147. "Invalid configuration option value: %s",
  17148. config_options[DOCUMENT_ROOT].name);
  17149. }
  17150. free_context(ctx);
  17151. pthread_setspecific(sTlsKey, NULL);
  17152. return NULL;
  17153. }
  17154. #endif
  17155. get_system_name(&ctx->systemName);
  17156. #if defined(USE_LUA)
  17157. /* If a Lua background script has been configured, start it. */
  17158. ctx->lua_bg_log_available = 0;
  17159. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17160. char ebuf[256];
  17161. struct vec opt_vec;
  17162. struct vec eq_vec;
  17163. const char *sparams;
  17164. memset(ebuf, 0, sizeof(ebuf));
  17165. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17166. /* Create a Lua state, load all standard libraries and the mg table */
  17167. lua_State *state = mg_lua_context_script_prepare(
  17168. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17169. if (!state) {
  17170. mg_cry_ctx_internal(ctx,
  17171. "lua_background_script load error: %s",
  17172. ebuf);
  17173. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17174. mg_snprintf(NULL,
  17175. NULL, /* No truncation check for error buffers */
  17176. error->text,
  17177. error->text_buffer_size,
  17178. "Error in script %s: %s",
  17179. config_options[LUA_BACKGROUND_SCRIPT].name,
  17180. ebuf);
  17181. }
  17182. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17183. free_context(ctx);
  17184. pthread_setspecific(sTlsKey, NULL);
  17185. return NULL;
  17186. }
  17187. /* Add a table with parameters into mg.params */
  17188. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17189. if (sparams && sparams[0]) {
  17190. lua_getglobal(state, "mg");
  17191. lua_pushstring(state, "params");
  17192. lua_newtable(state);
  17193. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17194. != NULL) {
  17195. reg_llstring(
  17196. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17197. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17198. break;
  17199. }
  17200. lua_rawset(state, -3);
  17201. lua_pop(state, 1);
  17202. }
  17203. /* Call script */
  17204. state = mg_lua_context_script_run(state,
  17205. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17206. ctx,
  17207. ebuf,
  17208. sizeof(ebuf));
  17209. if (!state) {
  17210. mg_cry_ctx_internal(ctx,
  17211. "lua_background_script start error: %s",
  17212. ebuf);
  17213. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17214. mg_snprintf(NULL,
  17215. NULL, /* No truncation check for error buffers */
  17216. error->text,
  17217. error->text_buffer_size,
  17218. "Error in script %s: %s",
  17219. config_options[DOCUMENT_ROOT].name,
  17220. ebuf);
  17221. }
  17222. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17223. free_context(ctx);
  17224. pthread_setspecific(sTlsKey, NULL);
  17225. return NULL;
  17226. }
  17227. /* state remains valid */
  17228. ctx->lua_background_state = (void *)state;
  17229. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17230. } else {
  17231. ctx->lua_background_state = 0;
  17232. }
  17233. #endif
  17234. /* Step by step initialization of ctx - depending on build options */
  17235. #if !defined(NO_FILESYSTEMS)
  17236. if (!set_gpass_option(ctx, NULL)) {
  17237. const char *err_msg = "Invalid global password file";
  17238. /* Fatal error - abort start. */
  17239. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17240. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17241. mg_snprintf(NULL,
  17242. NULL, /* No truncation check for error buffers */
  17243. error->text,
  17244. error->text_buffer_size,
  17245. "%s",
  17246. err_msg);
  17247. }
  17248. free_context(ctx);
  17249. pthread_setspecific(sTlsKey, NULL);
  17250. return NULL;
  17251. }
  17252. #endif
  17253. #if defined(USE_MBEDTLS)
  17254. if (!mg_sslctx_init(ctx, NULL)) {
  17255. const char *err_msg = "Error initializing SSL context";
  17256. /* Fatal error - abort start. */
  17257. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17258. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17259. mg_snprintf(NULL,
  17260. NULL, /* No truncation check for error buffers */
  17261. error->text,
  17262. error->text_buffer_size,
  17263. "%s",
  17264. err_msg);
  17265. }
  17266. free_context(ctx);
  17267. pthread_setspecific(sTlsKey, NULL);
  17268. return NULL;
  17269. }
  17270. #elif !defined(NO_SSL)
  17271. if (!init_ssl_ctx(ctx, NULL)) {
  17272. const char *err_msg = "Error initializing SSL context";
  17273. /* Fatal error - abort start. */
  17274. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17275. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17276. mg_snprintf(NULL,
  17277. NULL, /* No truncation check for error buffers */
  17278. error->text,
  17279. error->text_buffer_size,
  17280. "%s",
  17281. err_msg);
  17282. }
  17283. free_context(ctx);
  17284. pthread_setspecific(sTlsKey, NULL);
  17285. return NULL;
  17286. }
  17287. #endif
  17288. if (!set_ports_option(ctx)) {
  17289. const char *err_msg = "Failed to setup server ports";
  17290. /* Fatal error - abort start. */
  17291. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17292. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17293. mg_snprintf(NULL,
  17294. NULL, /* No truncation check for error buffers */
  17295. error->text,
  17296. error->text_buffer_size,
  17297. "%s",
  17298. err_msg);
  17299. }
  17300. free_context(ctx);
  17301. pthread_setspecific(sTlsKey, NULL);
  17302. return NULL;
  17303. }
  17304. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17305. if (!set_uid_option(ctx)) {
  17306. const char *err_msg = "Failed to run as configured user";
  17307. /* Fatal error - abort start. */
  17308. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17309. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17310. mg_snprintf(NULL,
  17311. NULL, /* No truncation check for error buffers */
  17312. error->text,
  17313. error->text_buffer_size,
  17314. "%s",
  17315. err_msg);
  17316. }
  17317. free_context(ctx);
  17318. pthread_setspecific(sTlsKey, NULL);
  17319. return NULL;
  17320. }
  17321. #endif
  17322. if (!set_acl_option(ctx)) {
  17323. const char *err_msg = "Failed to setup access control list";
  17324. /* Fatal error - abort start. */
  17325. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17326. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17327. mg_snprintf(NULL,
  17328. NULL, /* No truncation check for error buffers */
  17329. error->text,
  17330. error->text_buffer_size,
  17331. "%s",
  17332. err_msg);
  17333. }
  17334. free_context(ctx);
  17335. pthread_setspecific(sTlsKey, NULL);
  17336. return NULL;
  17337. }
  17338. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17339. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17340. sizeof(pthread_t),
  17341. ctx);
  17342. if (ctx->worker_threadids == NULL) {
  17343. const char *err_msg = "Not enough memory for worker thread ID array";
  17344. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17345. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17346. mg_snprintf(NULL,
  17347. NULL, /* No truncation check for error buffers */
  17348. error->text,
  17349. error->text_buffer_size,
  17350. "%s",
  17351. err_msg);
  17352. }
  17353. free_context(ctx);
  17354. pthread_setspecific(sTlsKey, NULL);
  17355. return NULL;
  17356. }
  17357. ctx->worker_connections =
  17358. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17359. sizeof(struct mg_connection),
  17360. ctx);
  17361. if (ctx->worker_connections == NULL) {
  17362. const char *err_msg =
  17363. "Not enough memory for worker thread connection array";
  17364. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17365. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17366. mg_snprintf(NULL,
  17367. NULL, /* No truncation check for error buffers */
  17368. error->text,
  17369. error->text_buffer_size,
  17370. "%s",
  17371. err_msg);
  17372. }
  17373. free_context(ctx);
  17374. pthread_setspecific(sTlsKey, NULL);
  17375. return NULL;
  17376. }
  17377. #if defined(ALTERNATIVE_QUEUE)
  17378. ctx->client_wait_events =
  17379. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17380. sizeof(ctx->client_wait_events[0]),
  17381. ctx);
  17382. if (ctx->client_wait_events == NULL) {
  17383. const char *err_msg = "Not enough memory for worker event array";
  17384. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17385. mg_free(ctx->worker_threadids);
  17386. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17387. mg_snprintf(NULL,
  17388. NULL, /* No truncation check for error buffers */
  17389. error->text,
  17390. error->text_buffer_size,
  17391. "%s",
  17392. err_msg);
  17393. }
  17394. free_context(ctx);
  17395. pthread_setspecific(sTlsKey, NULL);
  17396. return NULL;
  17397. }
  17398. ctx->client_socks =
  17399. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17400. sizeof(ctx->client_socks[0]),
  17401. ctx);
  17402. if (ctx->client_socks == NULL) {
  17403. const char *err_msg = "Not enough memory for worker socket array";
  17404. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17405. mg_free(ctx->client_wait_events);
  17406. mg_free(ctx->worker_threadids);
  17407. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17408. mg_snprintf(NULL,
  17409. NULL, /* No truncation check for error buffers */
  17410. error->text,
  17411. error->text_buffer_size,
  17412. "%s",
  17413. err_msg);
  17414. }
  17415. free_context(ctx);
  17416. pthread_setspecific(sTlsKey, NULL);
  17417. return NULL;
  17418. }
  17419. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17420. ctx->client_wait_events[i] = event_create();
  17421. if (ctx->client_wait_events[i] == 0) {
  17422. const char *err_msg = "Error creating worker event %i";
  17423. mg_cry_ctx_internal(ctx, err_msg, i);
  17424. while (i > 0) {
  17425. i--;
  17426. event_destroy(ctx->client_wait_events[i]);
  17427. }
  17428. mg_free(ctx->client_socks);
  17429. mg_free(ctx->client_wait_events);
  17430. mg_free(ctx->worker_threadids);
  17431. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17432. mg_snprintf(NULL,
  17433. NULL, /* No truncation check for error buffers */
  17434. error->text,
  17435. error->text_buffer_size,
  17436. err_msg,
  17437. i);
  17438. }
  17439. free_context(ctx);
  17440. pthread_setspecific(sTlsKey, NULL);
  17441. return NULL;
  17442. }
  17443. }
  17444. #endif
  17445. #if defined(USE_TIMERS)
  17446. if (timers_init(ctx) != 0) {
  17447. const char *err_msg = "Error creating timers";
  17448. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17449. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17450. mg_snprintf(NULL,
  17451. NULL, /* No truncation check for error buffers */
  17452. error->text,
  17453. error->text_buffer_size,
  17454. "%s",
  17455. err_msg);
  17456. }
  17457. free_context(ctx);
  17458. pthread_setspecific(sTlsKey, NULL);
  17459. return NULL;
  17460. }
  17461. #endif
  17462. /* Context has been created - init user libraries */
  17463. if (ctx->callbacks.init_context) {
  17464. ctx->callbacks.init_context(ctx);
  17465. }
  17466. /* From now, the context is successfully created.
  17467. * When it is destroyed, the exit callback should be called. */
  17468. ctx->callbacks.exit_context = exit_callback;
  17469. ctx->context_type = CONTEXT_SERVER; /* server context */
  17470. /* Start worker threads */
  17471. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17472. /* worker_thread sets up the other fields */
  17473. ctx->worker_connections[i].phys_ctx = ctx;
  17474. if (mg_start_thread_with_id(worker_thread,
  17475. &ctx->worker_connections[i],
  17476. &ctx->worker_threadids[i])
  17477. != 0) {
  17478. long error_no = (long)ERRNO;
  17479. /* thread was not created */
  17480. if (i > 0) {
  17481. /* If the second, third, ... thread cannot be created, set a
  17482. * warning, but keep running. */
  17483. mg_cry_ctx_internal(ctx,
  17484. "Cannot start worker thread %i: error %ld",
  17485. i + 1,
  17486. error_no);
  17487. /* If the server initialization should stop here, all
  17488. * threads that have already been created must be stopped
  17489. * first, before any free_context(ctx) call.
  17490. */
  17491. } else {
  17492. /* If the first worker thread cannot be created, stop
  17493. * initialization and free the entire server context. */
  17494. mg_cry_ctx_internal(ctx,
  17495. "Cannot create threads: error %ld",
  17496. error_no);
  17497. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17498. mg_snprintf(
  17499. NULL,
  17500. NULL, /* No truncation check for error buffers */
  17501. error->text,
  17502. error->text_buffer_size,
  17503. "Cannot create first worker thread: error %ld",
  17504. error_no);
  17505. }
  17506. free_context(ctx);
  17507. pthread_setspecific(sTlsKey, NULL);
  17508. return NULL;
  17509. }
  17510. break;
  17511. }
  17512. }
  17513. /* Start master (listening) thread */
  17514. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17515. pthread_setspecific(sTlsKey, NULL);
  17516. return ctx;
  17517. }
  17518. struct mg_context *
  17519. mg_start(const struct mg_callbacks *callbacks,
  17520. void *user_data,
  17521. const char **options)
  17522. {
  17523. struct mg_init_data init = {0};
  17524. init.callbacks = callbacks;
  17525. init.user_data = user_data;
  17526. init.configuration_options = options;
  17527. return mg_start2(&init, NULL);
  17528. }
  17529. /* Add an additional domain to an already running web server. */
  17530. int
  17531. mg_start_domain2(struct mg_context *ctx,
  17532. const char **options,
  17533. struct mg_error_data *error)
  17534. {
  17535. const char *name;
  17536. const char *value;
  17537. const char *default_value;
  17538. struct mg_domain_context *new_dom;
  17539. struct mg_domain_context *dom;
  17540. int idx, i;
  17541. if (error != NULL) {
  17542. error->code = 0;
  17543. if (error->text_buffer_size > 0) {
  17544. *error->text = 0;
  17545. }
  17546. }
  17547. if ((ctx == NULL) || (options == NULL)) {
  17548. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17549. mg_snprintf(NULL,
  17550. NULL, /* No truncation check for error buffers */
  17551. error->text,
  17552. error->text_buffer_size,
  17553. "%s",
  17554. "Invalid parameters");
  17555. }
  17556. return -1;
  17557. }
  17558. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17559. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17560. mg_snprintf(NULL,
  17561. NULL, /* No truncation check for error buffers */
  17562. error->text,
  17563. error->text_buffer_size,
  17564. "%s",
  17565. "Server already stopped");
  17566. }
  17567. return -1;
  17568. }
  17569. new_dom = (struct mg_domain_context *)
  17570. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17571. if (!new_dom) {
  17572. /* Out of memory */
  17573. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17574. mg_snprintf(NULL,
  17575. NULL, /* No truncation check for error buffers */
  17576. error->text,
  17577. error->text_buffer_size,
  17578. "%s",
  17579. "Out or memory");
  17580. }
  17581. return -6;
  17582. }
  17583. /* Store options - TODO: unite duplicate code */
  17584. while (options && (name = *options++) != NULL) {
  17585. if ((idx = get_option_index(name)) == -1) {
  17586. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17587. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17588. mg_snprintf(NULL,
  17589. NULL, /* No truncation check for error buffers */
  17590. error->text,
  17591. error->text_buffer_size,
  17592. "Invalid option: %s",
  17593. name);
  17594. }
  17595. mg_free(new_dom);
  17596. return -2;
  17597. } else if ((value = *options++) == NULL) {
  17598. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17599. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17600. mg_snprintf(NULL,
  17601. NULL, /* No truncation check for error buffers */
  17602. error->text,
  17603. error->text_buffer_size,
  17604. "Invalid option value: %s",
  17605. name);
  17606. }
  17607. mg_free(new_dom);
  17608. return -2;
  17609. }
  17610. if (new_dom->config[idx] != NULL) {
  17611. /* Duplicate option: Later values overwrite earlier ones. */
  17612. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17613. mg_free(new_dom->config[idx]);
  17614. }
  17615. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17616. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17617. }
  17618. /* Authentication domain is mandatory */
  17619. /* TODO: Maybe use a new option hostname? */
  17620. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17621. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17622. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17623. mg_snprintf(NULL,
  17624. NULL, /* No truncation check for error buffers */
  17625. error->text,
  17626. error->text_buffer_size,
  17627. "Mandatory option %s missing",
  17628. config_options[AUTHENTICATION_DOMAIN].name);
  17629. }
  17630. mg_free(new_dom);
  17631. return -4;
  17632. }
  17633. /* Set default value if needed. Take the config value from
  17634. * ctx as a default value. */
  17635. for (i = 0; config_options[i].name != NULL; i++) {
  17636. default_value = ctx->dd.config[i];
  17637. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17638. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17639. }
  17640. }
  17641. new_dom->handlers = NULL;
  17642. new_dom->next = NULL;
  17643. new_dom->nonce_count = 0;
  17644. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  17645. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17646. new_dom->shared_lua_websockets = NULL;
  17647. #endif
  17648. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  17649. if (!init_ssl_ctx(ctx, new_dom)) {
  17650. /* Init SSL failed */
  17651. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17652. mg_snprintf(NULL,
  17653. NULL, /* No truncation check for error buffers */
  17654. error->text,
  17655. error->text_buffer_size,
  17656. "%s",
  17657. "Initializing SSL context failed");
  17658. }
  17659. mg_free(new_dom);
  17660. return -3;
  17661. }
  17662. #endif
  17663. /* Add element to linked list. */
  17664. mg_lock_context(ctx);
  17665. idx = 0;
  17666. dom = &(ctx->dd);
  17667. for (;;) {
  17668. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17669. dom->config[AUTHENTICATION_DOMAIN])) {
  17670. /* Domain collision */
  17671. mg_cry_ctx_internal(ctx,
  17672. "domain %s already in use",
  17673. new_dom->config[AUTHENTICATION_DOMAIN]);
  17674. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17675. mg_snprintf(NULL,
  17676. NULL, /* No truncation check for error buffers */
  17677. error->text,
  17678. error->text_buffer_size,
  17679. "Domain %s specified by %s is already in use",
  17680. new_dom->config[AUTHENTICATION_DOMAIN],
  17681. config_options[AUTHENTICATION_DOMAIN].name);
  17682. }
  17683. mg_free(new_dom);
  17684. mg_unlock_context(ctx);
  17685. return -5;
  17686. }
  17687. /* Count number of domains */
  17688. idx++;
  17689. if (dom->next == NULL) {
  17690. dom->next = new_dom;
  17691. break;
  17692. }
  17693. dom = dom->next;
  17694. }
  17695. mg_unlock_context(ctx);
  17696. /* Return domain number */
  17697. return idx;
  17698. }
  17699. int
  17700. mg_start_domain(struct mg_context *ctx, const char **options)
  17701. {
  17702. return mg_start_domain2(ctx, options, NULL);
  17703. }
  17704. /* Feature check API function */
  17705. unsigned
  17706. mg_check_feature(unsigned feature)
  17707. {
  17708. static const unsigned feature_set = 0
  17709. /* Set bits for available features according to API documentation.
  17710. * This bit mask is created at compile time, according to the active
  17711. * preprocessor defines. It is a single const value at runtime. */
  17712. #if !defined(NO_FILES)
  17713. | MG_FEATURES_FILES
  17714. #endif
  17715. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17716. | MG_FEATURES_SSL
  17717. #endif
  17718. #if !defined(NO_CGI)
  17719. | MG_FEATURES_CGI
  17720. #endif
  17721. #if defined(USE_IPV6)
  17722. | MG_FEATURES_IPV6
  17723. #endif
  17724. #if defined(USE_WEBSOCKET)
  17725. | MG_FEATURES_WEBSOCKET
  17726. #endif
  17727. #if defined(USE_LUA)
  17728. | MG_FEATURES_LUA
  17729. #endif
  17730. #if defined(USE_DUKTAPE)
  17731. | MG_FEATURES_SSJS
  17732. #endif
  17733. #if !defined(NO_CACHING)
  17734. | MG_FEATURES_CACHE
  17735. #endif
  17736. #if defined(USE_SERVER_STATS)
  17737. | MG_FEATURES_STATS
  17738. #endif
  17739. #if defined(USE_ZLIB)
  17740. | MG_FEATURES_COMPRESSION
  17741. #endif
  17742. #if defined(USE_HTTP2)
  17743. | MG_FEATURES_HTTP2
  17744. #endif
  17745. #if defined(USE_X_DOM_SOCKET)
  17746. | MG_FEATURES_X_DOMAIN_SOCKET
  17747. #endif
  17748. /* Set some extra bits not defined in the API documentation.
  17749. * These bits may change without further notice. */
  17750. #if defined(MG_LEGACY_INTERFACE)
  17751. | 0x80000000u
  17752. #endif
  17753. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17754. | 0x40000000u
  17755. #endif
  17756. #if !defined(NO_RESPONSE_BUFFERING)
  17757. | 0x20000000u
  17758. #endif
  17759. #if defined(MEMORY_DEBUGGING)
  17760. | 0x10000000u
  17761. #endif
  17762. ;
  17763. return (feature & feature_set);
  17764. }
  17765. static size_t
  17766. mg_str_append(char **dst, char *end, const char *src)
  17767. {
  17768. size_t len = strlen(src);
  17769. if (*dst != end) {
  17770. /* Append src if enough space, or close dst. */
  17771. if ((size_t)(end - *dst) > len) {
  17772. strcpy(*dst, src);
  17773. *dst += len;
  17774. } else {
  17775. *dst = end;
  17776. }
  17777. }
  17778. return len;
  17779. }
  17780. /* Get system information. It can be printed or stored by the caller.
  17781. * Return the size of available information. */
  17782. int
  17783. mg_get_system_info(char *buffer, int buflen)
  17784. {
  17785. char *end, *append_eoobj = NULL, block[256];
  17786. size_t system_info_length = 0;
  17787. #if defined(_WIN32)
  17788. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17789. #else
  17790. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17791. #endif
  17792. if ((buffer == NULL) || (buflen < 1)) {
  17793. buflen = 0;
  17794. end = buffer;
  17795. } else {
  17796. *buffer = 0;
  17797. end = buffer + buflen;
  17798. }
  17799. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17800. /* has enough space to append eoobj */
  17801. append_eoobj = buffer;
  17802. if (end) {
  17803. end -= sizeof(eoobj) - 1;
  17804. }
  17805. }
  17806. system_info_length += mg_str_append(&buffer, end, "{");
  17807. /* Server version */
  17808. {
  17809. const char *version = mg_version();
  17810. mg_snprintf(NULL,
  17811. NULL,
  17812. block,
  17813. sizeof(block),
  17814. "%s\"version\" : \"%s\"",
  17815. eol,
  17816. version);
  17817. system_info_length += mg_str_append(&buffer, end, block);
  17818. }
  17819. /* System info */
  17820. {
  17821. #if defined(_WIN32)
  17822. DWORD dwVersion = 0;
  17823. DWORD dwMajorVersion = 0;
  17824. DWORD dwMinorVersion = 0;
  17825. SYSTEM_INFO si;
  17826. GetSystemInfo(&si);
  17827. #if defined(_MSC_VER)
  17828. #pragma warning(push)
  17829. /* GetVersion was declared deprecated */
  17830. #pragma warning(disable : 4996)
  17831. #endif
  17832. dwVersion = GetVersion();
  17833. #if defined(_MSC_VER)
  17834. #pragma warning(pop)
  17835. #endif
  17836. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17837. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17838. mg_snprintf(NULL,
  17839. NULL,
  17840. block,
  17841. sizeof(block),
  17842. ",%s\"os\" : \"Windows %u.%u\"",
  17843. eol,
  17844. (unsigned)dwMajorVersion,
  17845. (unsigned)dwMinorVersion);
  17846. system_info_length += mg_str_append(&buffer, end, block);
  17847. mg_snprintf(NULL,
  17848. NULL,
  17849. block,
  17850. sizeof(block),
  17851. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17852. eol,
  17853. (unsigned)si.wProcessorArchitecture,
  17854. (unsigned)si.dwNumberOfProcessors,
  17855. (unsigned)si.dwActiveProcessorMask);
  17856. system_info_length += mg_str_append(&buffer, end, block);
  17857. #elif defined(__ZEPHYR__)
  17858. mg_snprintf(NULL,
  17859. NULL,
  17860. block,
  17861. sizeof(block),
  17862. ",%s\"os\" : \"%s %s\"",
  17863. eol,
  17864. "Zephyr OS",
  17865. ZEPHYR_VERSION);
  17866. system_info_length += mg_str_append(&buffer, end, block);
  17867. #else
  17868. struct utsname name;
  17869. memset(&name, 0, sizeof(name));
  17870. uname(&name);
  17871. mg_snprintf(NULL,
  17872. NULL,
  17873. block,
  17874. sizeof(block),
  17875. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17876. eol,
  17877. name.sysname,
  17878. name.version,
  17879. name.release,
  17880. name.machine);
  17881. system_info_length += mg_str_append(&buffer, end, block);
  17882. #endif
  17883. }
  17884. /* Features */
  17885. {
  17886. mg_snprintf(NULL,
  17887. NULL,
  17888. block,
  17889. sizeof(block),
  17890. ",%s\"features\" : %lu"
  17891. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17892. eol,
  17893. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17894. eol,
  17895. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17896. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17897. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17898. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17899. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17900. : "",
  17901. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17902. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17903. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17904. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17905. system_info_length += mg_str_append(&buffer, end, block);
  17906. #if defined(USE_LUA)
  17907. mg_snprintf(NULL,
  17908. NULL,
  17909. block,
  17910. sizeof(block),
  17911. ",%s\"lua_version\" : \"%u (%s)\"",
  17912. eol,
  17913. (unsigned)LUA_VERSION_NUM,
  17914. LUA_RELEASE);
  17915. system_info_length += mg_str_append(&buffer, end, block);
  17916. #endif
  17917. #if defined(USE_DUKTAPE)
  17918. mg_snprintf(NULL,
  17919. NULL,
  17920. block,
  17921. sizeof(block),
  17922. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17923. eol,
  17924. (unsigned)DUK_VERSION / 10000,
  17925. ((unsigned)DUK_VERSION / 100) % 100,
  17926. (unsigned)DUK_VERSION % 100);
  17927. system_info_length += mg_str_append(&buffer, end, block);
  17928. #endif
  17929. }
  17930. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  17931. {
  17932. #if defined(BUILD_DATE)
  17933. const char *bd = BUILD_DATE;
  17934. #else
  17935. #if defined(GCC_DIAGNOSTIC)
  17936. #if GCC_VERSION >= 40900
  17937. #pragma GCC diagnostic push
  17938. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  17939. * does not work in some versions. If "BUILD_DATE" is defined to some
  17940. * string, it is used instead of __DATE__. */
  17941. #pragma GCC diagnostic ignored "-Wdate-time"
  17942. #endif
  17943. #endif
  17944. const char *bd = __DATE__;
  17945. #if defined(GCC_DIAGNOSTIC)
  17946. #if GCC_VERSION >= 40900
  17947. #pragma GCC diagnostic pop
  17948. #endif
  17949. #endif
  17950. #endif
  17951. mg_snprintf(
  17952. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17953. system_info_length += mg_str_append(&buffer, end, block);
  17954. }
  17955. /* Compiler information */
  17956. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17957. {
  17958. #if defined(_MSC_VER)
  17959. mg_snprintf(NULL,
  17960. NULL,
  17961. block,
  17962. sizeof(block),
  17963. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17964. eol,
  17965. (unsigned)_MSC_VER,
  17966. (unsigned)_MSC_FULL_VER);
  17967. system_info_length += mg_str_append(&buffer, end, block);
  17968. #elif defined(__MINGW64__)
  17969. mg_snprintf(NULL,
  17970. NULL,
  17971. block,
  17972. sizeof(block),
  17973. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17974. eol,
  17975. (unsigned)__MINGW64_VERSION_MAJOR,
  17976. (unsigned)__MINGW64_VERSION_MINOR);
  17977. system_info_length += mg_str_append(&buffer, end, block);
  17978. mg_snprintf(NULL,
  17979. NULL,
  17980. block,
  17981. sizeof(block),
  17982. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17983. eol,
  17984. (unsigned)__MINGW32_MAJOR_VERSION,
  17985. (unsigned)__MINGW32_MINOR_VERSION);
  17986. system_info_length += mg_str_append(&buffer, end, block);
  17987. #elif defined(__MINGW32__)
  17988. mg_snprintf(NULL,
  17989. NULL,
  17990. block,
  17991. sizeof(block),
  17992. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17993. eol,
  17994. (unsigned)__MINGW32_MAJOR_VERSION,
  17995. (unsigned)__MINGW32_MINOR_VERSION);
  17996. system_info_length += mg_str_append(&buffer, end, block);
  17997. #elif defined(__clang__)
  17998. mg_snprintf(NULL,
  17999. NULL,
  18000. block,
  18001. sizeof(block),
  18002. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18003. eol,
  18004. __clang_major__,
  18005. __clang_minor__,
  18006. __clang_patchlevel__,
  18007. __clang_version__);
  18008. system_info_length += mg_str_append(&buffer, end, block);
  18009. #elif defined(__GNUC__)
  18010. mg_snprintf(NULL,
  18011. NULL,
  18012. block,
  18013. sizeof(block),
  18014. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18015. eol,
  18016. (unsigned)__GNUC__,
  18017. (unsigned)__GNUC_MINOR__,
  18018. (unsigned)__GNUC_PATCHLEVEL__);
  18019. system_info_length += mg_str_append(&buffer, end, block);
  18020. #elif defined(__INTEL_COMPILER)
  18021. mg_snprintf(NULL,
  18022. NULL,
  18023. block,
  18024. sizeof(block),
  18025. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18026. eol,
  18027. (unsigned)__INTEL_COMPILER);
  18028. system_info_length += mg_str_append(&buffer, end, block);
  18029. #elif defined(__BORLANDC__)
  18030. mg_snprintf(NULL,
  18031. NULL,
  18032. block,
  18033. sizeof(block),
  18034. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18035. eol,
  18036. (unsigned)__BORLANDC__);
  18037. system_info_length += mg_str_append(&buffer, end, block);
  18038. #elif defined(__SUNPRO_C)
  18039. mg_snprintf(NULL,
  18040. NULL,
  18041. block,
  18042. sizeof(block),
  18043. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18044. eol,
  18045. (unsigned)__SUNPRO_C);
  18046. system_info_length += mg_str_append(&buffer, end, block);
  18047. #else
  18048. mg_snprintf(NULL,
  18049. NULL,
  18050. block,
  18051. sizeof(block),
  18052. ",%s\"compiler\" : \"other\"",
  18053. eol);
  18054. system_info_length += mg_str_append(&buffer, end, block);
  18055. #endif
  18056. }
  18057. /* Determine 32/64 bit data mode.
  18058. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18059. {
  18060. mg_snprintf(NULL,
  18061. NULL,
  18062. block,
  18063. sizeof(block),
  18064. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18065. "char:%u/%u, "
  18066. "ptr:%u, size:%u, time:%u\"",
  18067. eol,
  18068. (unsigned)sizeof(short),
  18069. (unsigned)sizeof(int),
  18070. (unsigned)sizeof(long),
  18071. (unsigned)sizeof(long long),
  18072. (unsigned)sizeof(float),
  18073. (unsigned)sizeof(double),
  18074. (unsigned)sizeof(long double),
  18075. (unsigned)sizeof(char),
  18076. (unsigned)sizeof(wchar_t),
  18077. (unsigned)sizeof(void *),
  18078. (unsigned)sizeof(size_t),
  18079. (unsigned)sizeof(time_t));
  18080. system_info_length += mg_str_append(&buffer, end, block);
  18081. }
  18082. /* Terminate string */
  18083. if (append_eoobj) {
  18084. strcat(append_eoobj, eoobj);
  18085. }
  18086. system_info_length += sizeof(eoobj) - 1;
  18087. return (int)system_info_length;
  18088. }
  18089. /* Get context information. It can be printed or stored by the caller.
  18090. * Return the size of available information. */
  18091. int
  18092. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18093. {
  18094. #if defined(USE_SERVER_STATS)
  18095. char *end, *append_eoobj = NULL, block[256];
  18096. size_t context_info_length = 0;
  18097. #if defined(_WIN32)
  18098. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18099. #else
  18100. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18101. #endif
  18102. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18103. if ((buffer == NULL) || (buflen < 1)) {
  18104. buflen = 0;
  18105. end = buffer;
  18106. } else {
  18107. *buffer = 0;
  18108. end = buffer + buflen;
  18109. }
  18110. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18111. /* has enough space to append eoobj */
  18112. append_eoobj = buffer;
  18113. end -= sizeof(eoobj) - 1;
  18114. }
  18115. context_info_length += mg_str_append(&buffer, end, "{");
  18116. if (ms) { /* <-- should be always true */
  18117. /* Memory information */
  18118. int blockCount = (int)ms->blockCount;
  18119. int64_t totalMemUsed = ms->totalMemUsed;
  18120. int64_t maxMemUsed = ms->maxMemUsed;
  18121. if (totalMemUsed > maxMemUsed) {
  18122. maxMemUsed = totalMemUsed;
  18123. }
  18124. mg_snprintf(NULL,
  18125. NULL,
  18126. block,
  18127. sizeof(block),
  18128. "%s\"memory\" : {%s"
  18129. "\"blocks\" : %i,%s"
  18130. "\"used\" : %" INT64_FMT ",%s"
  18131. "\"maxUsed\" : %" INT64_FMT "%s"
  18132. "}",
  18133. eol,
  18134. eol,
  18135. blockCount,
  18136. eol,
  18137. totalMemUsed,
  18138. eol,
  18139. maxMemUsed,
  18140. eol);
  18141. context_info_length += mg_str_append(&buffer, end, block);
  18142. }
  18143. if (ctx) {
  18144. /* Declare all variables at begin of the block, to comply
  18145. * with old C standards. */
  18146. char start_time_str[64] = {0};
  18147. char now_str[64] = {0};
  18148. time_t start_time = ctx->start_time;
  18149. time_t now = time(NULL);
  18150. int64_t total_data_read, total_data_written;
  18151. int active_connections = (int)ctx->active_connections;
  18152. int max_active_connections = (int)ctx->max_active_connections;
  18153. int total_connections = (int)ctx->total_connections;
  18154. if (active_connections > max_active_connections) {
  18155. max_active_connections = active_connections;
  18156. }
  18157. if (active_connections > total_connections) {
  18158. total_connections = active_connections;
  18159. }
  18160. /* Connections information */
  18161. mg_snprintf(NULL,
  18162. NULL,
  18163. block,
  18164. sizeof(block),
  18165. ",%s\"connections\" : {%s"
  18166. "\"active\" : %i,%s"
  18167. "\"maxActive\" : %i,%s"
  18168. "\"total\" : %i%s"
  18169. "}",
  18170. eol,
  18171. eol,
  18172. active_connections,
  18173. eol,
  18174. max_active_connections,
  18175. eol,
  18176. total_connections,
  18177. eol);
  18178. context_info_length += mg_str_append(&buffer, end, block);
  18179. /* Queue information */
  18180. #if !defined(ALTERNATIVE_QUEUE)
  18181. mg_snprintf(NULL,
  18182. NULL,
  18183. block,
  18184. sizeof(block),
  18185. ",%s\"queue\" : {%s"
  18186. "\"length\" : %i,%s"
  18187. "\"filled\" : %i,%s"
  18188. "\"maxFilled\" : %i,%s"
  18189. "\"full\" : %s%s"
  18190. "}",
  18191. eol,
  18192. eol,
  18193. ctx->sq_size,
  18194. eol,
  18195. ctx->sq_head - ctx->sq_tail,
  18196. eol,
  18197. ctx->sq_max_fill,
  18198. eol,
  18199. (ctx->sq_blocked ? "true" : "false"),
  18200. eol);
  18201. context_info_length += mg_str_append(&buffer, end, block);
  18202. #endif
  18203. /* Requests information */
  18204. mg_snprintf(NULL,
  18205. NULL,
  18206. block,
  18207. sizeof(block),
  18208. ",%s\"requests\" : {%s"
  18209. "\"total\" : %lu%s"
  18210. "}",
  18211. eol,
  18212. eol,
  18213. (unsigned long)ctx->total_requests,
  18214. eol);
  18215. context_info_length += mg_str_append(&buffer, end, block);
  18216. /* Data information */
  18217. total_data_read =
  18218. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18219. total_data_written =
  18220. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18221. mg_snprintf(NULL,
  18222. NULL,
  18223. block,
  18224. sizeof(block),
  18225. ",%s\"data\" : {%s"
  18226. "\"read\" : %" INT64_FMT ",%s"
  18227. "\"written\" : %" INT64_FMT "%s"
  18228. "}",
  18229. eol,
  18230. eol,
  18231. total_data_read,
  18232. eol,
  18233. total_data_written,
  18234. eol);
  18235. context_info_length += mg_str_append(&buffer, end, block);
  18236. /* Execution time information */
  18237. gmt_time_string(start_time_str,
  18238. sizeof(start_time_str) - 1,
  18239. &start_time);
  18240. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18241. mg_snprintf(NULL,
  18242. NULL,
  18243. block,
  18244. sizeof(block),
  18245. ",%s\"time\" : {%s"
  18246. "\"uptime\" : %.0f,%s"
  18247. "\"start\" : \"%s\",%s"
  18248. "\"now\" : \"%s\"%s"
  18249. "}",
  18250. eol,
  18251. eol,
  18252. difftime(now, start_time),
  18253. eol,
  18254. start_time_str,
  18255. eol,
  18256. now_str,
  18257. eol);
  18258. context_info_length += mg_str_append(&buffer, end, block);
  18259. }
  18260. /* Terminate string */
  18261. if (append_eoobj) {
  18262. strcat(append_eoobj, eoobj);
  18263. }
  18264. context_info_length += sizeof(eoobj) - 1;
  18265. return (int)context_info_length;
  18266. #else
  18267. (void)ctx;
  18268. if ((buffer != NULL) && (buflen > 0)) {
  18269. *buffer = 0;
  18270. }
  18271. return 0;
  18272. #endif
  18273. }
  18274. void
  18275. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18276. {
  18277. /* https://github.com/civetweb/civetweb/issues/727 */
  18278. if (conn != NULL) {
  18279. conn->must_close = 1;
  18280. }
  18281. }
  18282. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18283. /* Get connection information. It can be printed or stored by the caller.
  18284. * Return the size of available information. */
  18285. int
  18286. mg_get_connection_info(const struct mg_context *ctx,
  18287. int idx,
  18288. char *buffer,
  18289. int buflen)
  18290. {
  18291. const struct mg_connection *conn;
  18292. const struct mg_request_info *ri;
  18293. char *end, *append_eoobj = NULL, block[256];
  18294. size_t connection_info_length = 0;
  18295. int state = 0;
  18296. const char *state_str = "unknown";
  18297. #if defined(_WIN32)
  18298. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18299. #else
  18300. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18301. #endif
  18302. if ((buffer == NULL) || (buflen < 1)) {
  18303. buflen = 0;
  18304. end = buffer;
  18305. } else {
  18306. *buffer = 0;
  18307. end = buffer + buflen;
  18308. }
  18309. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18310. /* has enough space to append eoobj */
  18311. append_eoobj = buffer;
  18312. end -= sizeof(eoobj) - 1;
  18313. }
  18314. if ((ctx == NULL) || (idx < 0)) {
  18315. /* Parameter error */
  18316. return 0;
  18317. }
  18318. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18319. /* Out of range */
  18320. return 0;
  18321. }
  18322. /* Take connection [idx]. This connection is not locked in
  18323. * any way, so some other thread might use it. */
  18324. conn = (ctx->worker_connections) + idx;
  18325. /* Initialize output string */
  18326. connection_info_length += mg_str_append(&buffer, end, "{");
  18327. /* Init variables */
  18328. ri = &(conn->request_info);
  18329. #if defined(USE_SERVER_STATS)
  18330. state = conn->conn_state;
  18331. /* State as string */
  18332. switch (state) {
  18333. case 0:
  18334. state_str = "undefined";
  18335. break;
  18336. case 1:
  18337. state_str = "not used";
  18338. break;
  18339. case 2:
  18340. state_str = "init";
  18341. break;
  18342. case 3:
  18343. state_str = "ready";
  18344. break;
  18345. case 4:
  18346. state_str = "processing";
  18347. break;
  18348. case 5:
  18349. state_str = "processed";
  18350. break;
  18351. case 6:
  18352. state_str = "to close";
  18353. break;
  18354. case 7:
  18355. state_str = "closing";
  18356. break;
  18357. case 8:
  18358. state_str = "closed";
  18359. break;
  18360. case 9:
  18361. state_str = "done";
  18362. break;
  18363. }
  18364. #endif
  18365. /* Connection info */
  18366. if ((state >= 3) && (state < 9)) {
  18367. mg_snprintf(NULL,
  18368. NULL,
  18369. block,
  18370. sizeof(block),
  18371. "%s\"connection\" : {%s"
  18372. "\"remote\" : {%s"
  18373. "\"protocol\" : \"%s\",%s"
  18374. "\"addr\" : \"%s\",%s"
  18375. "\"port\" : %u%s"
  18376. "},%s"
  18377. "\"handled_requests\" : %u%s"
  18378. "}",
  18379. eol,
  18380. eol,
  18381. eol,
  18382. get_proto_name(conn),
  18383. eol,
  18384. ri->remote_addr,
  18385. eol,
  18386. ri->remote_port,
  18387. eol,
  18388. eol,
  18389. conn->handled_requests,
  18390. eol);
  18391. connection_info_length += mg_str_append(&buffer, end, block);
  18392. }
  18393. /* Request info */
  18394. if ((state >= 4) && (state < 6)) {
  18395. mg_snprintf(NULL,
  18396. NULL,
  18397. block,
  18398. sizeof(block),
  18399. "%s%s\"request_info\" : {%s"
  18400. "\"method\" : \"%s\",%s"
  18401. "\"uri\" : \"%s\",%s"
  18402. "\"query\" : %s%s%s%s"
  18403. "}",
  18404. (connection_info_length > 1 ? "," : ""),
  18405. eol,
  18406. eol,
  18407. ri->request_method,
  18408. eol,
  18409. ri->request_uri,
  18410. eol,
  18411. ri->query_string ? "\"" : "",
  18412. ri->query_string ? ri->query_string : "null",
  18413. ri->query_string ? "\"" : "",
  18414. eol);
  18415. connection_info_length += mg_str_append(&buffer, end, block);
  18416. }
  18417. /* Execution time information */
  18418. if ((state >= 2) && (state < 9)) {
  18419. char start_time_str[64] = {0};
  18420. char close_time_str[64] = {0};
  18421. time_t start_time = conn->conn_birth_time;
  18422. time_t close_time = 0;
  18423. double time_diff;
  18424. gmt_time_string(start_time_str,
  18425. sizeof(start_time_str) - 1,
  18426. &start_time);
  18427. #if defined(USE_SERVER_STATS)
  18428. close_time = conn->conn_close_time;
  18429. #endif
  18430. if (close_time != 0) {
  18431. time_diff = difftime(close_time, start_time);
  18432. gmt_time_string(close_time_str,
  18433. sizeof(close_time_str) - 1,
  18434. &close_time);
  18435. } else {
  18436. time_t now = time(NULL);
  18437. time_diff = difftime(now, start_time);
  18438. close_time_str[0] = 0; /* or use "now" ? */
  18439. }
  18440. mg_snprintf(NULL,
  18441. NULL,
  18442. block,
  18443. sizeof(block),
  18444. "%s%s\"time\" : {%s"
  18445. "\"uptime\" : %.0f,%s"
  18446. "\"start\" : \"%s\",%s"
  18447. "\"closed\" : \"%s\"%s"
  18448. "}",
  18449. (connection_info_length > 1 ? "," : ""),
  18450. eol,
  18451. eol,
  18452. time_diff,
  18453. eol,
  18454. start_time_str,
  18455. eol,
  18456. close_time_str,
  18457. eol);
  18458. connection_info_length += mg_str_append(&buffer, end, block);
  18459. }
  18460. /* Remote user name */
  18461. if ((ri->remote_user) && (state < 9)) {
  18462. mg_snprintf(NULL,
  18463. NULL,
  18464. block,
  18465. sizeof(block),
  18466. "%s%s\"user\" : {%s"
  18467. "\"name\" : \"%s\",%s"
  18468. "}",
  18469. (connection_info_length > 1 ? "," : ""),
  18470. eol,
  18471. eol,
  18472. ri->remote_user,
  18473. eol);
  18474. connection_info_length += mg_str_append(&buffer, end, block);
  18475. }
  18476. /* Data block */
  18477. if (state >= 3) {
  18478. mg_snprintf(NULL,
  18479. NULL,
  18480. block,
  18481. sizeof(block),
  18482. "%s%s\"data\" : {%s"
  18483. "\"read\" : %" INT64_FMT ",%s"
  18484. "\"written\" : %" INT64_FMT "%s"
  18485. "}",
  18486. (connection_info_length > 1 ? "," : ""),
  18487. eol,
  18488. eol,
  18489. conn->consumed_content,
  18490. eol,
  18491. conn->num_bytes_sent,
  18492. eol);
  18493. connection_info_length += mg_str_append(&buffer, end, block);
  18494. }
  18495. /* State */
  18496. mg_snprintf(NULL,
  18497. NULL,
  18498. block,
  18499. sizeof(block),
  18500. "%s%s\"state\" : \"%s\"",
  18501. (connection_info_length > 1 ? "," : ""),
  18502. eol,
  18503. state_str);
  18504. connection_info_length += mg_str_append(&buffer, end, block);
  18505. /* Terminate string */
  18506. if (append_eoobj) {
  18507. strcat(append_eoobj, eoobj);
  18508. }
  18509. connection_info_length += sizeof(eoobj) - 1;
  18510. return (int)connection_info_length;
  18511. }
  18512. #endif
  18513. /* Initialize this library. This function does not need to be thread safe.
  18514. */
  18515. unsigned
  18516. mg_init_library(unsigned features)
  18517. {
  18518. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18519. unsigned features_inited = features_to_init;
  18520. if (mg_init_library_called <= 0) {
  18521. /* Not initialized yet */
  18522. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18523. return 0;
  18524. }
  18525. }
  18526. mg_global_lock();
  18527. if (mg_init_library_called <= 0) {
  18528. #if defined(_WIN32)
  18529. int file_mutex_init = 1;
  18530. int wsa = 1;
  18531. #else
  18532. int mutexattr_init = 1;
  18533. #endif
  18534. int failed = 1;
  18535. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18536. if (key_create == 0) {
  18537. #if defined(_WIN32)
  18538. file_mutex_init =
  18539. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18540. if (file_mutex_init == 0) {
  18541. /* Start WinSock */
  18542. WSADATA data;
  18543. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18544. }
  18545. #else
  18546. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18547. if (mutexattr_init == 0) {
  18548. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18549. PTHREAD_MUTEX_RECURSIVE);
  18550. }
  18551. #endif
  18552. }
  18553. if (failed) {
  18554. #if defined(_WIN32)
  18555. if (wsa == 0) {
  18556. (void)WSACleanup();
  18557. }
  18558. if (file_mutex_init == 0) {
  18559. (void)pthread_mutex_destroy(&global_log_file_lock);
  18560. }
  18561. #else
  18562. if (mutexattr_init == 0) {
  18563. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18564. }
  18565. #endif
  18566. if (key_create == 0) {
  18567. (void)pthread_key_delete(sTlsKey);
  18568. }
  18569. mg_global_unlock();
  18570. (void)pthread_mutex_destroy(&global_lock_mutex);
  18571. return 0;
  18572. }
  18573. #if defined(USE_LUA)
  18574. lua_init_optional_libraries();
  18575. #endif
  18576. }
  18577. mg_global_unlock();
  18578. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  18579. || defined(OPENSSL_API_3_0)) \
  18580. && !defined(NO_SSL)
  18581. if (features_to_init & MG_FEATURES_SSL) {
  18582. if (!mg_openssl_initialized) {
  18583. char ebuf[128];
  18584. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  18585. mg_openssl_initialized = 1;
  18586. } else {
  18587. (void)ebuf;
  18588. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18589. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18590. }
  18591. } else {
  18592. /* ssl already initialized */
  18593. }
  18594. }
  18595. #endif
  18596. mg_global_lock();
  18597. if (mg_init_library_called <= 0) {
  18598. mg_init_library_called = 1;
  18599. } else {
  18600. mg_init_library_called++;
  18601. }
  18602. mg_global_unlock();
  18603. return features_inited;
  18604. }
  18605. /* Un-initialize this library. */
  18606. unsigned
  18607. mg_exit_library(void)
  18608. {
  18609. if (mg_init_library_called <= 0) {
  18610. return 0;
  18611. }
  18612. mg_global_lock();
  18613. mg_init_library_called--;
  18614. if (mg_init_library_called == 0) {
  18615. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  18616. if (mg_openssl_initialized) {
  18617. uninitialize_openssl();
  18618. mg_openssl_initialized = 0;
  18619. }
  18620. #endif
  18621. #if defined(_WIN32)
  18622. (void)WSACleanup();
  18623. (void)pthread_mutex_destroy(&global_log_file_lock);
  18624. #else
  18625. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18626. #endif
  18627. (void)pthread_key_delete(sTlsKey);
  18628. #if defined(USE_LUA)
  18629. lua_exit_optional_libraries();
  18630. #endif
  18631. mg_global_unlock();
  18632. (void)pthread_mutex_destroy(&global_lock_mutex);
  18633. return 1;
  18634. }
  18635. mg_global_unlock();
  18636. return 1;
  18637. }
  18638. /* End of civetweb.c */